#!/usr/bin/env python3
"""Generate 1600x900 SVG/PNG explanatory figures and verify math for CMU ANLP Lecture 14 (v1 r2)."""

from __future__ import annotations

from pathlib import Path
import html as html_lib
import json
import math
import struct
import subprocess
import tempfile
import xml.etree.ElementTree as ET

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from scipy.stats import norm

OUT_DIR = Path(__file__).resolve().parent
CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
FONT = "Helvetica Neue, Helvetica, Arial, sans-serif"

PALETTE = {
    "background": "#FAF6EE",
    "ink": "#1F2A2E",
    "muted": "#4A453F",
    "blue": "#356482",
    "terracotta": "#B5493A",
    "terracotta_text": "#9E382B",
    "sage": "#4B6B46",
    "sage_text": "#354D32",
    "ochre": "#A87919",
    "ochre_text": "#7C580F",
    "grid": "#DDD5C7",
    "card": "#F3ECE0",
}

STYLE_RC = {
    "font.family": "sans-serif",
    "font.sans-serif": ["Helvetica Neue", "Helvetica", "Arial", "DejaVu Sans"],
    "svg.fonttype": "none",
    "axes.edgecolor": PALETTE["muted"],
    "axes.linewidth": 1.1,
    "text.color": PALETTE["ink"],
    "axes.labelcolor": PALETTE["ink"],
    "xtick.color": PALETTE["muted"],
    "ytick.color": PALETTE["muted"],
}


def compute_verified_math() -> dict:
    """Independently compute and cross-check Lecture 14 power analysis, IAA, and constructed checks."""
    z_a2 = float(norm.ppf(1.0 - 0.05 / 2.0))
    z_b = float(norm.ppf(0.80))
    z_sum_sq = (z_a2 + z_b) ** 2

    # Slide 45: pilot n=156, displayed omega^2=0.077, alpha=0.05, power=0.80, delta=0.03
    n_slide45_exact_from_0077 = z_sum_sq * 0.077 / (0.03 ** 2)

    # Course power.ipynb: displayed omega^2_hat = 0.1161; unrounded binary pilot 18/155 = 0.11612903...
    power_nb_deltas = [0.010, 0.015, 0.020, 0.030]
    power_nb_from_displayed = {
        str(d): int(math.ceil(z_sum_sq * 0.1161 / (d ** 2)))
        for d in power_nb_deltas
    }
    power_nb_from_18_155 = {
        str(d): int(math.ceil(z_sum_sq * (18.0 / 155.0) / (d ** 2)))
        for d in power_nb_deltas
    }

    # Miller (2024) Sec. 5: deterministic omega^2=1/9, delta=0.03 -> 969 (Sec 4.2 moments give 1/12 -> 727)
    n_miller_det_1_9 = int(math.ceil(z_sum_sq * (1.0 / 9.0) / (0.03 ** 2)))
    n_miller_det_1_12 = int(math.ceil(z_sum_sq * (1.0 / 12.0) / (0.03 ** 2)))

    # Miller (2024) Sec. 5: nondeterministic n=198, omega^2=1/9, sigma_A^2=sigma_B^2=1/6
    mde_k = {}
    for k in (1, 2, 5, 10, 20, 50):
        mde = (z_a2 + z_b) * math.sqrt((1.0 / 9.0 + (1.0 / 6.0) / k + (1.0 / 6.0) / k) / 198.0)
        mde_k[str(k)] = round(mde * 100.0, 2)
    mde_asymptote_1_9 = round((z_a2 + z_b) * math.sqrt((1.0 / 9.0) / 198.0) * 100.0, 2)
    mde_asymptote_1_12 = round((z_a2 + z_b) * math.sqrt((1.0 / 12.0) / 198.0) * 100.0, 2)

    # Slide 15 Bernoulli plug-in SEs (p = 0.86)
    se_slide15 = {str(n): round(math.sqrt(0.86 * 0.14 / n), 4) for n in (100, 156, 500, 1000, 2000, 5000)}

    # Course iaa.ipynb: reproduce exact rng(2025) simulation and B=3000 rng(7) bootstrap CI
    rng_sim = np.random.default_rng(2025)
    n_iaa = 674
    true_label = rng_sim.binomial(1, 0.5, size=n_iaa)
    latent = rng_sim.normal(size=n_iaa)
    err1 = latent + rng_sim.normal(scale=1.0, size=n_iaa) > 2.0
    err2 = latent + rng_sim.normal(scale=1.0, size=n_iaa) > 1.8
    r1 = np.where(err1, 1 - true_label, true_label)
    r2 = np.where(err2, 1 - true_label, true_label)
    c00 = int(np.sum((r1 == 0) & (r2 == 0)))
    c01 = int(np.sum((r1 == 0) & (r2 == 1)))
    c10 = int(np.sum((r1 == 1) & (r2 == 0)))
    c11 = int(np.sum((r1 == 1) & (r2 == 1)))

    po = (c00 + c11) / n_iaa
    pA0, pA1 = (c00 + c01) / n_iaa, (c10 + c11) / n_iaa
    pB0, pB1 = (c00 + c10) / n_iaa, (c01 + c11) / n_iaa
    pe = pA0 * pB0 + pA1 * pB1
    kappa = (po - pe) / (1.0 - pe)

    rng_boot = np.random.default_rng(7)
    boot_k = np.empty(3000)
    for b in range(3000):
        idx = rng_boot.integers(0, n_iaa, size=n_iaa)
        b1, b2 = r1[idx], r2[idx]
        bc00 = np.sum((b1 == 0) & (b2 == 0))
        bc01 = np.sum((b1 == 0) & (b2 == 1))
        bc10 = np.sum((b1 == 1) & (b2 == 0))
        bc11 = np.sum((b1 == 1) & (b2 == 1))
        bpo = (bc00 + bc11) / n_iaa
        bpe = ((bc00 + bc01) * (bc00 + bc10) + (bc10 + bc11) * (bc01 + bc11)) / (n_iaa ** 2)
        boot_k[b] = (bpo - bpe) / (1.0 - bpe)
    ci_lo = float(np.quantile(boot_k, 0.025))
    ci_hi = float(np.quantile(boot_k, 0.975))

    # Constructed prevalence-paradox check (not lecture data): fixed p_o = 0.85, symmetric marginals p
    prevalence_check = {}
    for p in (0.50, 0.70, 0.85, 0.90, 0.915, 0.925):
        pe_c = p ** 2 + (1.0 - p) ** 2
        kap_c = (0.85 - pe_c) / (1.0 - pe_c)
        prevalence_check[f"p={p:.3f}"] = {
            "po": 0.85,
            "pe": round(pe_c, 4),
            "kappa": round(kap_c, 5),
        }

    return {
        "z_constants": {
            "z_alpha_over_2": round(z_a2, 6),
            "z_beta": round(z_b, 6),
            "z_sum_sq": round(z_sum_sq, 4),
        },
        "slide15_bernoulli_se_p086": se_slide15,
        "slide45_power": {
            "omega2_printed": 0.077,
            "n_from_rounded_0077_ceil": int(math.ceil(n_slide45_exact_from_0077)),
            "n_from_rounded_0077_exact": round(n_slide45_exact_from_0077, 4),
            "n_printed_slide45": 674,
        },
        "power_ipynb_saved_snapshot": {
            "saved_notebook_printed_n": {"0.01": 9115, "0.015": 4052, "0.02": 2279, "0.03": 1013},
            "recomputed_from_displayed_01161": power_nb_from_displayed,
            "recomputed_from_18_over_155": power_nb_from_18_155,
        },
        "miller_sec5": {
            "stipulated_omega2_1_9_delta_003_n": n_miller_det_1_9,
            "sec42_implied_omega2_1_12_delta_003_n": n_miller_det_1_12,
            "nondet_n198_mde_pp_by_K_using_1_9": mde_k,
            "nondet_n198_floor_pp_using_1_9": mde_asymptote_1_9,
            "nondet_n198_floor_pp_using_1_12": mde_asymptote_1_12,
        },
        "iaa_ipynb_reproduced_674": {
            "confusion_matrix": [[c00, c01], [c10, c11]],
            "n": n_iaa,
            "p_A_pos": round(pA1, 4),
            "p_B_pos": round(pB1, 4),
            "po": round(po, 4),
            "pe": round(pe, 4),
            "kappa": round(kappa, 4),
            "bootstrap_95ci_reproduced": [round(ci_lo, 4), round(ci_hi, 4)],
        },
        "constructed_prevalence_paradox_po_085": prevalence_check,
    }


