import argparse
import os
import sys
from audio_io import AudioIO
from windows_audio import WindowsAudioManager
import sounddevice as sd
from metadata_manager import MetaDataManager
from settings import SettingsManager

from flask import Flask
from flask_cors import CORS

from routes.recording import recording_bp
from routes.device import device_bp
from routes.metadata import metadata_bp
from routes.settings import settings_bp
from flask_socketio import SocketIO, emit
import threading

app = Flask(__name__)
CORS(app)
socketio = SocketIO(app, cors_allowed_origins="*", logger=True, engineio_logger=True, async_mode='eventlet')

@socketio.on('connect')
def handle_connect():
    print("Client connected")
    emit('full_data', MetaDataManager().collections)

@socketio.on('record_clip')
def record_clip():
    io = AudioIO()
    io.save_last_n_seconds();

@socketio.on('play_clip')
def play_clip(data):
    io = AudioIO()
    print(f"Received play_clip event with data: {data}")
    if data:
        io.play_clip(data)


def main():
    # Create argument parser
    parser = argparse.ArgumentParser(description='Audio Recording Service')
    
    # OSC port argument
    parser.add_argument('--osc-port', 
                        type=int, 
                        help='OSC server port number',
                        default=5010)
    
    # Parse arguments
    args = parser.parse_args()
    audio_manager = WindowsAudioManager()
    settings = SettingsManager()
    meta = MetaDataManager()

    
    
    # Ensure save path exists
    os.makedirs(settings.get_settings('save_path'), exist_ok=True)


    io = AudioIO()
    io.start_recording()

    # settings.socket = socketio
    io.socket = socketio
    meta.socket = socketio
    
    # Register blueprints
    app.register_blueprint(recording_bp)
    app.register_blueprint(device_bp)
    app.register_blueprint(metadata_bp)
    app.register_blueprint(settings_bp)
    print(f"Starting Flask server on port {settings.get_settings('http_port')}")
    # app.run(host='127.0.0.1', port=settings.get_settings('http_port'), debug=False, use_reloader=True)
    socketio.run(app, host='127.0.0.1', port=settings.get_settings('http_port'), debug=False, use_reloader=False, allow_unsafe_werkzeug=True)


    
    # Run the OSC server
    # try:
    #     print(f"Starting OSC Recording Server on port {args.osc_port}")
    #     # osc_server.run_server()
    # except KeyboardInterrupt:
    #     print("\nServer stopped by user.")
    # except Exception as e:
    #     print(f"Error starting server: {e}")
    #     sys.exit(1)


if __name__ == "__main__":
    main()