"""Phase 1: interactive Google / NotebookLM login via Playwright (browser → storage JSON)."""

from __future__ import annotations

import os
import subprocess
import sys
from pathlib import Path

from folio_notion.integrations.notebooklm.paths import (
    get_browser_profile_dir,
    get_notebooklm_home,
    get_storage_path,
)

NOTEBOOKLM_URL = "https://notebooklm.google.com/"

_CHROMIUM_ARGS = [
    "--disable-blink-features=AutomationControlled",
    "--password-store=basic",
]
_IGNORE_DEFAULT_ARGS = ["--enable-automation"]


def _try_install_chromium() -> None:
    """Best-effort: install browser if missing (non-interactive)."""
    try:
        subprocess.run(
            [sys.executable, "-m", "playwright", "install", "chromium"],
            check=False,
            capture_output=True,
            timeout=600,
        )
    except (OSError, subprocess.TimeoutExpired):
        pass


def interactive_login(
    *,
    storage_path: Path | None = None,
    browser_profile: Path | None = None,
) -> Path:
    """
    Open Chromium (persistent profile), let the user complete Google login,
    then write Playwright ``storage_state`` JSON (chmod 0o600).

    Returns path to ``storage_state.json``.
    """
    try:
        from playwright.sync_api import sync_playwright
    except ImportError as e:
        raise SystemExit(
            "playwright is not installed. Run:\n"
            '  pip install "folio-notion[notebooklm]"\n'
            "  playwright install chromium\n"
        ) from e

    get_notebooklm_home(create=True)
    storage = storage_path or get_storage_path()
    profile = browser_profile or get_browser_profile_dir()
    storage.parent.mkdir(parents=True, exist_ok=True)
    profile.mkdir(parents=True, exist_ok=True)

    if os.environ.get("FOLIO_PLAYWRIGHT_AUTO_INSTALL", "1") not in ("0", "false", "no"):
        _try_install_chromium()

    print(
        "Opening Chromium for NotebookLM sign-in.\n"
        "Complete Google login (MFA if needed) in the window.\n"
        "This profile is separate from your daily Chrome — data lives under:\n"
        f"  {profile}\n"
    )

    try:
        with sync_playwright() as p:
            context = p.chromium.launch_persistent_context(
                str(profile),
                headless=False,
                args=list(_CHROMIUM_ARGS),
                ignore_default_args=list(_IGNORE_DEFAULT_ARGS),
            )
            try:
                page = context.pages[0] if context.pages else context.new_page()
                page.goto(NOTEBOOKLM_URL, wait_until="domcontentloaded")
                # Use stdlib input() here: Playwright sync keeps an asyncio loop alive on
                # Python 3.12+, and prompt_toolkit calls asyncio.run() → RuntimeError.
                input(
                    "When NotebookLM loads and you are signed in, press Enter here → "
                )
                context.storage_state(path=str(storage))
            finally:
                context.close()
    except Exception:
        print(
            "If the browser failed to start, run: playwright install chromium",
            file=sys.stderr,
        )
        raise

    try:
        storage.chmod(0o600)
    except NotImplementedError:
        pass
    return storage