def save_opaque_rgb_png(fig: plt.Figure, png_path: Path, dpi: int = 200) -> None:
    """Save figure as an opaque RGB PNG (zero alpha) matching image_metadata standards."""
    tmp_png = png_path.with_suffix(".tmp.png")
    fig.savefig(tmp_png, format="png", dpi=dpi, facecolor=PALETTE["background"])
    with Image.open(tmp_png) as im:
        im.convert("RGB").save(png_path, format="PNG")
    tmp_png.unlink()


def fig_power_sample_size_and_mde(math_data: dict) -> tuple[Path, Path]:
    """Figure 1 (Lead cover): Power scaling 1/delta^2 (left) and resampling K MDE floor (right)."""
    fig = plt.figure(figsize=(8.0, 4.5), dpi=200, facecolor=PALETTE["background"])
    fig.text(
        0.042, 0.928,
        "Halving the Detectable Effect Quadruples Required Eval Items (4x)",
        fontsize=17.0, fontweight="bold", color=PALETTE["ink"], va="center",
    )
    fig.text(
        0.042, 0.870,
        "80% Power, alpha = 0.05: n Scales as 1/delta^2 (2 -> 1 pp jumps 2,279 -> 9,115); Resampling K Hits omega^2 Floor",
        fontsize=9.7, fontweight="bold", color=PALETTE["sage_text"], va="center",
    )

    gs = fig.add_gridspec(1, 2, wspace=0.22, left=0.095, right=0.975, top=0.785, bottom=0.155)

    # --- Panel A: Required n vs MDE delta (log10 y-axis, points + curves, no bars) ---
    ax1 = fig.add_subplot(gs[0, 0])
    ax1.set_facecolor(PALETTE["card"])
    for spine in ("top", "right"):
        ax1.spines[spine].set_visible(False)

    z_sum_sq = math_data["z_constants"]["z_sum_sq"]
    deltas_pp = np.linspace(0.95, 3.28, 200)
    deltas = deltas_pp / 100.0

    # Course notebook omega^2 = 0.1161 (solid blue curve + saved snapshot circle markers)
    n_nb_curve = z_sum_sq * (18.0 / 155.0) / (deltas ** 2)
    ax1.plot(deltas_pp, n_nb_curve, color=PALETTE["blue"], lw=2.3, ls="-",
             label="Formula curve + saved power.ipynb pts", zorder=3)
    nb_saved = math_data["power_ipynb_saved_snapshot"]["saved_notebook_printed_n"]
    nb_pts_x = [1.0, 1.5, 2.0, 3.0]
    nb_pts_y = [nb_saved["0.01"], nb_saved["0.015"], nb_saved["0.02"], nb_saved["0.03"]]
    ax1.scatter(nb_pts_x, nb_pts_y, color=PALETTE["blue"], edgecolor=PALETTE["background"],
                linewidth=1.1, s=56, marker="o", zorder=5)

    # Slide 45 omega^2 = 0.077 (dashed sage curve + printed point at 3.0 pp)
    n_s45_curve = z_sum_sq * 0.077 / (deltas ** 2)
    ax1.plot(deltas_pp, n_s45_curve, color=PALETTE["sage"], lw=2.0, ls="--",
             label="Curve (0.077) + Slide 45 pt (674)", zorder=2)
    ax1.scatter([3.0], [math_data["slide45_power"]["n_printed_slide45"]],
                color=PALETTE["sage"], edgecolor=PALETTE["background"],
                linewidth=1.1, s=72, marker="D", zorder=6)

    # Miller Sec 5 omega^2 = 1/9 at delta = 3.0 pp (slightly nudged x only? No—keep exact x=3.0, use hollow/smaller offset? Better: keep exact x=3.0 and label both cleanly!)
    n_miller_1_9 = math_data["miller_sec5"]["stipulated_omega2_1_9_delta_003_n"]
    ax1.scatter([3.0], [n_miller_1_9], color=PALETTE["terracotta"], edgecolor=PALETTE["background"],
                linewidth=1.1, s=54, marker="s", zorder=7,
                label="Miller Sec. 5 pt (omega^2 = 1/9)")

    ax1.set_yscale("log", base=10)
    ax1.set_ylim(420, 16500)
    ax1.set_xlim(0.84, 3.36)
    ax1.set_xticks([1.0, 1.5, 2.0, 2.5, 3.0])
    ax1.set_yticks([500, 1000, 2000, 4000, 10000])
    ax1.get_yaxis().set_major_formatter(mpl.ticker.FuncFormatter(lambda v, _: f"{int(v):,}"))
    ax1.grid(True, which="major", color=PALETTE["grid"], lw=0.8)
    ax1.set_title("A. Required Paired Items vs. Target Effect", fontsize=11.0, fontweight="bold", loc="left", pad=8)
    ax1.set_xlabel("Minimum detectable difference delta (pp)", fontsize=9.5, fontweight="bold")
    ax1.set_ylabel("Required items n (log10 scale)", fontsize=9.5, fontweight="bold")

    # Connect actual 2.0 pp (2,279) and 1.0 pp (9,115) observations with an explicit dashed comparison step + callout
    ax1.plot([1.0, 2.0], [9115, 2279], color=PALETTE["terracotta_text"], lw=1.4, ls=":", zorder=4)
    ax1.annotate(
        "delta = 1.0 pp\nn = 9,115",
        xy=(1.0, 9115), xytext=(1.03, 12200),
        fontsize=8.6, fontweight="bold", color=PALETTE["blue"],
        arrowprops=dict(arrowstyle="->", color=PALETTE["blue"], lw=1.2),
    )
    ax1.annotate(
        "delta = 2.0 pp\nn = 2,279",
        xy=(2.0, 2279), xytext=(2.16, 3300),
        fontsize=8.6, fontweight="bold", color=PALETTE["blue"],
        arrowprops=dict(arrowstyle="->", color=PALETTE["blue"], lw=1.2),
    )
    ax1.text(
        1.03, 1040,
        "2.0 -> 1.0 pp (dotted):\nn jumps 4.0x (fixed design)",
        fontsize=8.1, fontweight="bold", color=PALETTE["terracotta_text"],
        bbox=dict(boxstyle="round,pad=0.26", fc=PALETTE["background"], ec=PALETTE["terracotta"], lw=1.0),
    )
    # Disambiguate 1,013 vs 969 at 3.0 pp and Slide 45 674
    ax1.annotate(
        "3.0 pp: 1,013 (nb) / 969 (Miller)",
        xy=(3.0, 1013), xytext=(2.20, 2020),
        fontsize=7.9, fontweight="bold", color=PALETTE["terracotta_text"],
        arrowprops=dict(arrowstyle="->", color=PALETTE["terracotta_text"], lw=1.0),
    )
    ax1.annotate(
        "Slide 45: 674 printed\n(672 from 0.077)",
        xy=(3.0, 674), xytext=(1.98, 475),
        fontsize=8.0, fontweight="bold", color=PALETTE["sage_text"],
        arrowprops=dict(arrowstyle="->", color=PALETTE["sage_text"], lw=1.1),
    )
    ax1.legend(loc="upper right", fontsize=7.2, frameon=True, facecolor=PALETTE["background"], edgecolor=PALETTE["grid"])

    # --- Panel B: Resampling K_A = K_B shrinks MDE at fixed n = 198 (zero-baseline y-axis) ---
    ax2 = fig.add_subplot(gs[0, 1])
    ax2.set_facecolor(PALETTE["card"])
    for spine in ("top", "right"):
        ax2.spines[spine].set_visible(False)

    ks = np.array([1, 2, 3, 5, 8, 10, 15, 20, 30, 50])
    mde_vals = (norm.ppf(0.975) + norm.ppf(0.80)) * np.sqrt((1.0 / 9.0 + (1.0 / 6.0) / ks + (1.0 / 6.0) / ks) / 198.0) * 100.0
    floor_pp = math_data["miller_sec5"]["nondet_n198_floor_pp_using_1_9"]

    ax2.axhspan(0, floor_pp, color=PALETTE["sage"], alpha=0.10, label=f"Irreducible floor ({floor_pp:.2f} pp, omega^2=1/9)")
    ax2.axhline(floor_pp, color=PALETTE["sage"], lw=1.6, ls="--")
    ax2.plot(ks, mde_vals, color=PALETTE["terracotta"], lw=2.3, marker="s", markersize=5.6,
             markeredgecolor=PALETTE["background"], markeredgewidth=0.9,
             label="Author curve (Miller Sec. 5: n=198, s^2=1/6)")

    ax2.set_ylim(0, 16.0)
    ax2.set_xlim(-1, 52)
    ax2.set_xticks([1, 10, 20, 30, 40, 50])
    ax2.grid(True, color=PALETTE["grid"], lw=0.8)
    ax2.set_title("B. Resampling K Cuts Decoding Noise (n = 198)", fontsize=11.0, fontweight="bold", loc="left", pad=8)
    ax2.set_xlabel("Samples per question (K_A = K_B)", fontsize=9.5, fontweight="bold")
    ax2.set_ylabel("Minimum detectable effect delta (pp)", fontsize=9.5, fontweight="bold")

    ax2.annotate(
        f"K = 1: {mde_vals[0]:.1f} pp (Miller: 13.2%)",
        xy=(1.2, mde_vals[0]), xytext=(6.0, 11.4),
        fontsize=8.5, fontweight="bold", color=PALETTE["terracotta_text"],
        arrowprops=dict(arrowstyle="->", color=PALETTE["terracotta_text"], lw=1.1),
    )
    k10_idx = int(np.where(ks == 10)[0][0])
    ax2.annotate(
        f"K = 10: {mde_vals[k10_idx]:.1f} pp (Miller: 7.5%)",
        xy=(10, mde_vals[k10_idx]), xytext=(16.5, 9.7),
        fontsize=8.5, fontweight="bold", color=PALETTE["terracotta_text"],
        arrowprops=dict(arrowstyle="->", color=PALETTE["terracotta_text"], lw=1.1),
    )
    ax2.annotate(
        f"Floor as K -> inf: {floor_pp:.2f} pp\n(only more questions n lower this)",
        xy=(38, floor_pp), xytext=(12.5, 2.2),
        fontsize=8.4, fontweight="bold", color=PALETTE["sage_text"],
        arrowprops=dict(arrowstyle="->", color=PALETTE["sage_text"], lw=1.1),
    )
    ax2.legend(loc="upper right", fontsize=7.2, frameon=True, facecolor=PALETTE["background"], edgecolor=PALETTE["grid"])

    fig.text(
        0.042, 0.032,
        "Sources: Saved power.ipynb pts (omega^2=0.1161), Slide 45 pt (674), Miller Sec. 5 (omega^2=1/9) + author curves. Left: log10 pts; right: zero baseline.",
        fontsize=7.5, color=PALETTE["muted"],
    )

    svg_path = OUT_DIR / "power-sample-size-and-mde-curves.svg"
    png_path = OUT_DIR / "power-sample-size-and-mde-curves.png"
    fig.savefig(svg_path, format="svg", facecolor=PALETTE["background"])
    save_opaque_rgb_png(fig, png_path, dpi=200)
    plt.close(fig)
    return svg_path, png_path


