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

from __future__ import annotations

import sys
from pathlib import Path

_BUILD_DIR = Path(__file__).resolve().parent
if (_BUILD_DIR.parent / "docs").is_dir():
    ROOT = _BUILD_DIR.parent
    DOCS = ROOT / "docs"
else:
    ROOT = _BUILD_DIR.parent
    DOCS = ROOT

sys.path.insert(0, str(_BUILD_DIR))
from md_to_pdf import build_pdf_from_markdown  # noqa: E402

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)",
    "DRs/20260618_repos_reorganizing.md": "Repository & microservice split — frozen DR R1.1",
    "specs/20260618_repos_reorganizing.md": "Repository & microservice split — SPEC R1 (normative)",
    "20260620_postgres_timescale_db_platform.md": "PostgreSQL, TimescaleDB, platform DB adapters — advisory",
}


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 found", 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, f"From {rel}")
        try:
            build_pdf_from_markdown(md, out, doc_subtitle=subtitle)
            ok += 1
        except Exception as e:
            print(f"FAIL {rel}: {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())
