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

Usage: python _nlm_login_worker.py <storage_path>
"""
import sys
import os


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

    storage_path = sys.argv[1]
    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:
        browser = p.chromium.launch(
            headless=False,
            args=["--disable-blink-features=AutomationControlled"],
        )
        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()
        page.goto("https://notebooklm.google.com/", wait_until="networkidle")

        # Wait for user to complete login (max 5 minutes)
        try:
            page.wait_for_url("**/notebook/**", timeout=300_000)
        except Exception:
            pass

        current_url = page.url
        if "notebooklm.google.com" in current_url:
            context.storage_state(path=storage_path)
            browser.close()
            print("OK:" + storage_path)
            sys.exit(0)
        else:
            browser.close()
            print("ERROR:Login was not completed", file=sys.stderr)
            sys.exit(3)


if __name__ == "__main__":
    main()
