"""
Genesis Bridge: Elestio Browserless Connection Test
Validates that Genesis can successfully connect to the new managed browserless service.
"""

import asyncio
import os
from dotenv import load_dotenv
from playwright.async_api import async_playwright

# Load environment variables
load_dotenv()

async def test_browserless_connection():
    print("==========================================")
    print(" Genesis Bridge: Elestio Browserless Test")
    print("==========================================")
    
    # The endpoint will look like wss://browserless-xxxxx.vm.elestio.app
    # Need the exact URL + token from Elestio dashboard
    endpoint = os.getenv("ELESTIO_BROWSERLESS_URL")
    token = os.getenv("ELESTIO_BROWSERLESS_TOKEN")
    
    if not endpoint:
        print("❌ ERROR: ELESTIO_BROWSERLESS_URL not found in .env")
        print("Please copy the WebSocket URL from the Elestio dashboard.")
        return
        
    print(f"Connecting to: {endpoint}...")
    
    try:
        async with async_playwright() as pw:
            # Construct connection URL with auth if required by Elestio
            ws_url = f"{endpoint}?token={token}" if token else endpoint
            
            # Connect to the remote browser
            print("[1/3] Establishing CDP connection...")
            browser = await pw.chromium.connect_over_cdp(ws_url)
            print("[OK] Connected successfully!")
            
            # Create a new context (or use existing for persistent sessions)
            print("[2/3] Accessing browser context...")
            contexts = browser.contexts
            if contexts:
                context = contexts[0]
                print(f"[OK] Reusing existing context with {len(context.pages)} pages")
            else:
                context = await browser.new_context()
                print("[OK] Created new context")
                
            # Open a test page
            print("[3/3] Running navigation test...")
            page = await context.new_page()
            print("  Navigating to example.com...")
            await page.goto("https://example.com/", timeout=15000, wait_until="domcontentloaded")
            
            # Take a screenshot to verify stealth/rendering
            screenshot_path = "browserless_test.png"
            await page.screenshot(path=screenshot_path)
            title = await page.title()
            
            print(f"[OK] Navigation successful. Page title: '{title}'")
            print(f"[OK] Screenshot saved to {screenshot_path}")
            
            # Close just the test page, keep browser running
            await page.close()
            await browser.close()
            
            print("\nConnection test PASSED. Genesis is ready to use this hub.")
            
    except Exception as e:
        print(f"\n[FAIL] CONNECTION FAILED:")
        print(f"{type(e).__name__}: {str(e)}")
        print("\nTroubleshooting:")
        print("- Verify the WebSocket URL in .env is correct")
        print("- Ensure the Elestio service has finished deploying")

if __name__ == "__main__":
    asyncio.run(test_browserless_connection())
