"""One run: configure → ingest PDFs → auth → NotebookLM → export file → Notion."""

from __future__ import annotations

import logging
from collections.abc import Sequence
from pathlib import Path

from folio_notion.exceptions import PipelineStepError
from folio_notion.logging_config import setup_logging
from folio_notion.pipeline_context import PipelineContext
from folio_notion.steps import (
    capture,
    configure,
    ensure_auth,
    ingest_pdf,
    notebook,
    notion,
    prompt,
    wait,
    write_file,
)

log = logging.getLogger(__name__)


def _run_step(step: str, fn, ctx: PipelineContext) -> None:
    try:
        fn(ctx)
    except PipelineStepError:
        raise
    except Exception as e:
        raise PipelineStepError(step, str(e)) from e


def run_pipeline(
    project_root: Path | None = None,
    *,
    dry_run: bool = False,
    skip_notion: bool = False,
    cli_pdf_paths: Sequence[Path] | None = None,
) -> PipelineContext:
    """Execute the full sequence; returns context (paths, ids, URLs) for callers."""
    setup_logging()

    root = (project_root or Path.cwd()).resolve()
    ctx = PipelineContext(project_root=root)
    ctx.dry_run = dry_run
    ctx.skip_notion = skip_notion
    ctx.cli_pdf_paths = list(cli_pdf_paths) if cli_pdf_paths else []

    _run_step("configure", configure.run, ctx)

    if dry_run:
        _run_step("ensure_auth", ensure_auth.run, ctx)
        log.info("Dry run complete (skipped ingest, NotebookLM, export, Notion).")
        return ctx

    _run_step("ingest_pdf", ingest_pdf.run, ctx)
    _run_step("ensure_auth", ensure_auth.run, ctx)

    _run_step("notebook", notebook.run, ctx)
    _run_step("wait", wait.run, ctx)
    _run_step("prompt", prompt.run, ctx)
    _run_step("capture", capture.run, ctx)

    _run_step("write_file", write_file.run, ctx)
    _run_step("notion", notion.run, ctx)

    return ctx
