#!/usr/bin/env python3
"""
HTTPS server for serving web_client.html with SSL
Allows microphone access from remote browsers
"""

import http.server
import socketserver
import ssl
import os
import subprocess
import sys

# Configuration
PORT = 8080  # Using port 8080 for HTTPS
HOST = "0.0.0.0"
DIRECTORY = os.path.dirname(os.path.abspath(__file__))

# Certificate files
CERT_FILE = "server.crt"
KEY_FILE = "server.key"

class MyHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)
    
    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', '*')
        super().end_headers()

def generate_self_signed_cert():
    """Generate self-signed certificate if it doesn't exist"""
    if os.path.exists(CERT_FILE) and os.path.exists(KEY_FILE):
        print(f"✅ Using existing certificate: {CERT_FILE}")
        return
    
    print("🔐 Generating self-signed certificate...")
    
    # Generate certificate valid for 1 year
    cmd = [
        "openssl", "req", "-x509", "-newkey", "rsa:4096",
        "-keyout", KEY_FILE, "-out", CERT_FILE,
        "-days", "365", "-nodes",
        "-subj", "/CN=10.2.56.217"
    ]
    
    try:
        subprocess.run(cmd, check=True, capture_output=True)
        print(f"✅ Certificate generated: {CERT_FILE}, {KEY_FILE}")
    except subprocess.CalledProcessError as e:
        print(f"❌ Error generating certificate: {e.stderr.decode()}")
        print("\nPlease install openssl:")
        print("  Ubuntu/Debian: sudo apt-get install openssl")
        print("  Mac: brew install openssl")
        print("  Windows: https://slproweb.com/products/Win32OpenSSL.html")
        sys.exit(1)
    except FileNotFoundError:
        print("❌ openssl not found!")
        print("\nPlease install openssl:")
        print("  Ubuntu/Debian: sudo apt-get install openssl")
        print("  Mac: brew install openssl")
        print("  Windows: https://slproweb.com/products/Win32OpenSSL.html")
        sys.exit(1)

def main():
    # Generate certificate if needed
    generate_self_signed_cert()
    
    # Create SSL context
    context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    context.load_cert_chain(CERT_FILE, KEY_FILE)
    
    # Allow socket reuse
    socketserver.TCPServer.allow_reuse_address = True
    
    # Create HTTPS server
    with socketserver.TCPServer((HOST, PORT), MyHTTPRequestHandler) as httpd:
        httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
        
        print("="*60)
        print("🔒 HTTPS Server running")
        print("="*60)
        print(f"   Local:  https://localhost:{PORT}/web_client.html")
        print(f"   Remote: https://10.2.56.217:{PORT}/web_client.html")
        print("="*60)
        print("\n⚠️  Browser will show certificate warning")
        print("   Click 'Advanced' → 'Proceed to 10.2.56.217 (unsafe)'")
        print("\n   This is normal for self-signed certificates")
        print("="*60)
        print("\n   Press Ctrl+C to stop\n")
        
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\n\n🛑 Server stopped")

if __name__ == "__main__":
    main()
