#!/usr/bin/env python3
"""P0 baseline gallery: render ALL current brief figures onto A4 pages (WeasyPrint,
PNG path = proven embed route) + one SVG spike page, so the owner can judge the
current chart state in one folder. Writes ONLY under design/figures/_baseline_gallery/."""
import os, glob, shutil, sys

FIG_ROOT = os.path.dirname(os.path.abspath(__file__))
GAL = os.path.join(FIG_ROOT, "_baseline_gallery")
os.makedirs(GAL, exist_ok=True)

ORDER = ["MLI", "KEN", "SOM", "CMR", "ETH", "MRT", "NGA", "SDN", "TCD", "UGA"]
TITLES = {
    "FIG-GDP": "Livestock's contribution to the economy",
    "FIG-POP-TREND": "Livestock population by species, over time",
    "FIG-HERD-COMP": "Herd composition, latest year (by head and by TLU)",
    "FIG-SYSTEM": "Share of national herd by production system",
    "FIG-INCOME": "Livestock share of pastoral household income",
    "FIG-EMPLOY": "Employment in livestock (direct + indirect)",
    "FIG-TRADE-ICEBERG": "Livestock trade: formal vs informal",
    "FIG-EXPORT-TREND": "Livestock export value, over time",
    "FIG-NUTRITION": "Animal-source food & nutrition",
    "FIG-GAPS": "Key data gaps by category",
}

# ── 1. copy PNGs into per-country gallery folders ──────────────────────────
copied = {}
for iso in ORDER:
    srcs = sorted(glob.glob(os.path.join(FIG_ROOT, iso, "*.png")))
    if not srcs:
        continue
    dst = os.path.join(GAL, iso)
    os.makedirs(dst, exist_ok=True)
    for s in srcs:
        shutil.copy2(s, os.path.join(dst, os.path.basename(s)))
    copied[iso] = [os.path.basename(s) for s in srcs]

# ── 2. combined A4 HTML (PNG pages + one SVG spike) ────────────────────────
CSS = """
@page { size: A4; margin: 14mm; @bottom-center { content: counter(page) " / " counter(pages); font-size: 8pt; color: #6B7280; } }
body { font-family: 'DejaVu Sans', sans-serif; color: #111827; margin: 0; }
.figpage { break-after: page; }
.figpage svg, .figpage img { max-width: 100%; height: auto; }
h1 { font-size: 15pt; margin: 0 0 2mm 0; }
h2 { font-size: 11pt; color: #13452A; margin: 0 0 1mm 0; }
.cty { font-size: 8pt; color: #6B7280; text-transform: uppercase; letter-spacing: .08em; margin-bottom: 2mm; }
.spike h2 { color: #9F2241; }
"""

pages = []
pages.append('<div class="figpage"><h1>Brief figures — BASELINE GALLERY (before)</h1>'
             f'<p class="cty">Generated {__import__("datetime").date.today()} · 72 figures · '
             'PNG @300dpi rendered on A4 via WeasyPrint · final section = SVG-in-WeasyPrint spike</p></div>')
for iso in ORDER:
    for fn in copied.get(iso, []):
        fig = os.path.splitext(fn)[0]
        p = os.path.join(iso, fn)
        pages.append(
            f'<div class="figpage"><div class="cty">{iso}</div>'
            f'<h2>{fig} — {TITLES.get(fig, "")}</h2>'
            f'<img src="{os.path.join(FIG_ROOT, iso, fn)}"></div>')
# SVG spike: embed ONE svg directly to test WeasyPrint's SVG text rendering
svg_path = os.path.join(FIG_ROOT, "KEN", "FIG-GDP.svg")
pages.append(
    f'<div class="figpage spike"><div class="cty">SPIKE — SVG embedded directly (WeasyPrint native SVG renderer)</div>'
    f'<h2>KEN FIG-GDP as inline SVG (text-as-text test)</h2>'
    f'<img src="{svg_path}"></div>')

html = ("<html><head><meta charset='utf-8'><style>" + CSS + "</style></head><body>"
        + "".join(pages) + "</body></html>")
open(os.path.join(GAL, "_gallery.html"), "w", encoding="utf-8").write(html)

# ── 3. render PDF ───────────────────────────────────────────────────────────
from weasyprint import HTML
out_pdf = os.path.join(GAL, "before-gallery-A4.pdf")
doc = HTML(string=html, base_url=GAL).render()
doc.write_pdf(out_pdf)
n = len(doc.pages)
print(f"gallery PDF: {out_pdf} ({n} pages, {os.path.getsize(out_pdf):,} bytes)")
for iso in ORDER:
    print(f"  {iso}: {len(copied.get(iso, []))} figures")