#!/usr/bin/env python3
"""Build docs/**/*.pdf for every docs/**/*.md (recursive; skips _pdf_build/)."""

from __future__ import annotations

import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
DOCS = ROOT / "docs"
sys.path.insert(0, str(Path(__file__).resolve().parent))

from md_to_pdf import build_pdf_from_markdown  # noqa: E402

SUBTITLE = {
    "20260602_REVERSE_SSH_proposals_summary.md": "Generated from markdown — rev. 1–3 + appendices WG test/production",
    "20260607-2FA-email-mobile-auth-flow.md": "Email forwarding + registration/2FA — alpha must-have",
    "20260608_ALPHA_PRIORITIES.md": "Master alpha priority plan — 2026-06-08 renumber",
    "20260608_STREAM_DUMP_DEBUG.md": "FR 0.1 stream dump while casting",
    "OPEN_TASKS_GRAPH.md": "Open tasks dependency graph — alpha critical path",
    "GIT_FLOW.md": "Branches, next, release — from markdown",
    "REMOTE_ACCESS_IMPL.md": "WireGuard v1 — implementation and deploy",
    "REMOTE_ACCESS_VALIDATION.md": "Linux CLI validation — device sim + E2E",
    "INFRA.md": "Production topology — FE, BE, ports",
    "20260610_SERVICES.md": "Exposed services catalog — URLs, APIs, validation — 2026-06-10",
}

SUBTITLE_BY_REL = {
    "specs/20100611_3_url_shortener.md": "URL shortener service — SPEC (post-alpha, s.f0xx.org)",
    "DRs/20100611_3_url_shortener.md": "URL shortener service — design review",
    "specs/20100612_1_scaling.md": "Platform scaling — SPEC (clusters, bandwidth, GEO, cloud path)",
    "DRs/20100612_1_scaling.md": "Platform scaling — DR (architecture, bandwidth, GEO policy, task graph)",
}


def iter_markdown_files() -> list[Path]:
    out: list[Path] = []
    for md in sorted(DOCS.rglob("*.md")):
        if "_pdf_build" in md.parts or "drafts" in md.parts:
            continue
        out.append(md)
    return out


def rel_label(md: Path) -> str:
    try:
        return str(md.relative_to(DOCS))
    except ValueError:
        return md.name


def main() -> int:
    md_files = iter_markdown_files()
    if not md_files:
        print("No markdown files in docs/", file=sys.stderr)
        return 1
    ok = 0
    for md in md_files:
        out = md.with_suffix(".pdf")
        rel = rel_label(md)
        subtitle = SUBTITLE_BY_REL.get(rel, SUBTITLE.get(md.name, f"From {rel}"))
        try:
            build_pdf_from_markdown(md, out, doc_subtitle=subtitle)
            ok += 1
        except Exception as e:
            print(f"FAIL {rel_label(md)}: {e}", file=sys.stderr)
    print(f"Built {ok}/{len(md_files)} PDFs under docs/")
    return 0 if ok == len(md_files) else 1


if __name__ == "__main__":
    raise SystemExit(main())
