#!/usr/bin/env python3
"""
NotebookLM auth using real Chrome + persistent profile.
Saves storage_state.json for notebooklm-py CLI.
"""
import asyncio
import json
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"
PROFILE_DIR = Path.home() / ".notebooklm" / "chrome_profile"
NEED_CODE_FILE = Path("/tmp/notebooklm_2fa_needed")
CODE_FILE = Path("/tmp/notebooklm_2fa_code")

def wait_for_code(timeout=180):
    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")

async def main():
    STORAGE_PATH.parent.mkdir(parents=True, exist_ok=True)
    PROFILE_DIR.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:
        # Use real Chrome with persistent profile
        context = await p.chromium.launch_persistent_context(
            str(PROFILE_DIR),
            channel="chrome",
            headless=False,
            args=["--start-maximized"],
        )
        page = context.pages[0] if context.pages else await context.new_page()

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

        print(f"Current URL: {page.url}")

        if "notebooklm.google.com" in page.url and "accounts.google.com" not in page.url:
            print("✅ Already logged in!")
        elif "accounts.google.com" in page.url:
            print("Need to log in. Filling email...")
            
            # Use JS to fill (less detectable than Playwright fill)
            await page.wait_for_selector('input[type="email"]', timeout=10000)
            await page.evaluate(f"""
                const el = document.querySelector('input[type="email"]');
                el.value = '{EMAIL}';
                el.dispatchEvent(new Event('input', {{ bubbles: true }}));
                el.dispatchEvent(new Event('change', {{ bubbles: true }}));
            """)
            await page.wait_for_timeout(500)
            await page.keyboard.press("Enter")
            await page.wait_for_timeout(3000)

            print("Filling password...")
            await page.wait_for_selector('input[type="password"]', timeout=10000)
            await page.evaluate(f"""
                const el = document.querySelector('input[type="password"]');
                el.value = '{PASSWORD}';
                el.dispatchEvent(new Event('input', {{ bubbles: true }}));
                el.dispatchEvent(new Event('change', {{ bubbles: true }}));
            """)
            await page.wait_for_timeout(500)
            await page.keyboard.press("Enter")
            await page.wait_for_timeout(4000)

            print(f"After password URL: {page.url}")

            # Check for 2FA
            if "challenge" in page.url or "ipp" in page.url:
                print("⚠️ 2FA required! Writing signal file...")
                NEED_CODE_FILE.write_text("waiting")
                
                loop = asyncio.get_event_loop()
                code = await loop.run_in_executor(None, wait_for_code, 180)
                print(f"Got code: {code}")
                
                # Try multiple 2FA input selectors
                for selector in ['input[name="totpPin"]', '#totpPin', 
                                  'input[type="tel"]', 'input[data-initial-value]',
                                  'input.whsOnd']:
                    try:
                        el = page.locator(selector).first
                        if await el.count() > 0:
                            await el.fill(code)
                            print(f"Filled code with selector: {selector}")
                            break
                    except:
                        continue
                
                await page.keyboard.press("Enter")
                await page.wait_for_timeout(4000)

        # Wait for NotebookLM dashboard
        await page.wait_for_url("**/notebooklm.google.com/**", timeout=20000)
        print(f"✅ On NotebookLM! Saving storage state...")
        await context.storage_state(path=str(STORAGE_PATH))
        print(f"Saved to: {STORAGE_PATH}")
        
        await page.wait_for_timeout(2000)
        await context.close()
        print("SUCCESS - NotebookLM CLI is now authenticated")

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