"""
Local Telnyx Authenticator
Opens a local Chromium window so the user can easily log into Telnyx.
Saves the cookies locally, which Genesis will then use for the Elestio cloud browser.
"""

import asyncio
import os
from playwright.async_api import async_playwright

STATE_FILE = "e:\\genesis-system\\config\\telnyx_storage_state.json"

async def manual_auth_login():
    print("==========================================")
    print(" Genesis Local Auth: Telnyx Login")
    print("==========================================")
    
    async with async_playwright() as pw:
        # Launch a local browser WITH A VISIBLE WINDOW (headless=False)
        print("Launching local browser window...")
        browser = await pw.chromium.launch(headless=False)
        
        # Start fresh context to ensure clean login
        context = await browser.new_context(viewport={"width": 1920, "height": 1080})
        page = await context.new_page()
        
        print("\n[WAIT] Opening Telnyx Portal in the new window...")
        await page.goto("https://portal.telnyx.com/#/login/sign-in")
        
        print("\n==========================================")
        print("[ACTION REQUIRED]")
        print("1. A Chromium window just opened on your local computer.")
        print("2. Log into Telnyx normally in that window.")
        print("3. Take as much time as you need. There are no timeouts.")
        print("4. When you see your Telnyx Dashboard, come back to this terminal.")
        print("==========================================\n")
        
        input("Press ENTER here only AFTER you are fully logged into Telnyx...")
        
        print("\n[SAVE] Capturing your authenticated cookies...")
        await context.storage_state(path=STATE_FILE)
        
        print(f"[OK] Cookies saved successfully to: {STATE_FILE}")
        print("Genesis will now use these cookies to bypass the Cloudflare Turnstile on the Elestio hub.")
        
        await context.close()
        await browser.close()

if __name__ == "__main__":
    os.makedirs("e:\\genesis-system\\config", exist_ok=True)
    asyncio.run(manual_auth_login())
