import requests
import json

try:
    response = requests.get('http://localhost:4040/api/tunnels')
    tunnels = response.json()
    https_tunnel = [t for t in tunnels['tunnels'] if t['proto'] == 'https'][0]
    ngrok_url = https_tunnel["public_url"]
    print(f"Current ngrok URL: {ngrok_url}")
    
    # Update credentials.json with this URL
    with open('credentials.json', 'r') as f:
        creds = json.load(f)
    
    # Update redirect_uris and javascript_origins
    creds['web']['redirect_uris'] = [f"{ngrok_url}/oauth2callback"]
    creds['web']['javascript_origins'] = [ngrok_url]
    
    with open('credentials.json', 'w') as f:
        json.dump(creds, f)
    
    print(f"✓ Updated credentials.json with new ngrok URL")
    
except Exception as e:
    print(f"Error: {e}")
    print("Make sure ngrok is running on port 4040")