def fig_research_design_pipeline() -> str:
    """Figure 2 (Diagram): Author synthesis of Lecture 14 research design & validation workflow."""
    elems: list[str] = []

    elems.append(
        '<text x="72" y="136" font-size="23.5" font-weight="700" fill="#356482">'
        'Author Synthesis of CMU ANLP Lecture 14 Experimental Workflow (Slides 7&#8211;58)'
        '</text>'
    )

    cards = [
        {
            "x": 72, "y": 172, "w": 334, "h": 546,
            "num": "1", "title": "Frame & Survey", "color": "#356482", "tc": "#356482",
            "sub": "Slides 19–29",
            "blocks": [
                ("Two Research Modes", "Application: improve system\nCuriosity: explain model / text"),
                ("Idea Discovery", "Bottom-up: fix known failure\nTop-down: start from question\n(avoid solution-seeking-problem)"),
                ("Literature Survey", "ACL Anthology, OpenReview, arXiv\nCaveat (Varian 1994): over-reading\ncan constrain original framing"),
            ],
        },
        {
            "x": 432, "y": 172, "w": 348, "h": 546,
            "num": "2", "title": "Falsifiable Hypotheses", "color": "#9E382B", "tc": "#9E382B",
            "sub": "Slides 31–34",
            "blocks": [
                ("Indirect Trap (Avoid)", "\"Does X make Y better?\" -> \"Yes\"\nIf \"No\", fails to diagnose which\nunderlying assumption broke"),
                ("Mechanism Split (Qi et al.)", "Sub-questions + lecture priors:\nQ1: language family effect?\nQ2: small-data regime gains?\nQ4: cross-lingual alignment?"),
                ("Falsifiability Contract", "State in advance what outcome\nrefutes each assumption"),
            ],
        },
        {
            "x": 806, "y": 172, "w": 354, "h": 546,
            "num": "3", "title": "Power & Annotation Gate", "color": "#354D32", "tc": "#354D32",
            "sub": "Slides 38–52",
            "blocks": [
                ("Deterministic Power (Slide 44–45)", "Pilot n0 = 156 -> estimate omega^2\nn = ceil((z_a/2+z_b)^2 w^2 / d^2)\nw^2=0.077, d=3 pp -> 674 printed"),
                ("Guidelines First", "Self-annotate & document edge\ncases (Penn Treebank POS)\nPilot-hire before full run"),
                ("Quality Gate (Cohen kappa)", "kappa = (p_o - p_e) / (1 - p_e)\nLow kappa -> fix guidelines,\nre-hire, or re-scope task"),
            ],
        },
        {
            "x": 1186, "y": 172, "w": 342, "h": 546,
            "num": "4", "title": "Paired Analysis & Report", "color": "#7C580F", "tc": "#7C580F",
            "sub": "Slides 7–15, 55–58",
            "blocks": [
                ("Paired + Clustered SEs", "Compare on same items (x, yA, yB)\nusing SE = s_d / sqrt(n);\ncluster SE if items share context"),
                ("Look at the Data", "Combine quantitative metrics\nwith qualitative error checks\n(Slide 56: inspect failures)"),
                ("Author Reporting Checklist", "State N, SE / 95% CI, K samples,\nand refuted sub-hypotheses\n(Peyton Jones writing craft, S58)"),
            ],
        },
    ]

    for c in cards:
        x, y, w, h = c["x"], c["y"], c["w"], c["h"]
        elems.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="12" fill="#F3ECE0" stroke="{c["color"]}" stroke-width="2.2" />')
        elems.append(f'<rect x="{x}" y="{y}" width="{w}" height="74" rx="12" fill="{c["color"]}" />')
        elems.append(f'<rect x="{x}" y="{y + 52}" width="{w}" height="22" fill="{c["color"]}" />')
        elems.append(f'<text x="{x + 18}" y="{y + 34}" font-size="21.5" font-weight="700" fill="#FAF6EE">{html_lib.escape(c["num"] + ". " + c["title"])}</text>')
        elems.append(f'<text x="{x + 18}" y="{y + 60}" font-size="16" font-weight="700" fill="#FAF6EE">{html_lib.escape(c["sub"])}</text>')

        by = y + 92
        for btitle, bbody in c["blocks"]:
            lines = bbody.split("\n")
            bh = 44 + len(lines) * 25 + 10
            elems.append(f'<rect x="{x + 14}" y="{by}" width="{w - 28}" height="{bh}" rx="8" fill="#FAF6EE" stroke="#DDD5C7" stroke-width="1.4" />')
            elems.append(f'<text x="{x + 25}" y="{by + 27}" font-size="18" font-weight="700" fill="{c["tc"]}">{html_lib.escape(btitle)}</text>')
            for li, line in enumerate(lines):
                elems.append(f'<text x="{x + 25}" y="{by + 52 + li * 24}" font-size="16" fill="#1F2A2E">{html_lib.escape(line)}</text>')
            by += bh + 14

    for x1, x2 in [(406, 432), (780, 806), (1160, 1186)]:
        ym = 444
        elems.append(f'<line x1="{x1}" y1="{ym}" x2="{x2 - 8}" y2="{ym}" stroke="#1F2A2E" stroke-width="3.2" />')
        elems.append(f'<polygon points="{x2 - 10},{ym - 8} {x2},{ym} {x2 - 10},{ym + 8}" fill="#1F2A2E" />')

    elems.append(
        '<path d="M 1357 718 L 1357 780 L 606 780 L 606 728" '
        'fill="none" stroke="#9E382B" stroke-width="3.0" stroke-dasharray="9 6" />'
    )
    elems.append('<polygon points="598,731 606,718 614,731" fill="#9E382B" />')
    elems.append('<rect x="652" y="758" width="660" height="40" rx="8" fill="#FAF6EE" stroke="#9E382B" stroke-width="1.8" />')
    elems.append(
        '<text x="982" y="784" text-anchor="middle" font-size="17" font-weight="700" fill="#9E382B">'
        'Author Synthesis Loop: Error Analysis Refines Hypotheses &amp; Guidelines'
        '</text>'
    )

    elems.append(
        '<text x="72" y="856" font-size="18.0" fill="#4A453F">'
        'Source: Author synthesis of CMU ANLP Fall 2025 Lecture 14 (Sean Welleck), Slides 7&#8211;58 (Slide 17 returns to Observation).'
        '</text>'
    )

    return f"""<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 900" width="1600" height="900">
  <rect width="1600" height="900" fill="#FAF6EE" />
  <g font-family="{FONT}">
    <text x="72" y="88" font-size="37" font-weight="700" fill="#1F2A2E">Falsifiable Research Loops Test Why a Method Works, Not Just Whether It Wins</text>
    {"".join(elems)}
  </g>
</svg>
"""


