import argparse
import os
import sys
from audio_recorder import AudioRecorder
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
import threading

app = Flask(__name__)
CORS(app)
# socketio = SocketIO(app, cors_allowed_origins="*")
# CORS(socketio)

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()
    
    # Ensure save path exists
    os.makedirs(settings.get_settings('save_path'), exist_ok=True)


    # Register blueprints
    app.register_blueprint(recording_bp)
    app.register_blueprint(device_bp)
    app.register_blueprint(metadata_bp)
    app.register_blueprint(settings_bp)
    app.run(host='127.0.0.1', port=args.osc_port, debug=False, use_reloader=True)
    # socketio.run(app, host='127.0.0.1', port=args.osc_port, debug=False, use_reloader=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()