"""`fn status` — show whether Notion / NotebookLM / config look wired up."""

from __future__ import annotations

import argparse
import os
from pathlib import Path

from folio_notion.config_load import load_config
from folio_notion.envfile import load_dotenv
from folio_notion.integrations.notebooklm.auth import fetch_tokens_sync
from folio_notion.integrations.notebooklm.auth import load_auth_from_storage
from folio_notion.integrations.notebooklm.paths import get_notebooklm_home, get_storage_path
from folio_notion.integrations.notion_api import NotionAPIError, verify_integration_token


def _label(ok: bool) -> str:
    return "connected" if ok else "disconnected"


def print_status(args: argparse.Namespace) -> None:
    root = Path(getattr(args, "project_root", ".") or ".").resolve()
    env_path = root / ".env"
    load_dotenv(env_path)

    print(f"Folio status — project: {root}\n")

    # --- Notion ---
    token = (os.environ.get("NOTION_TOKEN") or "").strip()
    parent = (os.environ.get("NOTION_PARENT_PAGE_ID") or "").strip()
    if not parent:
        try:
            cfg = load_config(root)
            parent = (cfg.get("notion") or {}).get("parent_page_id") or ""
            parent = str(parent).strip()
        except Exception:
            parent = ""

    notion_api = _label(False)
    notion_who = ""
    if not token:
        notion_api = "disconnected (NOTION_TOKEN not set)"
    else:
        try:
            me = verify_integration_token(token)
            notion_api = "connected"
            notion_who = me.get("name") or me.get("id") or ""
        except NotionAPIError as e:
            notion_api = f"disconnected (API: {e})"

    parent_ok = bool(parent)
    parent_hint = (parent[:10] + "…") if len(parent) > 10 else parent if parent else ""

    print("Notion")
    print(f"  Integration:  {notion_api}" + (f" — {notion_who}" if notion_who else ""))
    if parent_ok:
        print(f"  Parent:       connected — id {parent_hint}")
    else:
        print("  Parent:       disconnected — set NOTION_PARENT_PAGE_ID or notion.parent_page_id")
    print()

    # --- NotebookLM ---
    st_path = get_storage_path()
    has_json = "NOTEBOOKLM_AUTH_JSON" in os.environ and bool(
        os.environ.get("NOTEBOOKLM_AUTH_JSON", "").strip()
    )
    storage_line = str(st_path)
    if has_json:
        storage_line = "(NOTEBOOKLM_AUTH_JSON env — inline session)"

    nb_state = _label(False)
    nb_detail = ""
    if has_json:
        try:
            cookies = load_auth_from_storage(None)
            fetch_tokens_sync(cookies)
            nb_state = "connected"
            nb_detail = "tokens ok (inline JSON)"
        except FileNotFoundError:
            nb_state = "disconnected"
            nb_detail = "NOTEBOOKLM_AUTH_JSON invalid or empty"
        except ValueError as e:
            nb_state = "disconnected"
            nb_detail = str(e)[:120]
        except Exception as e:
            nb_state = "disconnected"
            nb_detail = str(e)[:120]
    elif st_path.is_file():
        try:
            cookies = load_auth_from_storage(st_path)
            fetch_tokens_sync(cookies)
            nb_state = "connected"
            nb_detail = "session + NotebookLM tokens ok"
        except ValueError as e:
            nb_state = "disconnected"
            nb_detail = str(e)[:120]
        except Exception as e:
            nb_state = "disconnected"
            nb_detail = str(e)[:120]
    else:
        nb_state = "disconnected"
        nb_detail = f"no file at {st_path}"

    print("NotebookLM")
    print(f"  Session:      {nb_state}")
    print(f"  Storage:      {storage_line}")
    if nb_detail and nb_state != "connected":
        print(f"  Detail:       {nb_detail}")
    print(f"  Profile dir:  {get_notebooklm_home() / 'browser_profile'}\n")

    # --- Paths / config ---
    try:
        cfg = load_config(root)
        inp = (root / (cfg.get("input_dir") or "./var/inbox")).resolve()
        out = (root / (cfg.get("export_dir") or "./var/exports")).resolve()
        print("Pipeline")
        print(f"  input_dir:    {inp} {'(exists)' if inp.is_dir() else '(missing — will create on run)'}")
        print(f"  export_dir:   {out} {'(exists)' if out.is_dir() else '(missing — will create on run)'}")
    except Exception as e:
        print("Pipeline")
        print(f"  config:       could not load ({e})")

    print(f"\n.env:           {env_path} {'(present)' if env_path.is_file() else '(none)'}")
