#!/usr/bin/env python3
"""
Quick Fix for ERR_NGROK_3200 and ngrok-related errors
Performs automatic repairs and restarts
"""

import subprocess
import time
import sys
import os
import json
import requests

def print_section(title):
    print("\n" + "="*70)
    print(f"  {title}")
    print("="*70)

def fix_1_kill_and_restart_ngrok():
    """Fix 1: Force restart ngrok"""
    print_section("FIX 1: Force Restart ngrok")
    print("[1/3] Killing existing ngrok process...")
    subprocess.run(['taskkill', '/IM', 'ngrok.exe', '/F'], 
                   stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
    time.sleep(2)
    
    print("[2/3] Starting fresh ngrok tunnel...")
    subprocess.Popen('ngrok http 5000', shell=True, 
                    stdout=subprocess.DEVNULL, 
                    stderr=subprocess.DEVNULL)
    time.sleep(5)
    
    print("[3/3] Verifying ngrok is running...")
    try:
        response = requests.get('http://127.0.0.1:4040/api/tunnels', timeout=5)
        if response.status_code == 200:
            tunnels = response.json().get('tunnels', [])
            if tunnels:
                url = tunnels[0].get('public_url', 'unknown')
                print(f"✓ ngrok restarted successfully")
                print(f"  Public URL: {url}")
                return url
    except:
        pass
    print("✗ Failed to restart ngrok")
    return None

def fix_2_sync_credentials(ngrok_url=None):
    """Fix 2: Sync credentials.json with current ngrok URL"""
    print_section("FIX 2: Sync OAuth Credentials")
    
    if not ngrok_url:
        try:
            response = requests.get('http://127.0.0.1:4040/api/tunnels', timeout=5)
            tunnels = response.json().get('tunnels', [])
            if tunnels:
                ngrok_url = tunnels[0].get('public_url')
        except:
            pass
    
    if not ngrok_url:
        print("✗ Could not determine ngrok URL")
        return False
    
    try:
        with open('credentials.json', 'r') as f:
            creds = json.load(f)
        
        old_uri = creds['web']['redirect_uris'][0]
        new_uri = f"{ngrok_url}/oauth2callback"
        
        if old_uri == new_uri:
            print(f"✓ Credentials already synchronized")
            print(f"  URI: {new_uri}")
            return True
        
        print(f"[1/2] Updating redirect URI...")
        print(f"  Old: {old_uri}")
        print(f"  New: {new_uri}")
        
        creds['web']['redirect_uris'][0] = new_uri
        
        with open('credentials.json', 'w') as f:
            json.dump(creds, f, indent=2)
        
        print(f"[2/2] Verifying update...")
        with open('credentials.json', 'r') as f:
            verify_creds = json.load(f)
        
        if verify_creds['web']['redirect_uris'][0] == new_uri:
            print(f"✓ Credentials synchronized successfully")
            return True
        else:
            print("✗ Credentials sync verification failed")
            return False
    
    except FileNotFoundError:
        print("✗ credentials.json not found")
        return False
    except Exception as e:
        print(f"✗ Error: {e}")
        return False

def fix_3_restart_flask():
    """Fix 3: Restart Flask if needed"""
    print_section("FIX 3: Restart Flask Application")
    
    print("[1/2] Checking Flask status...")
    try:
        response = requests.get('http://localhost:5000', timeout=5)
        print(f"✓ Flask is running (HTTP {response.status_code})")
        print("  No restart needed")
        return True
    except:
        print("✗ Flask is not responding")
        print("[2/2] Attempting to restart Flask...")
        print("  NOTE: You'll need to manually restart Flask")
        print("  Command: python app.py")
        return False

def fix_4_clear_browser_cache():
    """Fix 4: Provide instructions for clearing browser cache"""
    print_section("FIX 4: Browser Cache Issues")
    print("ERR_NGROK_3200 can be caused by browser caching issues.\n")
    print("Clear your browser cache:")
    print("  Chrome/Edge: Ctrl+Shift+Delete and clear 'All time'")
    print("  Firefox: Ctrl+Shift+Delete and clear 'Everything'")
    print("  Safari: Develop menu → Empty Web Caches\n")
    print("Then try accessing: https://gawsy-gregg-overrudely.ngrok-free.dev")

def fix_5_check_ngrok_rate_limit():
    """Fix 5: Check ngrok account status"""
    print_section("FIX 5: Check ngrok Account & Rate Limiting")
    print("If ERR_NGROK_3200 persists, it might be:")
    print("  1. ngrok free tier rate limiting")
    print("  2. Account suspension")
    print("  3. Network firewall blocking\n")
    print("Solutions:")
    print("  - Try: ngrok http --host-header=rewrite 5000")
    print("  - Check ngrok account: https://dashboard.ngrok.com")
    print("  - Check network/firewall settings")

def main():
    print("\n" + "="*70)
    print("  ERR_NGROK_3200 - AUTO FIX TOOL")
    print("="*70)
    
    success_count = 0
    
    # Run fixes in order
    ngrok_url = fix_1_kill_and_restart_ngrok()
    if ngrok_url:
        success_count += 1
    
    if fix_2_sync_credentials(ngrok_url):
        success_count += 1
    
    if fix_3_restart_flask():
        success_count += 1
    
    fix_4_clear_browser_cache()
    fix_5_check_ngrok_rate_limit()
    
    # Summary
    print_section("SUMMARY")
    print(f"✓ {success_count}/3 critical fixes applied successfully\n")
    
    if success_count == 3:
        print("✓ All systems restored!")
        print("\nNext steps:")
        print("  1. Clear your browser cache (see Fix 4)")
        print("  2. Visit: https://gawsy-gregg-overrudely.ngrok-free.dev")
        print("  3. Try logging in again")
        sys.exit(0)
    else:
        print("⚠ Some issues remain. Check the output above for details.")
        print("If ERR_NGROK_3200 persists, see Fix 5 for account troubleshooting.")
        sys.exit(1)

if __name__ == '__main__':
    main()
