"""
Alternative Solution: HTTP + ngrok for Real SSL

This approach runs your Flask app on HTTP locally,
then uses ngrok to provide real HTTPS with valid certificates.
"""

from app import create_app
from app.config import Config
import subprocess
import sys
import os
import time
import threading

def install_ngrok():
    """Instructions for installing ngrok"""
    print("📥 To use this solution, you need ngrok:")
    print("1. Go to https://ngrok.com/")
    print("2. Sign up for a free account")
    print("3. Download ngrok for Windows")
    print("4. Extract ngrok.exe to this folder")
    print("5. Run this script again")
    print()
    input("Press Enter when ngrok.exe is in this folder...")

def start_ngrok():
    """Start ngrok tunnel"""
    print("🚀 Starting ngrok tunnel...")
    try:
        # Try to use ngrok from system path
        ngrok_command = "ngrok"
        
        print("� Looking for ngrok in system path...")
        
        # Start ngrok in background
        process = subprocess.Popen(
            [ngrok_command, "http", "5003"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
        
        # Wait a moment for ngrok to start
        time.sleep(3)
        
        print("✅ ngrok tunnel started!")
        print("🌐 Check the ngrok dashboard at: http://localhost:4040")
        print("📱 Use the HTTPS URL shown in the dashboard for mobile access")
        print("🎤 The HTTPS URL will work perfectly with microphone on mobile!")
        
        return True
    except Exception as e:
        print(f"❌ Error starting ngrok: {e}")
        return False

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__':
    print("🔄 HTTP + ngrok Solution")
    print("This provides real HTTPS certificates that mobile browsers trust!")
    print()
    
    # Start ngrok in a separate thread
    ngrok_thread = threading.Thread(target=start_ngrok)
    ngrok_thread.daemon = True
    ngrok_thread.start()
    
    print("🌐 Starting Flask app on HTTP (ngrok will provide HTTPS)...")
    print("📱 Once ngrok starts, use the HTTPS URL it provides")
    print()
    
    # Start Flask app on HTTP
    app.run(
        debug=True,
        host='0.0.0.0',
        port=5003,
        # No SSL - ngrok handles it
    )