def fig_iaa_confusion_and_kappa_paradox(math_data: dict) -> tuple[Path, Path]:
    """Figure 3: Course iaa.ipynb 2x2 matrix (left) + Constructed prevalence paradox curve (right)."""
    iaa = math_data["iaa_ipynb_reproduced_674"]
    (c00, c01), (c10, c11) = iaa["confusion_matrix"]
    n_iaa = iaa["n"]
    po = iaa["po"]
    pe = iaa["pe"]
    kappa = iaa["kappa"]
    ci_lo, ci_hi = iaa["bootstrap_95ci_reproduced"]

    fig = plt.figure(figsize=(8.0, 4.5), dpi=200, facecolor=PALETTE["background"])
    fig.text(
        0.042, 0.928,
        "Raw Agreement Masks Chance; Cohen's Kappa Discounts Marginals",
        fontsize=15.8, fontweight="bold", color=PALETTE["ink"], va="center",
    )
    fig.text(
        0.042, 0.870,
        f"Left: Reproduced iaa.ipynb Run (n = {n_iaa}, kappa = {kappa:.4f}); Right: Constructed Check at Fixed p_o = 0.85",
        fontsize=10.0, fontweight="bold", color=PALETTE["blue"], va="center",
    )

    gs = fig.add_gridspec(1, 2, width_ratios=[1.0, 1.05], wspace=0.28, left=0.055, right=0.975, top=0.785, bottom=0.155)

    # --- Panel A: Confusion Matrix + Decomposition from iaa.ipynb ---
    ax1 = fig.add_subplot(gs[0, 0])
    ax1.set_facecolor(PALETTE["card"])
    ax1.set_xlim(-0.98, 2.55)
    ax1.set_ylim(2.85, -0.82)
    ax1.axis("off")
    ax1.set_title(f"A. Simulated Tweet IAA (iaa.ipynb, n = {n_iaa})", fontsize=10.8, fontweight="bold", loc="left", pad=8)

    cells = [
        (0, 0, c00, f"Agree Not-Pos\n({c00/n_iaa:.1%})", PALETTE["sage"], True),
        (0, 1, c01, f"Disagree\n({c01/n_iaa:.1%})", PALETTE["terracotta"], False),
        (1, 0, c10, f"Disagree\n({c10/n_iaa:.1%})", PALETTE["terracotta"], False),
        (1, 1, c11, f"Agree Pos\n({c11/n_iaa:.1%})", PALETTE["sage"], True),
    ]
    for r, c, val, sub, col, diag in cells:
        alpha = 0.16 if diag else 0.12
        rect = mpl.patches.FancyBboxPatch(
            (c - 0.43, r - 0.41), 0.86, 0.82,
            boxstyle="round,pad=0.02,rounding_size=0.06",
            facecolor=mpl.colors.to_rgba(col, alpha),
            edgecolor=col, linewidth=1.8,
        )
        ax1.add_patch(rect)
        tcol = PALETTE["ink"] if diag else PALETTE["terracotta_text"]
        ax1.text(c, r - 0.10, f"{val}", ha="center", va="center", fontsize=16.5, fontweight="bold", color=tcol)
        ax1.text(c, r + 0.21, sub, ha="center", va="center", fontsize=7.8, color=PALETTE["ink"], fontweight="bold")

    ax1.text(0, -0.62, "R2: Not-Pos (0)", ha="center", va="center", fontsize=8.8, fontweight="bold", color=PALETTE["ink"])
    ax1.text(1, -0.62, "R2: Pos (1)", ha="center", va="center", fontsize=8.8, fontweight="bold", color=PALETTE["ink"])
    ax1.text(2.05, -0.62, "R1 Total", ha="center", va="center", fontsize=8.8, fontweight="bold", color=PALETTE["muted"])
    ax1.text(-0.50, 0, "R1: Not-Pos", ha="right", va="center", fontsize=8.6, fontweight="bold", color=PALETTE["ink"])
    ax1.text(-0.50, 1, "R1: Pos", ha="right", va="center", fontsize=8.6, fontweight="bold", color=PALETTE["ink"])

    r1_0, r1_1 = c00 + c01, c10 + c11
    r2_0, r2_1 = c00 + c10, c01 + c11
    ax1.text(2.05, 0, f"{r1_0}\n({r1_0/n_iaa:.1%})", ha="center", va="center", fontsize=8.8, fontweight="bold", color=PALETTE["blue"])
    ax1.text(2.05, 1, f"{r1_1}\n({r1_1/n_iaa:.1%})", ha="center", va="center", fontsize=8.8, fontweight="bold", color=PALETTE["blue"])
    ax1.text(0, 1.60, f"{r2_0} ({r2_0/n_iaa:.1%})", ha="center", va="center", fontsize=8.6, fontweight="bold", color=PALETTE["blue"])
    ax1.text(1, 1.60, f"{r2_1} ({r2_1/n_iaa:.1%})", ha="center", va="center", fontsize=8.6, fontweight="bold", color=PALETTE["blue"])
    ax1.text(2.05, 1.60, f"n = {n_iaa}", ha="center", va="center", fontsize=8.8, fontweight="bold", color=PALETTE["ink"])

    summary_box = mpl.patches.FancyBboxPatch(
        (-0.88, 1.88), 3.38, 0.88,
        boxstyle="round,pad=0.02,rounding_size=0.06",
        facecolor=PALETTE["background"], edgecolor=PALETTE["grid"], linewidth=1.2,
    )
    ax1.add_patch(summary_box)
    ax1.text(
        0.81, 2.13,
        f"p_o = {c00+c11}/{n_iaa} = {po:.4f}   |   p_e = {pe:.4f}",
        ha="center", va="center", fontsize=8.8, fontweight="bold", color=PALETTE["ink"],
    )
    ax1.text(
        0.81, 2.40,
        f"kappa = ({po:.4f} - {pe:.4f}) / (1 - {pe:.4f}) = {kappa:.4f}",
        ha="center", va="center", fontsize=8.5, fontweight="bold", color=PALETTE["sage_text"],
    )
    ax1.text(
        0.81, 2.63,
        f"Bootstrap 95% CI (B = 3,000): [{ci_lo:.4f}, {ci_hi:.4f}]",
        ha="center", va="center", fontsize=8.0, color=PALETTE["muted"],
    )

    # --- Panel B: Constructed Prevalence Paradox Check (p_o = 0.85 fixed) ---
    ax2 = fig.add_subplot(gs[0, 1])
    ax2.set_facecolor(PALETTE["card"])
    for spine in ("top", "right"):
        ax2.spines[spine].set_visible(False)

    ps = np.linspace(0.50, 0.915, 200)
    po_const = np.full_like(ps, 0.85)
    pe_curve = ps ** 2 + (1.0 - ps) ** 2
    kappa_curve = (0.85 - pe_curve) / (1.0 - pe_curve)

    ax2.plot(ps, po_const, color=PALETTE["blue"], lw=2.2, ls="--", label="p_o = 0.85 (fixed raw agreement)")
    ax2.plot(ps, pe_curve, color=PALETTE["ochre"], lw=2.2, ls=":", label="p_e = p^2 + (1-p)^2 (chance)")
    ax2.plot(ps, kappa_curve, color=PALETTE["terracotta"], lw=2.5, ls="-", label="Cohen's kappa = (p_o - p_e)/(1 - p_e)")

    mark_ps = np.array([0.50, 0.70, 0.85, 0.90])
    mark_pe = mark_ps ** 2 + (1.0 - mark_ps) ** 2
    mark_kap = (0.85 - mark_pe) / (1.0 - mark_pe)
    ax2.scatter(mark_ps, mark_kap, color=PALETTE["terracotta"], edgecolor=PALETTE["background"],
                linewidth=1.1, s=56, marker="s", zorder=5)
    ax2.scatter(mark_ps, mark_pe, color=PALETTE["ochre"], edgecolor=PALETTE["background"],
                linewidth=1.0, s=46, marker="^", zorder=5)

    ax2.set_ylim(0.0, 1.04)
    ax2.set_xlim(0.48, 0.93)
    ax2.set_xticks([0.50, 0.60, 0.70, 0.80, 0.90])
    ax2.grid(True, color=PALETTE["grid"], lw=0.8)
    ax2.set_title("B. Constructed Check: Skew Collapses kappa", fontsize=10.8, fontweight="bold", loc="left", pad=8)
    ax2.set_xlabel("Symmetric positive class rate p (both raters)", fontsize=9.5, fontweight="bold")
    ax2.set_ylabel("Agreement / Kappa score (zero baseline)", fontsize=9.5, fontweight="bold")

    ax2.annotate(
        "Balanced (p = 0.50):\np_e = 0.50 -> kappa = 0.700",
        xy=(0.50, 0.70), xytext=(0.52, 0.90),
        fontsize=8.2, fontweight="bold", color=PALETTE["terracotta_text"],
        arrowprops=dict(arrowstyle="->", color=PALETTE["terracotta_text"], lw=1.1),
    )
    ax2.annotate(
        "Highlighted (p = 0.90):\np_e = 0.82 -> kappa = 0.167",
        xy=(0.90, 0.167), xytext=(0.51, 0.34),
        fontsize=8.2, fontweight="bold", color=PALETTE["terracotta_text"],
        bbox=dict(boxstyle="round,pad=0.25", fc=PALETTE["background"], ec=PALETTE["terracotta"], lw=1.0),
        arrowprops=dict(arrowstyle="->", color=PALETTE["terracotta_text"], lw=1.1, connectionstyle="arc3,rad=0.14"),
    )
    ax2.legend(loc="lower left", fontsize=7.3, frameon=True, facecolor=PALETTE["background"], edgecolor=PALETTE["grid"])

    fig.text(
        0.042, 0.032,
        "Sources: Panel A reproduced from iaa.ipynb (Slide 49-50 task, seeds 2025 & 7). Panel B: constructed check (domain [0.50, 0.915]; zero baseline).",
        fontsize=7.5, color=PALETTE["muted"],
    )

    svg_path = OUT_DIR / "iaa-confusion-and-kappa-paradox.svg"
    png_path = OUT_DIR / "iaa-confusion-and-kappa-paradox.png"
    fig.savefig(svg_path, format="svg", facecolor=PALETTE["background"])
    save_opaque_rgb_png(fig, png_path, dpi=200)
    plt.close(fig)
    return svg_path, png_path


