import subprocess
import time
import json
import os
import re
import sys
import threading

def start_cf():
    print("Starting cloudflared on port 8001...")
    
    cf_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'cloudflared')
    if not os.path.exists(cf_path):
        print(f"Error: {cf_path} not found.")
        sys.exit(1)

    # Ensure executable permissions
    os.chmod(cf_path, 0o755)

    process = subprocess.Popen(
        [cf_path, 'tunnel', '--url', 'http://localhost:8001'],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True
    )
    
    public_url = None
    url_found = threading.Event()

    def read_stderr():
        nonlocal public_url
        for line in iter(process.stderr.readline, ''):
            if not line:
                break
            print(line.strip())
            if not url_found.is_set():
                match = re.search(r'(https://[a-zA-Z0-9-]+\.trycloudflare\.com)', line)
                if match:
                    public_url = match.group(1)
                    url_found.set()

    t = threading.Thread(target=read_stderr)
    t.daemon = True
    t.start()
    
    if url_found.wait(timeout=20):
        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 = {
            "cloudflare_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"\n✅ Success! cloudflared is running.")
        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 cloudflared.")
    else:
        print("\n❌ Could not find Cloudflare Tunnel URL within timeout.")
        process.terminate()
        sys.exit(1)

    try:
        process.wait()
    except KeyboardInterrupt:
        print("\nStopping cloudflared...")
        process.terminate()
        process.wait()

if __name__ == "__main__":
    start_cf()
