import subprocess
import time
import json
import urllib.request
import os
import sys

def start_ngrok():
    print("Starting ngrok on port 8000...")
    try:
        process = subprocess.Popen(['ngrok', 'http', '8000'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    except FileNotFoundError:
        print("Error: 'ngrok' command not found. Please install ngrok from https://ngrok.com/download")
        sys.exit(1)
    
    # Wait for ngrok to initialize and open the tunnel
    time.sleep(3)
    
    try:
        req = urllib.request.Request("http://127.0.0.1:4040/api/tunnels")
        with urllib.request.urlopen(req) as response:
            data = json.loads(response.read().decode('utf-8'))
            tunnels = data.get("tunnels", [])
            public_url = None
            for t in tunnels:
                if t.get("proto") == "https":
                    public_url = t.get("public_url")
                    break
            
            if public_url:
                webhook_url = f"{public_url}/api/restaurants/whatsapp/webhook/"
                json_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'whatsapp_link.json')
                
                output_data = {
                    "ngrok_public_url": public_url,
                    "twilio_webhook_url": webhook_url
                }
                
                with open(json_path, 'w') as f:
                    json.dump(output_data, f, indent=4)
                
                print(f"✅ Success! ngrok is running in the background.")
                print(f"🔗 Tunnel URL: {public_url}")
                print(f"🔗 Webhook URL: {webhook_url}")
                print(f"📁 Saved automatically to: {json_path}")
                print("\nPress Ctrl+C to stop ngrok.")
            else:
                print("❌ Could not find an active HTTPS tunnel. Is ngrok authenticated?")
    except Exception as e:
        print(f"❌ Error connecting to ngrok local API: {e}")
        print("Make sure ngrok is properly installed and authenticated.")

    try:
        # Keep the script running to keep the ngrok process alive
        process.wait()
    except KeyboardInterrupt:
        print("\nStopping ngrok...")
        process.terminate()

if __name__ == "__main__":
    start_ngrok()
