#!/usr/bin/env python
"""
Startup helper - Shows current ngrok URL and required steps
"""
import subprocess
import time
import sys

print("\n" + "="*60)
print("SALES DASHBOARD - NGROK SETUP")
print("="*60)

# Check if ngrok is running
try:
    result = subprocess.run(['powershell', '-Command', 'Get-Process ngrok -ErrorAction SilentlyContinue'], 
                          capture_output=True, text=True, timeout=5)
    
    if not result.stdout.strip():
        print("\n❌ ngrok is NOT running!")
        print("Please start ngrok in another terminal:")
        print("   ngrok http --host-header=rewrite 5000")
        print("\nThen come back and run this script again.")
        sys.exit(1)
    
    print("✓ ngrok is running")
    
    # Try to get the tunnel URL
    import requests
    try:
        response = requests.get('http://localhost:4040/api/tunnels', timeout=2)
        tunnels = response.json()
        https_tunnel = [t for t in tunnels.get('tunnels', []) if t.get('proto') == 'https']
        
        if https_tunnel:
            ngrok_url = https_tunnel[0]['public_url']
            print(f"\n✓ Your current ngrok URL: {ngrok_url}")
            
            print("\n" + "="*60)
            print("NEXT STEPS:")
            print("="*60)
            print(f"\n1. Go to Google Cloud Console OAuth 2.0 settings")
            print(f"2. Update Authorized Redirect URIs to:")
            print(f"   {ngrok_url}/oauth2callback")
            print(f"\n3. Update Authorized JavaScript Origins to:")
            print(f"   {ngrok_url}")
            print(f"\n4. Then you can start the Flask app:")
            print(f"   python app.py")
            print("\n" + "="*60 + "\n")
            
        else:
            print("\n⚠ Could not find HTTPS tunnel")
            print("Make sure ngrok is running with: ngrok http 5000")
            
    except Exception as e:
        print(f"\n⚠ Could not reach ngrok API: {e}")
        print("Check that ngrok is running properly")
        sys.exit(1)
        
except Exception as e:
    print(f"\n⚠ Error: {e}")
    sys.exit(1)
