"""CLI: Playwright login → storage_state.json → verify NotebookLM tokens (httpx)."""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

from folio_notion.envfile import load_dotenv, upsert_env
from folio_notion.integrations.notebooklm.auth import AuthTokens
from folio_notion.integrations.notebooklm.session import interactive_login
from folio_notion.prompts import prompt_line


def _project_env_path(args: argparse.Namespace) -> Path:
    root = Path(getattr(args, "project_root", ".") or ".").resolve()
    return root / ".env"


def _prompt_yes_no(prompt: str, default_yes: bool) -> bool:
    hint = "Y/n" if default_yes else "y/N"
    try:
        line = prompt_line(f"{prompt} [{hint}] ").strip().lower()
    except EOFError:
        return default_yes
    if not line:
        return default_yes
    return line in ("y", "yes")


def connect_notebooklm(args: argparse.Namespace) -> None:
    load_dotenv(_project_env_path(args))

    storage_arg = (getattr(args, "storage", None) or "").strip()
    storage_path = Path(storage_arg).expanduser().resolve() if storage_arg else None

    path = interactive_login(storage_path=storage_path)

    if not getattr(args, "no_verify", False):
        try:
            AuthTokens.from_storage(path)
        except Exception as e:
            print(
                f"Saved session to {path}, but API token check failed: {e}",
                file=sys.stderr,
            )
            print(
                "Try signing in again in the browser, or run with --no-verify.",
                file=sys.stderr,
            )
            raise SystemExit(1) from e
        print("NotebookLM API tokens (SNlM0e / FdrFJe) verified.\n")
    else:
        print(f"Session saved to {path} (--no-verify: skipped token check).\n")

    env_key = "FOLIO_NOTEBOOKLM_STORAGE"
    updates = {env_key: str(path)}
    save = getattr(args, "save", False)
    no_save = getattr(args, "no_save", False)
    tty = sys.stdin.isatty()

    if save:
        should_save = True
    elif no_save:
        should_save = False
    elif tty:
        should_save = _prompt_yes_no(
            f"Add {env_key} to project .env (recommended)?",
            True,
        )
        print()
    else:
        should_save = False

    if should_save:
        upsert_env(_project_env_path(args), updates)
        print(f"Updated {_project_env_path(args)} with {env_key}.")
    else:
        print(f"Export for shells: export {env_key}={path!s}")

    print("NotebookLM connect finished.")
