from app import create_app
from app.config import Config
import os

try:
    # Validate FFmpeg paths before creating app
    Config.validate_paths()
    app = create_app()
except Exception as e:
    print(f"Error starting application: {str(e)}")
    raise

if __name__ == '__main__':
    cert_path = os.path.join(os.path.dirname(__file__), 'certs', 'cert.pem')
    key_path = os.path.join(os.path.dirname(__file__), 'certs', 'key.pem')
    
    if not os.path.exists(cert_path) or not os.path.exists(key_path):
        print("SSL certificates not found. Please run generate_cert.py first.")
        exit(1)
    
    print("🔐 HTTPS Server with Waitress (Production-Ready)")
    print("📱 Mobile Access URLs:")
    print(f"   • From this computer: https://localhost:5003")
    print(f"   • From mobile/other devices: https://192.168.234.162:5003")
    print(f"   • Test page: https://192.168.234.162:5003/mobile-test")
    print()
    print("⚠️  Mobile browsers will show a security warning for self-signed certificates.")
    print("   Click 'Advanced' → 'Proceed to site (unsafe)' to continue.")
    print()
    print("🎤 HTTPS is required for microphone access on mobile devices.")
    print("🚀 Using Waitress WSGI server for better SSL handling...")
    
    try:
        from waitress import serve
        serve(
            app,
            host='0.0.0.0',
            port=5003,
            url_scheme='https',
            ssl_cert=cert_path,
            ssl_key=key_path,
            threads=6,
            connection_limit=200,
            cleanup_interval=10,
            channel_timeout=120
        )
    except ImportError:
        print("⚠️  Waitress not installed. Installing...")
        import subprocess
        import sys
        subprocess.check_call([sys.executable, "-m", "pip", "install", "waitress"])
        
        print("✅ Waitress installed. Starting server...")
        from waitress import serve
        serve(
            app,
            host='0.0.0.0',
            port=5003,
            url_scheme='https',
            ssl_cert=cert_path,
            ssl_key=key_path,
            threads=6,
            connection_limit=200,
            cleanup_interval=10,
            channel_timeout=120
        )