#!/usr/bin/env python3
"""
NotebookLM login using the exact same persistent profile as notebooklm CLI.
Saves to ~/.notebooklm/storage_state.json so the CLI works immediately after.
"""
import asyncio, json, time
from pathlib import Path
from playwright.async_api import async_playwright

EMAIL = "moon.clawdbot@gmail.com"
PASSWORD = "Ai210126"
PROFILE_DIR = Path.home() / ".notebooklm" / "browser_profile"
STORAGE_PATH = Path.home() / ".notebooklm" / "storage_state.json"
CODE_FILE = Path("/tmp/nlm_code.txt")
NEED_CODE = Path("/tmp/nlm_need_code.txt")

def wait_for_code(timeout=180):
    NEED_CODE.write_text("waiting")
    start = time.time()
    while time.time() - start < timeout:
        if CODE_FILE.exists():
            code = CODE_FILE.read_text().strip()
            CODE_FILE.unlink()
            NEED_CODE.unlink(missing_ok=True)
            return code
        time.sleep(2)
    raise TimeoutError("No 2FA code received")

async def human_type(page, selector, text):
    """Type slowly like a human."""
    await page.wait_for_selector(selector, timeout=30000)
    await page.click(selector)
    await page.wait_for_timeout(500)
    for char in text:
        await page.keyboard.type(char)
        await page.wait_for_timeout(80)

async def main():
    PROFILE_DIR.mkdir(parents=True, exist_ok=True)
    CODE_FILE.unlink(missing_ok=True)
    NEED_CODE.unlink(missing_ok=True)

    async with async_playwright() as p:
        ctx = await p.chromium.launch_persistent_context(
            str(PROFILE_DIR),
            channel="chrome",
            headless=False,
            slow_mo=50,
            args=["--start-maximized", "--disable-blink-features=AutomationControlled"],
            ignore_default_args=["--enable-automation"],
        )
        page = ctx.pages[0] if ctx.pages else await ctx.new_page()

        print("→ Navigating to NotebookLM...")
        await page.goto("https://notebooklm.google.com", wait_until="domcontentloaded")
        await page.wait_for_timeout(3000)
        await page.screenshot(path="/tmp/nlm_step1.png")
        print(f"  URL: {page.url}")

        if "notebooklm.google.com" in page.url and "accounts.google.com" not in page.url:
            print("✅ Already authenticated!")
        elif "accounts.google.com" in page.url:
            print("→ Login required. Typing email...")
            await human_type(page, 'input[type="email"]', EMAIL)
            await page.screenshot(path="/tmp/nlm_step2.png")
            await page.keyboard.press("Enter")
            await page.wait_for_timeout(4000)
            await page.screenshot(path="/tmp/nlm_step3.png")
            print(f"  After email URL: {page.url}")

            if "rejected" in page.url:
                print("❌ Google rejected — retrying with different approach")
                await page.goto("https://accounts.google.com/ServiceLogin?continue=https://notebooklm.google.com")
                await page.wait_for_timeout(3000)
                await human_type(page, 'input[type="email"]', EMAIL)
                await page.keyboard.press("Enter")
                await page.wait_for_timeout(4000)

            print("→ Typing password...")
            await human_type(page, 'input[type="password"]', PASSWORD)
            await page.screenshot(path="/tmp/nlm_step4.png")
            await page.keyboard.press("Enter")
            await page.wait_for_timeout(4000)
            await page.screenshot(path="/tmp/nlm_step5.png")
            print(f"  After password URL: {page.url}")

            if "challenge" in page.url or "ipp" in page.url or "2sv" in page.url:
                print("→ 2FA needed — writing signal...")
                loop = asyncio.get_event_loop()
                code = await loop.run_in_executor(None, wait_for_code, 180)
                print(f"  Got code: {code}")
                await human_type(page, 'input[type="tel"], input[name="totpPin"], input[data-initial-value]', code)
                await page.keyboard.press("Enter")
                await page.wait_for_timeout(4000)
                await page.screenshot(path="/tmp/nlm_step6.png")

        # Wait for NotebookLM to fully load
        print("→ Waiting for NotebookLM dashboard...")
        await page.wait_for_url("*notebooklm.google.com*", timeout=20000)
        await page.wait_for_timeout(2000)

        print(f"✅ Authenticated! Saving state to {STORAGE_PATH}")
        await ctx.storage_state(path=str(STORAGE_PATH))
        
        # Verify
        state = json.loads(STORAGE_PATH.read_text())
        cookies = state.get("cookies", [])
        has_sid = any(c["name"] == "SID" for c in cookies)
        print(f"  Saved {len(cookies)} cookies. Has SID: {has_sid}")
        print("SUCCESS" if has_sid else "WARNING: SID missing — login may not have worked")
        
        await ctx.close()

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