#!/usr/bin/env python3
"""Owner review galleries: ONE PDF per chart type, one page per country.
Left = BEFORE (canonical, _baseline_gallery = main state) · Right = AFTER (current tree).
Regenerate after any single-chart fix:  python3 design/figures/make_type_review_galleries.py
Writes ONLY under design/figures/_review/. Pure matplotlib — seconds, no model calls."""
import os, re, glob
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.patches as mpatches


def rdimg(p):
    """Robust image read: plt.imread can return str for certain inputs; force via PIL."""
    from PIL import Image
    import numpy as np
    return np.asarray(Image.open(p).convert("RGBA"))

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

ORDER = ["MLI", "KEN", "SOM", "CMR", "ETH", "MRT", "NGA", "SDN", "TCD", "UGA"]
CTY = {"MLI": "Mali", "KEN": "Kenya", "SOM": "Somalia", "CMR": "Cameroon", "ETH": "Ethiopia",
       "MRT": "Mauritania", "NGA": "Nigeria", "SDN": "Sudan", "TCD": "Chad", "UGA": "Uganda"}
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",
}


def skip_reason(iso, fig):
    p = os.path.join(FIG_ROOT, "..", "figure-data", iso, fig + ".md")
    if os.path.exists(p):
        m = re.search(r"\*\*(?:Data-gap reason|Status):\*\* (.+)", open(p, encoding="utf-8").read())
        if m:
            return m.group(1).strip()
    return "not built in the current tree"


def wrap(t, w=62):
    import textwrap
    return "\n".join(textwrap.wrap(t, width=w))


def build_type(fig):
    pages = []
    for iso in ORDER:
        b = os.path.join(GAL, iso, fig + ".png")
        a = os.path.join(FIG_ROOT, iso, fig + ".png")
        if not (os.path.exists(b) or os.path.exists(a)):
            continue
        pages.append((iso, b if os.path.exists(b) else None, a if os.path.exists(a) else None))
    if not pages:
        return None
    pdf_path = os.path.join(OUT, fig + ".review.pdf")
    with PdfPages(pdf_path) as pdf:
        # ── cover page ──
        f = plt.figure(figsize=(11.69, 8.27))
        f.text(0.5, 0.62, fig + " — " + TITLES.get(fig, ""), ha="center", fontsize=20,
               fontweight="bold", color="#1A5632")
        f.text(0.5, 0.52, "Before (left) = current canonical · After (right) = current development state",
               ha="center", fontsize=11, color="#555555")
        n_b = sum(1 for _, b, _ in pages if b)
        n_a = sum(1 for _, _, a in pages if a)
        f.text(0.5, 0.44, f"{len(pages)} countries on the following pages · {n_b} with a before panel · "
               f"{n_a} with an after panel", ha="center", fontsize=10, color="#777777")
        missing = [CTY[i] for i, _, a in pages if a is None]
        if missing:
            f.text(0.5, 0.38, "AFTER not built (gate skip / dropped): " + ", ".join(missing),
                   ha="center", fontsize=9, color="#8B1E3F")
        pdf.savefig(f)
        plt.close(f)
        # ── one page per country ──
        for iso, b, a in pages:
            f = plt.figure(figsize=(11.69, 8.27))
            f.text(0.5, 0.955, f"{fig} · {CTY[iso]} ({iso})", ha="center", fontsize=14,
                   fontweight="bold", color="#1A5632")
            if b:
                ax = f.add_axes([0.02, 0.03, 0.47, 0.88])
                ax.axis("off")
                ax.imshow(rdimg(b))
                ax.set_title("BEFORE — canonical (main)", fontsize=10, color="#333333", pad=6)
            else:
                f.text(0.255, 0.47, "no baseline", ha="center", fontsize=11, color="#999999")
            if a:
                ax = f.add_axes([0.51, 0.03, 0.47, 0.88])
                ax.axis("off")
                ax.imshow(rdimg(a))
                ax.set_title("AFTER — current state", fontsize=10, color="#1A5632", pad=6)
            else:
                r = skip_reason(iso, fig)
                f.text(0.745, 0.50, "NOT BUILT\n\n" + wrap(r, 46), ha="center", va="center",
                       fontsize=9.5, color="#8B1E3F",
                       bbox=dict(boxstyle="round,pad=0.6", facecolor="#F7F3EE",
                                 edgecolor="#C9B458"))
                f.text(0.745, 0.90, "AFTER — current state", ha="center", fontsize=10, color="#1A5632")
            pdf.savefig(f)
            plt.close(f)
    return pdf_path, len(pages) + 1


if __name__ == "__main__":
    import sys
    # Owner rule (2026-09-09): regenerate ONLY the chart type(s) actually enhanced,
    # so the owner can see exactly which review PDF changed. Pass FIG-ids as args,
    # e.g.  python3 design/figures/make_type_review_galleries.py FIG-EMPLOY FIG-GDP
    only = [a for a in sys.argv[1:] if a in TITLES]
    if sys.argv[1:] and not only:
        print("no matching chart types among:", ", ".join(sys.argv[1:]))
        sys.exit(2)
    figs = only or sorted(TITLES)
    made = []
    for fig in figs:
        r = build_type(fig)
        if r:
            made.append((fig, r[1]))
            print(f"  {fig}.review.pdf  ({r[1]} pages)")
        else:
            print(f"  {fig}: skipped (no before/after panels anywhere)")
    print(f"\n{len(made)} review PDFs -> {OUT}")