"""
Standalone script to run Playwright Google login for NotebookLM.
Called as a subprocess to avoid asyncio/thread issues.

This version runs in headless mode with CDP (Chrome DevTools Protocol) support,
allowing remote debugging via websocket URL.

Usage: python _nlm_login_worker.py <storage_path> [cdp_port]
"""
import sys
import os
import subprocess
import time
import json


def main():
    if len(sys.argv) < 2:
        print("ERROR:Usage: python _nlm_login_worker.py <storage_path> [cdp_port]", file=sys.stderr)
        sys.exit(1)

    storage_path = sys.argv[1]
    cdp_port = int(sys.argv[2]) if len(sys.argv) > 2 else 9222
    os.makedirs(os.path.dirname(storage_path), exist_ok=True)

    try:
        from playwright.sync_api import sync_playwright
    except ImportError:
        print("ERROR:Playwright is not installed. Run: pip install playwright && playwright install chromium", file=sys.stderr)
        sys.exit(2)

    with sync_playwright() as p:
        # Launch with remote debugging for potential external access
        browser = p.chromium.launch(
            headless=True,
            args=[
                "--disable-blink-features=AutomationControlled",
                "--no-sandbox",
                "--disable-dev-shm-usage",
                f"--remote-debugging-port={cdp_port}",
                "--remote-debugging-address=0.0.0.0",
            ],
        )

        # Output the debugging info for potential external connection
        debug_info = {
            "cdp_url": f"ws://localhost:{cdp_port}",
            "storage_path": storage_path,
        }

        context = browser.new_context(
            locale="ar-SA",
            user_agent=(
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                "AppleWebKit/537.36 (KHTML, like Gecko) "
                "Chrome/120.0.0.0 Safari/537.36"
            ),
        )
        page = context.new_page()

        # Navigate to NotebookLM
        page.goto("https://notebooklm.google.com/", wait_until="networkidle")

        # For headless mode, we need to use Google OAuth programmatically
        # This requires Google OAuth credentials to be set up
        # For now, we'll wait for the URL to change (which won't work in pure headless)

        # Alternative: Use a timeout-based approach with polling
        # In production, you'd want to set up proper OAuth flow
        timeout_seconds = 300  # 5 minutes
        start_time = time.time()

        print(f"INFO:Browser started with CDP on port {cdp_port}", file=sys.stderr)
        print(f"INFO:Waiting for login... (will timeout after {timeout_seconds}s)", file=sys.stderr)

        # Wait for navigation to a notebook page (indicating successful login)
        try:
            # In headless mode, this won't work without user interaction
            # We need to implement a different approach
            page.wait_for_url("**/notebook/**", timeout=timeout_seconds * 1000)
            success = True
        except Exception:
            # Timeout - check if we're still on login page or notebook page
            current_url = page.url
            success = "notebooklm.google.com" in current_url and "/notebook/" in current_url

        current_url = page.url
        if success:
            context.storage_state(path=storage_path)
            browser.close()
            print("OK:" + storage_path)
            sys.exit(0)
        else:
            browser.close()
            error_msg = f"Login was not completed. Final URL: {current_url}"
            print("ERROR:" + error_msg, file=sys.stderr)
            sys.exit(3)


if __name__ == "__main__":
    main()
