#!/usr/bin/env python3
"""
Automated NotebookLM auth via Playwright.
File-based 2FA: writes /tmp/notebooklm_2fa_needed when 2FA required,
reads /tmp/notebooklm_2fa_code when code is ready.
"""
import asyncio
import os
import time
from pathlib import Path
from playwright.async_api import async_playwright

EMAIL = "moon.clawdbot@gmail.com"
PASSWORD = "Ai210126"
STORAGE_PATH = Path.home() / ".notebooklm" / "storage_state.json"
NEED_CODE_FILE = Path("/tmp/notebooklm_2fa_needed")
CODE_FILE = Path("/tmp/notebooklm_2fa_code")

def wait_for_code(timeout=120):
    """Wait up to timeout seconds for 2FA code file to appear."""
    start = time.time()
    while time.time() - start < timeout:
        if CODE_FILE.exists():
            code = CODE_FILE.read_text().strip()
            CODE_FILE.unlink()
            return code
        time.sleep(2)
    raise TimeoutError("No 2FA code received within timeout")

async def main():
    STORAGE_PATH.parent.mkdir(parents=True, exist_ok=True)
    NEED_CODE_FILE.unlink(missing_ok=True)
    CODE_FILE.unlink(missing_ok=True)

    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(
            user_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
        )
        page = await context.new_page()

        print("Navigating to NotebookLM...")
        await page.goto("https://notebooklm.google.com")
        await page.wait_for_load_state("networkidle")

        if "accounts.google.com" in page.url:
            print("Login page detected. Entering email...")
            await page.wait_for_selector('input[type="email"]', timeout=10000)
            await page.fill('input[type="email"]', EMAIL)
            await page.wait_for_timeout(1000)
            await page.keyboard.press("Enter")
            await page.wait_for_timeout(2500)

            print("Entering password...")
            await page.wait_for_selector('input[type="password"]', timeout=10000)
            await page.fill('input[type="password"]', PASSWORD)
            await page.wait_for_timeout(1000)
            await page.keyboard.press("Enter")
            await page.wait_for_timeout(3000)

            # Check for 2FA
            if "challenge" in page.url or "ipp" in page.url or "totp" in page.url:
                print("2FA challenge detected. Waiting for code...")
                NEED_CODE_FILE.write_text("2FA needed")
                # Wait for code from external file
                loop = asyncio.get_event_loop()
                code = await loop.run_in_executor(None, wait_for_code, 180)
                print(f"Got code: {code[:3]}***")
                
                # Find the code input - try multiple selectors
                for selector in ['input[name="totpPin"]', 'input[data-initial-value]', '#totpPin', 'input[type="tel"]']:
                    try:
                        el = await page.wait_for_selector(selector, timeout=2000)
                        if el:
                            await el.fill(code)
                            break
                    except:
                        continue
                
                await page.keyboard.press("Enter")
                await page.wait_for_timeout(3000)

        # Wait for NotebookLM
        try:
            await page.wait_for_url("https://notebooklm.google.com/**", timeout=15000)
            print(f"✅ Authenticated! Saving session to {STORAGE_PATH}")
            await context.storage_state(path=str(STORAGE_PATH))
            print("SUCCESS")
        except Exception as e:
            print(f"Current URL: {page.url}")
            print(f"Error: {e}")
            await page.screenshot(path="/tmp/notebooklm_auth_debug.png")
            print("Screenshot saved to /tmp/notebooklm_auth_debug.png")

        await browser.close()

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