"""CLI entry: run pipeline, connect Notion (`fn connect notion`), etc."""

from __future__ import annotations

import argparse
import sys


def _add_notion_connect_args(p: argparse.ArgumentParser) -> None:
    p.add_argument(
        "--token",
        metavar="SECRET",
        help="Internal integration secret (otherwise NOTION_TOKEN or prompt).",
    )
    p.add_argument(
        "--parent",
        metavar="PAGE_ID",
        help="Parent page or database UUID (otherwise prompt or NOTION_PARENT_PAGE_ID).",
    )
    p.add_argument(
        "--save",
        action="store_true",
        help="Write .env without asking.",
    )
    p.add_argument(
        "--no-save",
        action="store_true",
        help="Do not write .env.",
    )
    p.add_argument(
        "-C",
        "--directory",
        dest="project_root",
        default=".",
        help="Project root where .env is read/written (default: current directory).",
    )


def _add_notebooklm_connect_args(p: argparse.ArgumentParser) -> None:
    p.add_argument(
        "--storage",
        metavar="PATH",
        help="Path for storage_state.json (default: Folio / NOTEBOOKLM_HOME layout).",
    )
    p.add_argument(
        "--no-verify",
        action="store_true",
        help="Skip httpx check for SNlM0e / FdrFJe after saving storage.",
    )
    p.add_argument(
        "--save",
        action="store_true",
        help="Write FOLIO_NOTEBOOKLM_STORAGE to .env without asking.",
    )
    p.add_argument(
        "--no-save",
        action="store_true",
        help="Do not write .env.",
    )
    p.add_argument(
        "-C",
        "--directory",
        dest="project_root",
        default=".",
        help="Project root where .env is read/written (default: current directory).",
    )


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Folio: PDFs → NotebookLM → disk + Notion.",
    )
    sub = parser.add_subparsers(dest="command", help="Command")

    run_p = sub.add_parser(
        "run",
        help="Run pipeline: ingest PDFs → NotebookLM synthesis → export + Notion.",
    )
    run_p.add_argument(
        "-C",
        "--directory",
        dest="project_root",
        default=".",
        help="Project root (config, .env, var/). Default: current directory.",
    )
    run_p.add_argument(
        "--dry-run",
        action="store_true",
        help="Load config and verify auth only (no ingest, NotebookLM, export, Notion).",
    )
    run_p.add_argument(
        "--skip-notion",
        action="store_true",
        help="Write local export only; skip Notion token checks and page creation.",
    )
    run_p.add_argument(
        "--pdf",
        action="append",
        dest="pdf",
        metavar="PATH",
        help="PDF file or directory of PDFs (repeatable). Merged with inbox; avoids prompt.",
    )
    run_p.set_defaults(_handler=_cmd_run)

    st_p = sub.add_parser(
        "status",
        help="Show Notion / NotebookLM connection state and pipeline paths.",
    )
    st_p.add_argument(
        "-C",
        "--directory",
        dest="project_root",
        default=".",
        help="Project root (for .env and config). Default: current directory.",
    )
    st_p.set_defaults(_handler=_cmd_status)

    connect = sub.add_parser("connect", help="Connect external services.")
    connect_sub = connect.add_subparsers(dest="connect_target", required=True)
    cn = connect_sub.add_parser(
        "notion",
        help="Verify Notion integration token and optional parent page; save .env.",
    )
    _add_notion_connect_args(cn)
    cn.set_defaults(_handler=_connect_notion)

    cnb = connect_sub.add_parser(
        "notebooklm",
        help="Browser login to NotebookLM; save Playwright storage + verify API tokens.",
    )
    _add_notebooklm_connect_args(cnb)
    cnb.set_defaults(_handler=_connect_notebooklm)

    notion = sub.add_parser("notion", help="Notion shortcuts (alias of connect notion).")
    notion_sub = notion.add_subparsers(dest="notion_target", required=True)
    nc = notion_sub.add_parser(
        "connect",
        help="Same as: connect notion",
    )
    _add_notion_connect_args(nc)
    nc.set_defaults(_handler=_connect_notion)

    nb = sub.add_parser("notebooklm", help="NotebookLM shortcuts.")
    nb_sub = nb.add_subparsers(dest="notebooklm_target", required=True)
    nbc = nb_sub.add_parser("connect", help="Same as: connect notebooklm")
    _add_notebooklm_connect_args(nbc)
    nbc.set_defaults(_handler=_connect_notebooklm)

    args = parser.parse_args()
    handler = getattr(args, "_handler", None)
    if handler is None:
        if getattr(args, "project_root", None) is None:
            setattr(args, "project_root", ".")
        _cmd_run(args)
    else:
        handler(args)


def _cmd_run(args: argparse.Namespace) -> None:
    from pathlib import Path

    from folio_notion.exceptions import PipelineStepError
    from folio_notion.pipeline import run_pipeline

    root = Path(getattr(args, "project_root", ".") or ".").resolve()
    dry = bool(getattr(args, "dry_run", False))
    skip_notion = bool(getattr(args, "skip_notion", False))
    pdf_arg = getattr(args, "pdf", None) or []
    cli_pdfs = [Path(p).expanduser() for p in pdf_arg]
    try:
        ctx = run_pipeline(
            root,
            dry_run=dry,
            skip_notion=skip_notion,
            cli_pdf_paths=cli_pdfs,
        )
    except NotImplementedError as e:
        print("Pipeline step not implemented yet:", e, file=sys.stderr)
        raise SystemExit(2) from e
    except PipelineStepError as e:
        print(str(e), file=sys.stderr)
        raise SystemExit(1) from e
    except RuntimeError as e:
        print(e, file=sys.stderr)
        raise SystemExit(1) from e

    if dry:
        print("Dry run finished (config + auth only).")
    else:
        print("Pipeline complete.")
    if ctx.export_file:
        print(f"  Local:  {ctx.export_file}")
    if ctx.notion_page_url:
        print(f"  Notion: {ctx.notion_page_url}")


def _connect_notion(args: argparse.Namespace) -> None:
    from folio_notion.commands.connect_notion import connect_notion

    connect_notion(args)


def _connect_notebooklm(args: argparse.Namespace) -> None:
    from folio_notion.commands.connect_notebooklm import connect_notebooklm

    connect_notebooklm(args)


def _cmd_status(args: argparse.Namespace) -> None:
    from folio_notion.commands.status import print_status

    print_status(args)


if __name__ == "__main__":
    main()
