"""
Genesis Authentication Gateway: Telnyx Portal
Connects to Elestio Browserless, holds open a session for human login,
and exports the authenticated storage state (cookies) for future agents.
"""

import asyncio
import os
import json
from dotenv import load_dotenv
from playwright.async_api import async_playwright

load_dotenv()

STATE_FILE = "e:\\genesis-system\\config\\telnyx_storage_state.json"

async def manual_auth_login():
    print("==========================================")
    print(" Genesis Auth Gateway: Telnyx Login")
    print("==========================================")
    
    endpoint = os.getenv("ELESTIO_BROWSERLESS_URL")
    token = os.getenv("ELESTIO_BROWSERLESS_TOKEN")
    
    # Enable headed mode on browserless so we can interact with it via the web viewer
    ws_url = f"{endpoint}?token={token}&stealth=true&headful=true"
    
    print(f"Connecting to Elestio Browserless...")
    
    async with async_playwright() as pw:
        # We use connect_over_cdp for Browserless websocket endpoints
        browser = await pw.chromium.connect_over_cdp(ws_url)
        print("[OK] Connected to Cloud Hub!")
        
        # Load existing state if we have it, otherwise start fresh
        context_args: dict = {"viewport": {"width": 1920, "height": 1080}}
        if os.path.exists(STATE_FILE):
            print(f"Loading existing cookies from {STATE_FILE}...")
            context_args["storage_state"] = STATE_FILE
            
        context = await browser.new_context(**context_args)
        page = await context.new_page()
        
        print("\n[WAIT] Opening Telnyx Portal...")
        await page.goto("https://portal.telnyx.com/#/login/sign-in")
        
        print("\n==========================================")
        print("[ACTION REQUIRED]")
        print("1. Go to: https://browserless-genesis-u50607.vm.elestio.app")
        print("2. Click on the 'Sessions' tab on the left menu")
        print("3. You should see an active session running. Click the EYE ICON (Live Debugger)")
        print("4. VERY IMPORTANT: In the debugger window, click the 'PAUSE' button (⏸️)")
        print("   (If you don't pause, you can't click anything)")
        print("5. Log into Telnyx manually through that viewer window.")
        print("6. After you are fully logged in to the dashboard, click 'RESUME' (▶️)")
        print("7. Finally, come back to this terminal and press ENTER to save.")
        print("==========================================\n")
        
        input("Press ENTER here only AFTER you have fully logged into Telnyx...")
        
        print("\n[SAVE] Capturing authenticated state cookies...")
        state = await context.storage_state(path=STATE_FILE)
        
        print(f"[OK] State saved successfully to: {STATE_FILE}")
        print("Genesis agents will now use this state file to bypass Cloudflare Turnstile permanently.")
        
        await context.close()
        await browser.close()

if __name__ == "__main__":
    # Ensure config dir exists
    os.makedirs("e:\\genesis-system\\config", exist_ok=True)
    asyncio.run(manual_auth_login())
