import os
import sys
import threading
from django.apps import AppConfig


def _run_ngrok_in_background():
    try:
        import subprocess
        import time
        import json
        import urllib.request
        from django.conf import settings
        
        # Check if ngrok API is already responding on 4040
        already_running = False
        try:
            req = urllib.request.Request("http://127.0.0.1:4040/api/tunnels")
            with urllib.request.urlopen(req) as response:
                already_running = True
        except Exception:
            pass

        # If not, start ngrok
        if not already_running:
            ngrok_path = os.path.join(os.path.dirname(sys.executable), 'ngrok')
            if not os.path.exists(ngrok_path):
                ngrok_path = 'ngrok' # fallback to PATH
            subprocess.Popen([ngrok_path, 'http', '8000'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            time.sleep(3)  # Give ngrok time to open the tunnel
        
        # Fetch the tunnel URL
        req = urllib.request.Request("http://127.0.0.1:4040/api/tunnels")
        try:
            with urllib.request.urlopen(req) as response:
                data = json.loads(response.read().decode('utf-8'))
        except Exception:
            print("\n[HotelFinder] ❌ Ngrok failed to start or crashed instantly.")
            print("[HotelFinder] 👉 Did you add your auth token? Run: ngrok config add-authtoken <your-token>\n")
            return
            tunnels = data.get("tunnels", [])
            public_url = next((t.get("public_url") for t in tunnels if t.get("proto") == "https"), None)
            
            if public_url:
                webhook_url = f"{public_url}/api/restaurants/whatsapp/webhook/"
                json_path = os.path.join(settings.BASE_DIR, 'whatsapp_link.json')
                
                with open(json_path, 'w') as f:
                    json.dump({
                        "ngrok_public_url": public_url,
                        "twilio_webhook_url": webhook_url
                    }, f, indent=4)
                
                print(f"\n[HotelFinder] ✅ Ngrok running! URL saved to whatsapp_link.json: {webhook_url}\n")
    except Exception as e:
        print(f"\n[HotelFinder] ⚠️ Ngrok auto-start skipped: {e}")


class RestaurantConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'restaurant'

    def ready(self):
        import restaurant.signals  # noqa: F401

        # Only run ngrok when 'runserver' is used, and only inside the main reloader thread
        if 'runserver' in sys.argv and os.environ.get('RUN_MAIN') == 'true':
            t = threading.Thread(target=_run_ngrok_in_background)
            t.daemon = True
            t.start()
