"""
Automatically fetch the current ngrok public URL and update credentials.json
Run this after starting ngrok to sync the redirect URI
"""

import json
import requests
import time
import sys

def get_ngrok_url():
    """Fetch current ngrok public URL from local API"""
    try:
        # ngrok exposes a local API at http://127.0.0.1:4040/api/tunnels
        response = requests.get('http://127.0.0.1:4040/api/tunnels', timeout=5)
        response.raise_for_status()
        
        tunnels = response.json().get('tunnels', [])
        
        for tunnel in tunnels:
            if 'https' in tunnel.get('proto', ''):
                public_url = tunnel.get('public_url')
                if public_url:
                    return public_url
        
        print("[ERROR] No HTTPS tunnel found in ngrok")
        return None
        
    except requests.exceptions.ConnectionError:
        print("[ERROR] Cannot connect to ngrok API at http://127.0.0.1:4040")
        print("        Make sure ngrok is running: ngrok http 5000")
        return None
    except Exception as e:
        print(f"[ERROR] Failed to fetch ngrok URL: {e}")
        return None

def update_credentials_json(ngrok_url):
    """Update credentials.json with new ngrok redirect URI"""
    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"
        
        # Update the redirect URI
        creds['web']['redirect_uris'][0] = new_uri
        
        # Write back to file
        with open('credentials.json', 'w') as f:
            json.dump(creds, f, indent=2)
        
        print(f"[SUCCESS] Updated credentials.json")
        print(f"  Old URI: {old_uri}")
        print(f"  New URI: {new_uri}")
        
        return True
        
    except FileNotFoundError:
        print("[ERROR] credentials.json not found")
        return False
    except KeyError as e:
        print(f"[ERROR] Missing key in credentials.json: {e}")
        return False
    except Exception as e:
        print(f"[ERROR] Failed to update credentials.json: {e}")
        return False

def main():
    """Main function"""
    print("\n" + "="*70)
    print("NGROK URL UPDATER - Sync credentials with current ngrok tunnel")
    print("="*70)
    
    # Get ngrok URL
    print("\n[1/2] Fetching ngrok public URL...")
    ngrok_url = get_ngrok_url()
    
    if not ngrok_url:
        print("\n[FAILED] Could not get ngrok URL")
        sys.exit(1)
    
    print(f"[OK] Found ngrok URL: {ngrok_url}")
    
    # Update credentials
    print("\n[2/2] Updating credentials.json...")
    if update_credentials_json(ngrok_url):
        print("\n" + "="*70)
        print("✅ COMPLETE - Your OAuth redirect URI is now synchronized")
        print("="*70)
        print(f"\nAccess your app at: {ngrok_url}")
        print("\nNote: You may need to restart Flask for changes to take effect")
        sys.exit(0)
    else:
        print("\n[FAILED] Could not update credentials")
        sys.exit(1)

if __name__ == '__main__':
    main()