def rasterize_svg(svg_str: str, png_path: Path) -> None:
    html = f"""<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<style>
* {{ margin: 0; padding: 0; border: 0; box-sizing: border-box; }}
html, body {{ width: 1600px; height: 900px; overflow: hidden; background: #FAF6EE; }}
svg {{ display: block; width: 1600px; height: 900px; }}
</style>
</head>
<body>{svg_str}</body>
</html>
"""
    with tempfile.TemporaryDirectory(dir="/tmp") as tmp:
        html_path = Path(tmp) / "fig.html"
        prof_dir = Path(tmp) / "profile"
        prof_dir.mkdir()
        html_path.write_text(html, encoding="utf-8")
        subprocess.run(
            [
                CHROME,
                "--headless=new",
                "--no-sandbox",
                "--disable-gpu",
                "--hide-scrollbars",
                f"--user-data-dir={prof_dir}",
                "--force-device-scale-factor=1",
                "--window-size=1600,900",
                f"--screenshot={png_path}",
                f"file://{html_path}",
            ],
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )


def png_dimensions(png_path: Path) -> tuple[int, int]:
    data = png_path.read_bytes()
    assert data[:8] == b"\x89PNG\r\n\x1a\n", f"Not PNG: {png_path}"
    return struct.unpack(">II", data[16:24])


