#!/usr/bin/env python3
"""
Clean restart of ngrok with proper configuration
Fixes ERR_NGROK_3200 by ensuring fresh tunnel
"""

import subprocess
import time
import requests
import json
import sys

def kill_ngrok():
    """Kill all ngrok processes"""
    print("Killing all ngrok processes...")
    subprocess.run(['taskkill', '/IM', 'ngrok.exe', '/F'], 
                   stderr=subprocess.DEVNULL, 
                   stdout=subprocess.DEVNULL)
    time.sleep(2)

def start_ngrok():
    """Start ngrok with proper settings"""
    print("Starting ngrok tunnel...")
    # Start ngrok in background
    subprocess.Popen('ngrok http 5000 --log=stdout', 
                    shell=True,
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL)
    print("Waiting for tunnel to establish...")
    time.sleep(8)

def get_tunnel_url():
    """Get the active tunnel URL"""
    try:
        response = requests.get('http://127.0.0.1:4040/api/tunnels', timeout=5)
        data = response.json()
        tunnels = data.get('tunnels', [])
        
        if not tunnels:
            return None
        
        # Get HTTPS tunnel
        for tunnel in tunnels:
            if tunnel.get('proto') == 'https':
                return tunnel.get('public_url')
        
        # Fallback to first tunnel
        return tunnels[0].get('public_url')
    except Exception as e:
        print(f"Error getting tunnel URL: {e}")
        return None

def update_credentials(new_url):
    """Update credentials.json with new URL"""
    try:
        with open('credentials.json', 'r') as f:
            creds = json.load(f)
        
        callback_url = f"{new_url}/oauth2callback"
        creds['web']['redirect_uris'] = [callback_url]
        creds['web']['javascript_origins'] = [new_url]
        
        with open('credentials.json', 'w') as f:
            json.dump(creds, f, indent=2)
        
        print(f"✓ Updated credentials.json")
        print(f"  Redirect URI: {callback_url}")
        return True
    except Exception as e:
        print(f"✗ Failed to update credentials: {e}")
        return False

def verify_flask():
    """Check if Flask is running"""
    try:
        response = requests.get('http://localhost:5000', timeout=5)
        return True
    except:
        return False

def main():
    print("="*70)
    print("  NGROK CLEAN RESTART - ERR_NGROK_3200 FIX")
    print("="*70)
    print()
    
    # Step 1: Verify Flask
    print("[1/5] Checking Flask...")
    if not verify_flask():
        print("✗ Flask is not running on localhost:5000")
        print("  Please start Flask first: python app.py")
        sys.exit(1)
    print("✓ Flask is running")
    
    # Step 2: Kill ngrok
    print("\n[2/5] Stopping existing ngrok...")
    kill_ngrok()
    print("✓ Stopped")
    
    # Step 3: Start fresh ngrok
    print("\n[3/5] Starting fresh ngrok tunnel...")
    start_ngrok()
    
    # Step 4: Get new URL
    print("\n[4/5] Retrieving tunnel URL...")
    url = get_tunnel_url()
    if not url:
        print("✗ Failed to get tunnel URL")
        print("  ngrok might not be installed or authenticated")
        print("  Try: ngrok config add-authtoken YOUR_TOKEN")
        sys.exit(1)
    print(f"✓ Tunnel URL: {url}")
    
    # Step 5: Update credentials
    print("\n[5/5] Updating OAuth credentials...")
    if not update_credentials(url):
        sys.exit(1)
    
    print("\n" + "="*70)
    print("  SUCCESS!")
    print("="*70)
    print(f"\nYour app is now available at:")
    print(f"  {url}")
    print()
    print("IMPORTANT: Update Google Cloud Console")
    print("Go to: https://console.cloud.google.com/apis/credentials")
    print("Update your OAuth 2.0 Client ID with:")
    print(f"  Authorized redirect URIs: {url}/oauth2callback")
    print(f"  Authorized JavaScript origins: {url}")
    print()
    print("Then:")
    print("  1. Clear your browser cache (Ctrl+Shift+Delete)")
    print("  2. Close all browser tabs")
    print("  3. Visit the URL above")
    print()

if __name__ == '__main__':
    main()
