#!/usr/bin/env python3
"""
Generate seed PDFs for new donor RAG corpora (FCDO, AFD, JICA, ADB).

Usage:
    python scripts/generate_new_donor_seed_pdfs.py

Output: docs/rag_seed_corpus/{fcdo,afd,jica,adb}/*.pdf

Requires: reportlab (pip install reportlab)
"""

from __future__ import annotations

import sys
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parent.parent
CORPUS_DIR = REPO_ROOT / "docs" / "rag_seed_corpus"

DONORS = ["fcdo", "afd", "jica", "adb"]


def _build_pdf_from_txt(txt_path: Path) -> Path:
    try:
        from reportlab.lib.pagesizes import letter
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.lib.units import inch
        from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer
    except ImportError:
        print("ERROR: reportlab not installed. Run: pip install reportlab", file=sys.stderr)
        sys.exit(1)

    pdf_path = txt_path.with_suffix(".pdf")
    text = txt_path.read_text(encoding="utf-8")

    doc = SimpleDocTemplate(
        str(pdf_path),
        pagesize=letter,
        rightMargin=inch,
        leftMargin=inch,
        topMargin=inch,
        bottomMargin=inch,
    )
    styles = getSampleStyleSheet()
    story = []

    for line in text.splitlines():
        stripped = line.strip()
        if not stripped:
            story.append(Spacer(1, 6))
            continue
        if line == stripped and len(stripped) < 80 and not stripped.endswith("."):
            style = styles["Heading2"]
        else:
            style = styles["BodyText"]
        story.append(Paragraph(stripped, style))

    doc.build(story)
    return pdf_path


def main() -> None:
    generated = 0
    skipped = 0

    for donor in DONORS:
        donor_dir = CORPUS_DIR / donor
        if not donor_dir.exists():
            print(f"  WARNING: {donor_dir} not found, skipping")
            continue

        txt_files = sorted(donor_dir.glob("*.txt"))
        if not txt_files:
            print(f"  WARNING: no .txt files in {donor_dir}")
            continue

        for txt_path in txt_files:
            pdf_path = txt_path.with_suffix(".pdf")
            if pdf_path.exists():
                print(f"  skip (exists): {pdf_path.name}")
                skipped += 1
                continue
            print(f"  generating: {pdf_path.name} ...")
            _build_pdf_from_txt(txt_path)
            print(f"  ok: {pdf_path.name}")
            generated += 1

    print(f"\nDone. Generated: {generated}, skipped (already exist): {skipped}")
    print("Next: run docs/rag_seed_corpus/bulk_ingest_seed_corpus.sh with DONOR_IDS=fcdo,afd,jica,adb")


if __name__ == "__main__":
    main()
