#!/usr/bin/env python3
"""
Connect to Elestio Browserless via CDP and login to GHL portal.
Goal: Generate a fresh PIT (Personal Integration Token) API key.
"""
import asyncio
import json
import sys
from playwright.async_api import async_playwright

BROWSERLESS_URL = "wss://browserless-genesis-u50607.vm.elestio.app?token=e3-CMPmnhYA3o9Ocz7gRG"
GHL_EMAIL = "kinan@agileadpt.com"
GHL_PASSWORD = "SystemBird505*"
GHL_LOGIN_URL = "https://app.gohighlevel.com/login"


async def main():
    print("[1/6] Connecting to Browserless via CDP...")
    async with async_playwright() as p:
        browser = await p.chromium.connect_over_cdp(BROWSERLESS_URL)
        print(f"  Connected. Browser contexts: {len(browser.contexts)}")

        # Use existing context or create new one
        context = browser.contexts[0] if browser.contexts else await browser.new_context(
            viewport={"width": 1280, "height": 800},
            user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
        )
        page = await context.new_page()

        print("[2/6] Navigating to GHL login page...")
        try:
            resp = await page.goto(GHL_LOGIN_URL, wait_until="domcontentloaded", timeout=30000)
            print(f"  Status: {resp.status if resp else 'no response'}")
            print(f"  URL: {page.url}")
            title = await page.title()
            print(f"  Title: {title}")
        except Exception as e:
            print(f"  Navigation error: {e}")
            # Take screenshot anyway
            await page.screenshot(path="/mnt/e/genesis-system/qa_reports/ghl_login_attempt.png")
            print("  Screenshot saved to qa_reports/ghl_login_attempt.png")
            await browser.close()
            return

        # Check for Cloudflare challenge
        content = await page.content()
        if "challenge" in content.lower() or "turnstile" in content.lower() or "cf-" in content.lower():
            print("  ⚠ Cloudflare challenge detected!")
            await page.screenshot(path="/mnt/e/genesis-system/qa_reports/ghl_cloudflare_block.png")
            print("  Screenshot saved. Collaborative Browser Handoff needed.")
            await browser.close()
            return

        # Wait for page to fully load
        await page.wait_for_timeout(3000)
        await page.screenshot(path="/mnt/e/genesis-system/qa_reports/ghl_login_page.png")
        print("  Login page screenshot saved.")

        print("[3/6] Attempting login...")
        try:
            # Look for email input
            email_sel = 'input[type="email"], input[name="email"], input[placeholder*="email" i], #email'
            await page.wait_for_selector(email_sel, timeout=10000)
            await page.fill(email_sel, GHL_EMAIL)
            print(f"  Email filled: {GHL_EMAIL}")

            # Look for password input
            pass_sel = 'input[type="password"], input[name="password"], #password'
            await page.wait_for_selector(pass_sel, timeout=5000)
            await page.fill(pass_sel, GHL_PASSWORD)
            print("  Password filled.")

            # Click login button
            btn_sel = 'button[type="submit"], button:has-text("Sign In"), button:has-text("Login"), button:has-text("Log In")'
            await page.click(btn_sel)
            print("  Login button clicked.")

            # Wait for navigation
            await page.wait_for_timeout(5000)
            print(f"  Post-login URL: {page.url}")
            title = await page.title()
            print(f"  Post-login title: {title}")
            await page.screenshot(path="/mnt/e/genesis-system/qa_reports/ghl_post_login.png")

        except Exception as e:
            print(f"  Login error: {e}")
            await page.screenshot(path="/mnt/e/genesis-system/qa_reports/ghl_login_error.png")
            print("  Error screenshot saved.")

        # Check if we're logged in
        if "dashboard" in page.url.lower() or "location" in page.url.lower() or "sub-account" in page.url.lower():
            print("[4/6] LOGIN SUCCESS! Navigating to API settings...")
            # Try to get to Settings > Integrations
            try:
                settings_url = "https://app.gohighlevel.com/settings/integrations"
                await page.goto(settings_url, wait_until="domcontentloaded", timeout=30000)
                await page.wait_for_timeout(3000)
                print(f"  Settings URL: {page.url}")
                await page.screenshot(path="/mnt/e/genesis-system/qa_reports/ghl_settings.png")

                # Look for API key or Personal Integration Token section
                content = await page.content()
                if "integration" in content.lower() or "api" in content.lower():
                    print("[5/6] Found integrations page. Looking for PIT key...")
                    await page.screenshot(path="/mnt/e/genesis-system/qa_reports/ghl_integrations.png")
                else:
                    print("  Integrations page not found at expected URL")
                    # Try alternative path
                    alt_url = "https://app.gohighlevel.com/v2/settings/integrations"
                    await page.goto(alt_url, wait_until="domcontentloaded", timeout=30000)
                    await page.wait_for_timeout(3000)
                    await page.screenshot(path="/mnt/e/genesis-system/qa_reports/ghl_integrations_v2.png")

            except Exception as e:
                print(f"  Settings navigation error: {e}")
                await page.screenshot(path="/mnt/e/genesis-system/qa_reports/ghl_settings_error.png")
        else:
            print(f"  May not be logged in. Current URL: {page.url}")
            # Check for 2FA or other challenges
            content = await page.content()
            if "two-factor" in content.lower() or "2fa" in content.lower() or "verification" in content.lower():
                print("  ⚠ 2FA or verification required!")
            elif "invalid" in content.lower() or "incorrect" in content.lower():
                print("  ⚠ Invalid credentials!")
            await page.screenshot(path="/mnt/e/genesis-system/qa_reports/ghl_login_result.png")

        print("[6/6] Done. Check screenshots in qa_reports/")
        await browser.close()


if __name__ == "__main__":
    asyncio.run(main())