def verify_svg_xml(svg_path: Path) -> None:
    root = ET.fromstring(svg_path.read_text(encoding="utf-8"))
    assert root.tag.endswith("svg"), f"{svg_path.name}: root not svg"


def main() -> None:
    math_data = compute_verified_math()

    with mpl.rc_context(STYLE_RC):
        s1, p1 = fig_power_sample_size_and_mde(math_data)
        verify_svg_xml(s1)
        assert png_dimensions(p1) == (1600, 900), f"{p1.name} bad size {png_dimensions(p1)}"
        print(f"{p1.stem}: valid SVG + PNG {png_dimensions(p1)}")

        svg2 = fig_research_design_pipeline()
        s2 = OUT_DIR / "research-design-hypothesis-pipeline.svg"
        p2 = OUT_DIR / "research-design-hypothesis-pipeline.png"
        s2.write_text(svg2, encoding="utf-8")
        verify_svg_xml(s2)
        rasterize_svg(svg2, p2)
        assert png_dimensions(p2) == (1600, 900), f"{p2.name} bad size {png_dimensions(p2)}"
        print(f"{p2.stem}: valid SVG + PNG {png_dimensions(p2)}")

        s3, p3 = fig_iaa_confusion_and_kappa_paradox(math_data)
        verify_svg_xml(s3)
        assert png_dimensions(p3) == (1600, 900), f"{p3.name} bad size {png_dimensions(p3)}"
        print(f"{p3.stem}: valid SVG + PNG {png_dimensions(p3)}")

    manifest = {
        "lecture": "CMU CS11-711 Advanced NLP (Fall 2025) — Lecture 14: Research Skills and Experimental Design",
        "version": "v1 r2",
        "figures": [
            {
                "png": p1.name,
                "svg": s1.name,
                "generator": "matplotlib 200dpi (8x4.5 in) -> opaque RGB PNG",
                "role": "lead_cover",
                "sources": ["Slide 44-45", "power.ipynb saved snapshot", "Miller 2024 Sec. 5"],
            },
            {
                "png": p2.name,
                "svg": s2.name,
                "generator": "explicit SVG + Chrome headless raster",
                "role": "pipeline_diagram",
                "sources": ["Author synthesis across Slides 7-58"],
            },
            {
                "png": p3.name,
                "svg": s3.name,
                "generator": "matplotlib 200dpi (8x4.5 in) -> opaque RGB PNG",
                "role": "iaa_and_prevalence_check",
                "sources": ["Slide 49-50", "iaa.ipynb (seeds 2025 & 7)", "constructed check (p_o=0.85)"],
            },
        ],
        "verified_math": math_data,
        "palette": PALETTE,
    }
    (OUT_DIR / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")


if __name__ == "__main__":
    main()
