#!/usr/bin/env python3
"""Generate publication SVGs (for blog) and standalone PDFs (for LaTeX preprint)
directly from verified JSON outputs in out/ and independent/RECOMPUTED.json."""

from __future__ import annotations

import json
import subprocess
from html import escape
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
OUT_DIR = ROOT / "out"
IND_DIR = ROOT / "independent"
BLOG_ROOT = ROOT.parents[2]
SVG_DIR = (BLOG_ROOT / "public" / "images" / "post-cutoff-judges") if (BLOG_ROOT / "public").exists() else (ROOT / "figures")
PDF_DIR = ROOT / "figures"

PAPER = "#FAF9F5"
CARD = "#F2EFE6"
INK = "#141413"
MUTED = "#6B6A64"
GRID = "#DFDBD0"
CLAY = "#BA6348"
CLAY_LIGHT = "#D99B87"
SLATE = "#3D5A6C"
SLATE_LIGHT = "#A8BAC4"
NEUTRAL = "#8E8C84"

SERIF = "Georgia, 'Times New Roman', serif"
MONO = "Menlo, Monaco, Consolas, monospace"


def load_data():
    arm1 = json.loads((OUT_DIR / "arm1_priors.json").read_text())
    arm2 = json.loads((OUT_DIR / "arm2_results.json").read_text())
    arm3 = json.loads((OUT_DIR / "arm3_results.json").read_text())
    verdict = json.loads((OUT_DIR / "verdict_summary.json").read_text())
    recomputed = json.loads((IND_DIR / "RECOMPUTED.json").read_text())
    return arm1, arm2, arm3, verdict, recomputed


def svg_header(width: int, height: int, title: str, desc: str) -> str:
    return (
        f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {height}" '
        f'width="{width}" height="{height}" role="img" aria-label="{escape(title)}">\n'
        f'  <title>{escape(title)}</title>\n'
        f'  <desc>{escape(desc)}</desc>\n'
        f'  <rect x="0" y="0" width="{width}" height="{height}" fill="{PAPER}"/>\n'
    )


def text_el(x, y, s, size=12, fill=INK, weight="normal", anchor="start", family=SERIF, style="normal"):
    return (
        f'  <text x="{x:.1f}" y="{y:.1f}" font-family="{family}" font-size="{size}" '
        f'font-weight="{weight}" font-style="{style}" text-anchor="{anchor}" fill="{fill}">'
        f'{escape(str(s))}</text>\n'
    )


def line_el(x1, y1, x2, y2, stroke=GRID, width=1.0, dash=""):
    d = f' stroke-dasharray="{dash}"' if dash else ""
    return f'  <line x1="{x1:.1f}" y1="{y1:.1f}" x2="{x2:.1f}" y2="{y2:.1f}" stroke="{stroke}" stroke-width="{width}"{d}/>\n'


def rect_el(x, y, w, h, fill=CARD, stroke="none", sw=1.0, rx=4):
    st = f' stroke="{stroke}" stroke-width="{sw}"' if stroke != "none" else ""
    return f'  <rect x="{x:.1f}" y="{y:.1f}" width="{w:.1f}" height="{h:.1f}" rx="{rx}" fill="{fill}"{st}/>\n'


def arrow_defs() -> str:
    return (
        '  <defs>\n'
        f'    <marker id="arr-ink" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">\n'
        f'      <path d="M 0 1 L 8 5 L 0 9 z" fill="{MUTED}"/>\n'
        '    </marker>\n'
        f'    <marker id="arr-clay" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">\n'
        f'      <path d="M 0 1 L 8 5 L 0 9 z" fill="{CLAY}"/>\n'
        '    </marker>\n'
        f'    <marker id="arr-slate" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">\n'
        f'      <path d="M 0 1 L 8 5 L 0 9 z" fill="{SLATE}"/>\n'
        '    </marker>\n'
        '  </defs>\n'
    )


def rhu(v: float, nd: int = 3) -> str:
    """Deterministic round-half-up formatting so .xx5 matches standard decimal rounding."""
    from decimal import Decimal, ROUND_HALF_UP
    q = Decimal(10) ** -nd
    d = Decimal(str(v)).quantize(q, rounding=ROUND_HALF_UP)
    return f"{d}"


def rhu_signed(v: float, nd: int = 3) -> str:
    s = rhu(abs(v), nd)
    return f"+{s}" if v >= 0 else f"-{s}"


def build_fig1(arm1):
    w, h = 860, 460
    out = [
        svg_header(
            w,
            h,
            "Post-cutoff forecasting decouples prior belief from eventual truth",
            "Comparison of confounded textbook claims and Corpus-2026 post-cutoff forecasting questions with Arm 1 AUROC calibration.",
        )
    ]
    out.append(arrow_defs())
    out.append(text_el(24, 30, "How post-cutoff forecasting decouples prior belief from truth", size=17, weight="bold"))
    out.append(text_el(24, 50, "Pre-cutoff textbook claims confound belief with truth; future resolutions split Wrong-Prior cases where they pull apart.", size=12, fill=MUTED))

    # Left panel: confounded
    out.append(rect_el(24, 68, 396, 178, fill=CARD, stroke=GRID, rx=6))
    out.append(text_el(40, 92, "1. Confounded test (pre-cutoff textbook claims)", size=13, weight="bold"))
    out.append(rect_el(40, 108, 134, 34, fill=PAPER, stroke=CLAY, sw=1.2, rx=4))
    out.append(text_el(107, 129, "Model prior: YES", size=11.5, fill=CLAY, weight="bold", anchor="middle"))
    out.append(rect_el(40, 152, 134, 34, fill=PAPER, stroke=SLATE, sw=1.2, rx=4))
    out.append(text_el(107, 173, "Settled truth: YES", size=11.5, fill=SLATE, weight="bold", anchor="middle"))
    out.append(f'  <line x1="176" y1="125" x2="232" y2="142" stroke="{CLAY}" stroke-width="1.6" marker-end="url(#arr-clay)"/>\n')
    out.append(f'  <line x1="176" y1="169" x2="232" y2="152" stroke="{SLATE}" stroke-width="1.6" marker-end="url(#arr-slate)"/>\n')
    out.append(rect_el(236, 124, 168, 46, fill=PAPER, stroke=GRID, sw=1.2, rx=4))
    out.append(text_el(320, 144, "Judge rewards YES", size=12, weight="bold", anchor="middle"))
    out.append(text_el(320, 160, "(collinear; ambiguous)", size=11, fill=MUTED, anchor="middle"))
    out.append(text_el(40, 214, "Prior agreement and truth-tracking make identical predictions.", size=11.5, fill=INK))
    out.append(text_el(40, 231, "Cannot separate prejudice from genuine argument quality.", size=11, fill=MUTED))

    # Right panel: decoupled
    out.append(rect_el(440, 68, 396, 178, fill=CARD, stroke=CLAY, sw=1.2, rx=6))
    out.append(text_el(456, 92, "2. Decoupled test (Corpus-2026, resolved Feb-Nov 2026)", size=13, weight="bold"))
    out.append(rect_el(456, 108, 170, 34, fill=PAPER, stroke=GRID, rx=4))
    out.append(text_el(466, 129, "Right-Prior:", size=11.5, fill=MUTED, weight="bold"))
    out.append(text_el(542, 129, "143-152 Qs", size=11.5, fill=INK, family=MONO))
    out.append(rect_el(456, 150, 170, 56, fill="#FBF3EF", stroke=CLAY, sw=1.4, rx=4))
    out.append(text_el(466, 169, "Wrong-Prior:", size=11.5, fill=CLAY, weight="bold"))
    out.append(text_el(548, 169, "148-157 Qs", size=11.5, fill=CLAY, family=MONO))
    out.append(text_el(466, 186, "Prior != Eventual truth", size=11, fill=INK))
    out.append(text_el(466, 200, "Sharp separation", size=10.5, fill=CLAY))
    out.append(rect_el(644, 114, 176, 36, fill=PAPER, stroke=SLATE, sw=1.2, rx=4))
    out.append(text_el(732, 130, "Eventual truth", size=11, fill=SLATE, weight="bold", anchor="middle"))
    out.append(text_el(732, 143, "pulls toward side B", size=10.5, fill=MUTED, anchor="middle"))
    out.append(rect_el(644, 164, 176, 36, fill=PAPER, stroke=CLAY, sw=1.2, rx=4))
    out.append(text_el(732, 180, "Judge's own prior", size=11, fill=CLAY, weight="bold", anchor="middle"))
    out.append(text_el(732, 193, "pulls toward side A", size=10.5, fill=MUTED, anchor="middle"))
    out.append(text_el(456, 231, "Opposite sides win under H1 (prior) vs. H2 (truth).", size=11, fill=MUTED))

    # Bottom bar chart: Arm 1 AUROC
    out.append(line_el(24, 266, 836, 266, stroke=GRID))
    out.append(text_el(24, 290, "Arm 1 pre-resolution priors vs. crowd baseline (Corpus-2026, N = 300: 150 YES, 150 NO)", size=13, weight="bold"))

    # Axis 0.40 to 0.82 shifted left so right readout fits cleanly inside 836px
    x0, x1 = 212, 535
    amin, amax = 0.40, 0.82
    def ax(v):
        return x0 + (v - amin) / (amax - amin) * (x1 - x0)

    for tick in [0.40, 0.50, 0.60, 0.70, 0.80]:
        tx = ax(tick)
        is_chance = abs(tick - 0.50) < 1e-6
        out.append(line_el(tx, 316, tx, 422, stroke=NEUTRAL if is_chance else GRID, width=1.2 if is_chance else 0.8, dash="4,3" if is_chance else ""))
        out.append(text_el(tx, 437, f"{tick:.2f}", size=10.5, fill=INK if is_chance else MUTED, anchor="middle", family=MONO))
    out.append(text_el(ax(0.50), 310, "Chance (0.50)", size=10.5, fill=MUTED, anchor="middle"))
    out.append(text_el((x0 + x1) / 2, 453, "AUROC against eventual post-cutoff outcome", size=10.5, fill=MUTED, anchor="middle"))

    c_qwen25 = arm1["models"]["qwen2.5-1.5b"]["corpus_2026"]
    c_smol = arm1["models"]["smollm2-1.7b"]["corpus_2026"]
    c_qwen3 = arm1["models"]["qwen3-4b-2507"]["corpus_2026"]
    rows = [
        ("Crowd market baseline", c_qwen25["auroc_mkt_vs_truth"], f"{rhu(c_qwen25['auroc_mkt_vs_truth'])}  |  Brier {rhu(c_qwen25['brier_mkt'])}", SLATE, True),
        ("Qwen3-4B-2507 (<= Jul 2025)", c_qwen3["auroc_prior_vs_truth"], f"{rhu(c_qwen3['auroc_prior_vs_truth'])}  |  {c_qwen3['prior_accuracy']*100:.1f}% acc  |  {c_qwen3['n_wrong_prior']} wrong", NEUTRAL, False),
        ("Qwen2.5-1.5B (<= Sep 2024)", c_qwen25["auroc_prior_vs_truth"], f"{rhu(c_qwen25['auroc_prior_vs_truth'])}  |  {c_qwen25['prior_accuracy']*100:.1f}% acc  |  {c_qwen25['n_wrong_prior']} wrong", NEUTRAL, False),
        ("SmolLM2-1.7B (<= Nov 2024)", c_smol["auroc_prior_vs_truth"], f"{rhu(c_smol['auroc_prior_vs_truth'])}  |  {c_smol['prior_accuracy']*100:.1f}% acc  |  {c_smol['n_wrong_prior']} wrong", NEUTRAL, False),
    ]
    for i, (label, val, note, col, bold) in enumerate(rows):
        cy = 332 + i * 24
        out.append(text_el(24, cy + 4, label, size=11.5, fill=INK if bold else MUTED, weight="bold" if bold else "normal"))
        bx = ax(0.40)
        bw = ax(val) - bx
        out.append(rect_el(bx, cy - 7, bw, 13, fill=col, rx=2))
        out.append(text_el(548, cy + 4, note, size=10.5, fill=INK if bold else MUTED, family=MONO))

    out.append("</svg>\n")
    return "".join(out), w, h


def build_fig2(arm2):
    w, h = 860, 526
    out = [
        svg_header(
            w,
            h,
            "Horse-race OLS slopes across three models and four interventions",
            "Standardized OLS coefficients for own prior vs eventual truth in Arm 2 across Plain, Instructed, Hard-to-vary, and Pairwise strong protocols.",
        )
    ]
    out.append(text_el(24, 30, "Judges reward their own prior under every prompt and show zero truth signal", size=16.5, weight="bold"))
    out.append(text_el(24, 49, "Standardized Arm 2 OLS slopes (N = 300 questions, 95% clustered CIs), controlling for crowd price and length ratio.", size=11.5, fill=MUTED))

    # Legend
    out.append(f'  <circle cx="246" cy="70" r="4.5" fill="{CLAY}"/>\n')
    out.append(text_el(256, 74, "Own prior (beta_prior)", size=11.5, fill=INK, weight="bold"))
    out.append(f'  <circle cx="426" cy="70" r="4.5" fill="{PAPER}" stroke="{SLATE}" stroke-width="2"/>\n')
    out.append(text_el(436, 74, "Eventual truth (beta_truth)", size=11.5, fill=SLATE, weight="bold"))
    out.append(text_el(704, 74, "Prior", size=11, fill=CLAY, weight="bold", anchor="middle", family=MONO))
    out.append(text_el(794, 74, "Truth", size=11, fill=SLATE, weight="bold", anchor="middle", family=MONO))

    x0, x1 = 235, 645
    xmin, xmax = -0.26, 0.56
    def sx(v):
        return x0 + (v - xmin) / (xmax - xmin) * (x1 - x0)

    # Ticks
    y_top, y_bot = 86, 456
    for tick in [-0.2, -0.1, 0.0, 0.1, 0.2, 0.3, 0.4, 0.5]:
        tx = sx(tick)
        is0 = abs(tick) < 1e-6
        out.append(line_el(tx, y_top, tx, y_bot, stroke=INK if is0 else GRID, width=1.1 if is0 else 0.7, dash="4,3" if is0 else ""))
        out.append(text_el(tx, y_bot + 16, f"{tick:+.1f}" if tick != 0 else "0.0", size=10.5, fill=INK if is0 else MUTED, anchor="middle", family=MONO))
    out.append(text_el((x0 + x1) / 2, y_bot + 36, "Standardized OLS regression coefficient (controlling for crowd price and argument length)", size=10.5, fill=MUTED, anchor="middle"))

    models_meta = [
        ("qwen2.5-1.5b", "Qwen2.5-1.5B-Instruct (<= Sep 2024)  |  H1"),
        ("smollm2-1.7b", "SmolLM2-1.7B-Instruct (<= Nov 2024)  |  Unsettled*"),
        ("qwen3-4b-2507", "Qwen3-4B-Instruct-2507 (<= Jul 2025) |  H1"),
    ]
    protos = [
        ("plain", "Plain rubric (1-5)"),
        ("instructed", "Instructed (ignore prior)"),
        ("hard_to_vary", "Hard-to-vary rubric"),
        ("pairwise_strong", "Pairwise swapped (A/B)"),
    ]

    cy = 104
    for m_idx, (m_key, m_title) in enumerate(models_meta):
        if m_idx > 0:
            out.append(line_el(24, cy - 12, 836, cy - 12, stroke=GRID, width=1.0))
        out.append(text_el(24, cy + 4, m_title, size=12, weight="bold", fill=INK))
        cy += 22
        for p_key, p_label in protos:
            is_prim = p_key == "instructed"
            if is_prim:
                out.append(rect_el(24, cy - 11, 812, 22, fill=CARD, rx=3))
            out.append(text_el(34, cy + 4, p_label, size=11, fill=INK if is_prim else MUTED, weight="bold" if is_prim else "normal"))

            preds = arm2[m_key]["regressions"][p_key]["predictors"]
            pb, (plo, phi) = preds["prior"]["beta"], preds["prior"]["ci95"]
            tb, (tlo, thi) = preds["truth"]["beta"], preds["truth"]["ci95"]

            # Prior CI + dot slightly above midline
            py = cy - 3.5
            out.append(line_el(sx(plo), py, sx(phi), py, stroke=CLAY, width=2.0))
            out.append(f'  <circle cx="{sx(pb):.1f}" cy="{py:.1f}" r="4.0" fill="{CLAY}"/>\n')

            # Truth CI + open dot slightly below midline
            ty = cy + 3.5
            out.append(line_el(sx(tlo), ty, sx(thi), ty, stroke=SLATE, width=1.8))
            out.append(f'  <circle cx="{sx(tb):.1f}" cy="{ty:.1f}" r="3.8" fill="{PAPER}" stroke="{SLATE}" stroke-width="1.8"/>\n')

            out.append(text_el(704, cy + 4, rhu_signed(pb), size=10.8, fill=CLAY, weight="bold" if is_prim else "normal", anchor="middle", family=MONO))
            out.append(text_el(794, cy + 4, rhu_signed(tb), size=10.8, fill=SLATE, weight="bold" if is_prim else "normal", anchor="middle", family=MONO))
            cy += 24
        cy += 10

    out.append(text_el(24, 514, "*SmolLM2-1.7B lands in Unsettled under the frozen sign rule only because label offset flips raw delta negative (Fig. 3A).", size=10.5, fill=MUTED, style="italic"))
    out.append("</svg>\n")
    return "".join(out), w, h


def build_fig3(arm2, verdict, recomputed):
    w, h = 880, 455
    out = [
        svg_header(
            w,
            h,
            "Two measurement traps uncovered during verification",
            "Left: YES label offset times NO prior base rate flips raw differences on SmolLM2-1.7B. Right: Reversed 1-5 scale fails below 4B alongside Wrong-Prior conflict failure.",
        )
    ]
    out.append(text_el(24, 30, "Two measurement traps that invert naive metrics or break below 4B", size=16.5, weight="bold"))
    out.append(text_el(24, 49, "A. Asymmetric label offsets invert raw differences under prior skew.  B. Scale reversal fails at 1.5B-1.7B but recovers at 4B.", size=11.5, fill=MUTED))

    # Panel A card
    out.append(rect_el(24, 66, 408, 370, fill=CARD, stroke=GRID, rx=6))
    out.append(text_el(40, 90, "A. Label-offset sign flip (Instructed, Wrong-Prior)", size=13, weight="bold"))

    # Legend A
    out.append(rect_el(40, 102, 10, 10, fill=CLAY_LIGHT, rx=1))
    out.append(text_el(55, 111, "Raw diff", size=10.5, fill=MUTED))
    out.append(rect_el(120, 102, 10, 10, fill=SLATE, rx=1))
    out.append(text_el(135, 111, "Centered diff", size=10.5, fill=SLATE))
    out.append(rect_el(228, 102, 10, 10, fill=CLAY, rx=1))
    out.append(text_el(243, 111, "OLS beta_prior", size=10.5, fill=CLAY, weight="bold"))

    ax0, ax1 = 152, 368
    amin, amax = -0.65, 0.65
    def px(v):
        return ax0 + (v - amin) / (amax - amin) * (ax1 - ax0)

    for t in [-0.5, 0.0, 0.5]:
        tx = px(t)
        out.append(line_el(tx, 124, tx, 342, stroke=INK if t == 0 else GRID, width=1.1 if t == 0 else 0.7, dash="4,3" if t == 0 else ""))
        out.append(text_el(tx, 356, f"{t:+.1f}" if t != 0 else "0.0", size=10, fill=INK if t == 0 else MUTED, anchor="middle", family=MONO))

    panel_a_models = [
        ("qwen2.5-1.5b", "Qwen2.5-1.5B", "71% YES prior", "+0.68 YES off"),
        ("smollm2-1.7b", "SmolLM2-1.7B", "91% NO prior", "+0.68 YES off"),
        ("qwen3-4b-2507", "Qwen3-4B-2507", "71% NO prior", "-0.72 NO off"),
    ]
    y_a = 142
    for m_key, label, skew_s, off_s in panel_a_models:
        raw_v = verdict["per_model"][m_key]["delta_prior_wrong_instructed"]["mean"]
        ctr_v = recomputed["arm2"][m_key]["pointwise"]["instructed"]["diagnostic_yes_offset"]["delta_prior_wrong_centered"]["mean"]
        ols_v = verdict["per_model"][m_key]["beta_prior_instructed"]["beta"]

        out.append(text_el(38, y_a + 12, label, size=11.5, weight="bold"))
        out.append(text_el(38, y_a + 27, skew_s, size=10, fill=MUTED))
        out.append(text_el(38, y_a + 40, off_s, size=10, fill=MUTED))

        bars = [(raw_v, CLAY_LIGHT, 0), (ctr_v, SLATE, 18), (ols_v, CLAY, 36)]
        for bv, col, dy in bars:
            x_z = px(0.0)
            x_b = px(bv)
            bx = min(x_z, x_b)
            bw = max(abs(x_b - x_z), 2.0)
            out.append(rect_el(bx, y_a + dy, bw, 12, fill=col, rx=2))
            if bv >= 0:
                out.append(text_el(x_b + 5, y_a + dy + 10, rhu_signed(bv), size=9.8, fill=col if col != CLAY_LIGHT else INK, anchor="start", family=MONO))
            else:
                out.append(text_el(x_b - 5, y_a + dy + 10, rhu_signed(bv), size=9.8, fill=CLAY, weight="bold", anchor="end", family=MONO))
        y_a += 72

    out.append(rect_el(36, 370, 384, 54, fill="#FBF3EF", stroke=CLAY, sw=1.0, rx=4))
    out.append(text_el(46, 389, "Why SmolLM2 flips negative: (+0.68 YES offset) x (91.3% NO priors)", size=10.5, fill=INK, weight="bold"))
    out.append(text_el(46, 405, "subtracts -0.521 on raw diffs, hiding the strongest continuous slope (+0.402).", size=10.5, fill=MUTED))
    out.append(text_el(46, 419, "Centering or regression with an intercept eliminates this offset trap.", size=10.5, fill=MUTED))

    # Panel B right side
    out.append(rect_el(448, 66, 408, 370, fill=CARD, stroke=GRID, rx=6))
    out.append(text_el(464, 90, "B1. Reversed 1-5 scale (sub100, 400 cells)", size=13, weight="bold"))
    out.append(rect_el(464, 102, 10, 10, fill=CLAY, rx=1))
    out.append(text_el(479, 111, "Scale-reversal rho", size=10.5, fill=INK))
    out.append(f'  <polygon points="622,102 627,107 622,112 617,107" fill="{SLATE}"/>\n')
    out.append(text_el(632, 111, "Greedy 0-100 vs. E[1..5] rho", size=10.5, fill=SLATE))

    bx0, bx1 = 588, 782
    bmin, bmax = -1.05, 1.05
    def qx(v):
        return bx0 + (v - bmin) / (bmax - bmin) * (bx1 - bx0)

    for t in [-1.0, -0.5, 0.0, 0.5, 1.0]:
        tx = qx(t)
        out.append(line_el(tx, 124, tx, 232, stroke=INK if t == 0 else GRID, width=1.1 if t == 0 else 0.7, dash="4,3" if t == 0 else ""))
        out.append(text_el(tx, 246, f"{t:+.1f}" if t != 0 else "0.0", size=9.8, fill=INK if t == 0 else MUTED, anchor="middle", family=MONO))

    sr_models = [("qwen2.5-1.5b", "Qwen2.5-1.5B"), ("smollm2-1.7b", "SmolLM2-1.7B"), ("qwen3-4b-2507", "Qwen3-4B-2507")]
    for idx, (m_key, m_lbl) in enumerate(sr_models):
        ry = 144 + idx * 32
        sr_rho = arm2[m_key]["scale_reversal_sub100"]["spearman_norm_vs_rev_aligned"]
        g_rho = arm2[m_key]["g100_bridge_sub100"]["spearman_g100_vs_e15"]
        col = SLATE if sr_rho > 0 else CLAY
        out.append(text_el(464, ry + 4, m_lbl, size=11, fill=INK, weight="bold" if sr_rho > 0 else "normal"))
        xz, xr = qx(0.0), qx(sr_rho)
        out.append(rect_el(min(xz, xr), ry - 7, abs(xr - xz), 14, fill=col, rx=2))
        gx = qx(g_rho)
        out.append(f'  <polygon points="{gx:.1f},{ry-6:.1f} {gx+6:.1f},{ry:.1f} {gx:.1f},{ry+6:.1f} {gx-6:.1f},{ry:.1f}" fill="{SLATE}" stroke="{PAPER}" stroke-width="1"/>\n')
        if sr_rho < 0:
            out.append(text_el(xr - 4, ry + 4, rhu_signed(sr_rho), size=9.8, fill=CLAY, weight="bold", anchor="end", family=MONO))
            out.append(text_el(gx + 8, ry + 4, rhu_signed(g_rho, 2), size=9.8, fill=SLATE, anchor="start", family=MONO))
        else:
            out.append(text_el(xr + 6, ry + 4, rhu_signed(sr_rho), size=9.8, fill=INK, weight="bold", anchor="start", family=MONO))

    out.append(text_el(464, 268, "At 4B, rubric reversal works (rho = +0.891), yet prior prejudice remains (+0.452).", size=10.5, fill=MUTED))
    out.append(line_el(464, 282, 840, 282, stroke=GRID))

    # B2 Conflict fail rate
    out.append(text_el(464, 304, "B2. Wrong-Prior pairwise conflict failure rate", size=12.5, weight="bold"))
    out.append(text_el(464, 320, "Share preferring Weak(Prior-Aligned) over Strong(Prior-Contradicting).", size=10.5, fill=MUTED))

    cx0, cx1 = 588, 782
    def fx(v):
        return cx0 + v * (cx1 - cx0)

    out.append(line_el(fx(0.5), 332, fx(0.5), 414, stroke=NEUTRAL, width=1.1, dash="4,3"))
    out.append(text_el(fx(0.5), 427, "50% chance", size=9.8, fill=MUTED, anchor="middle"))

    for idx, (m_key, m_lbl) in enumerate(sr_models):
        ry = 345 + idx * 25
        cf = arm2[m_key]["conflict_weak_prior_vs_strong_contra"]["fail_rate_wrong"]["mean"]
        out.append(text_el(464, ry + 4, m_lbl, size=11, fill=INK))
        out.append(rect_el(cx0, ry - 6, fx(cf) - cx0, 12, fill=CLAY if cf > 0.5 else MUTED, rx=2))
        extra = " (low mass)" if m_key == "smollm2-1.7b" else ""
        lbl_txt = f"{cf*100:.1f}%{extra}"
        lx = fx(cf) + 6
        if m_key == "smollm2-1.7b":
            # Mask dashed line behind label so digits never intersect vertical reference line
            out.append(rect_el(lx - 3, ry - 7, 118, 15, fill=CARD, rx=2))
        out.append(text_el(lx, ry + 4, lbl_txt, size=9.8, fill=INK if cf > 0.5 else MUTED, family=MONO))

    out.append("</svg>\n")
    return "".join(out), w, h


def build_fig4(arm3):
    w, h = 860, 425
    out = [
        svg_header(
            w,
            h,
            "Real post-cutoff human arguments: chance truth recovery and strong length bias",
            "Arm 3 Wrong-Prior [PROB]-redacted truth recovery rates with 95% CIs and individual-comment correlations with log length vs truth alignment.",
        )
    ]
    out.append(text_el(24, 30, "On real human arguments, judges sit at chance and reward length", size=16.5, weight="bold"))
    out.append(text_el(24, 49, "Arm 3 post-cutoff human rationales with probabilities redacted ([PROB]); 95% question-clustered bootstrap CIs.", size=11.5, fill=MUTED))

    # Panel A left
    out.append(rect_el(24, 68, 396, 300, fill=CARD, stroke=GRID, rx=6))
    out.append(text_el(40, 92, "A. Wrong-Prior truth recovery (pairwise swapped)", size=13, weight="bold"))

    ax0, ax1 = 185, 345
    def px(v):
        return ax0 + (v - 0.20) / (0.95 - 0.20) * (ax1 - ax0)

    for tick in [0.25, 0.50, 0.75]:
        tx = px(tick)
        out.append(line_el(tx, 114, tx, 308, stroke=INK if tick == 0.50 else GRID, width=1.2 if tick == 0.50 else 0.8, dash="4,3" if tick == 0.50 else ""))
        out.append(text_el(tx, 324, f"{int(tick*100)}%", size=10, fill=INK if tick == 0.50 else MUTED, anchor="middle", family=MONO))
    out.append(text_el(px(0.50), 109, "50% chance", size=10, fill=MUTED, anchor="middle"))

    c_q25 = arm3["qwen2.5-1.5b"]["combined_pairs_redacted"]["inst_redacted"]["acc_wrong_prior"]
    c_smol = arm3["smollm2-1.7b"]["combined_pairs_redacted"]["inst_redacted"]["acc_wrong_prior"]
    c_q3i = arm3["qwen3-4b-2507"]["combined_pairs_redacted"]["inst_redacted"]["acc_wrong_prior"]
    c_q3h = arm3["qwen3-4b-2507"]["combined_pairs_redacted"]["htv_redacted"]["acc_wrong_prior"]

    rows_a = [
        ("Qwen2.5-1.5B (Inst)", f"n={c_q25['n']} (3A+3B)", c_q25, SLATE),
        ("SmolLM2-1.7B (Inst)", f"n={c_smol['n']} (3A+3B)", c_smol, SLATE),
        ("Qwen3-4B (Inst)", f"n={c_q3i['n']} (3B only)", c_q3i, SLATE),
        ("Qwen3-4B (Hard-to-vary)", f"n={c_q3h['n']} (3B only)", c_q3h, CLAY),
    ]
    for i, (lbl, sub, d, col) in enumerate(rows_a):
        cy = 142 + i * 44
        out.append(text_el(38, cy, lbl, size=11, weight="bold"))
        out.append(text_el(38, cy + 15, sub, size=10, fill=MUTED))
        lo, hi = d["ci95"]
        m = d["mean"]
        out.append(line_el(px(lo), cy + 4, px(hi), cy + 4, stroke=col, width=2.2))
        out.append(f'  <circle cx="{px(m):.1f}" cy="{cy+4:.1f}" r="4.5" fill="{col}"/>\n')
        out.append(text_el(360, cy + 8, f"{m*100:.1f}%", size=10.5, fill=INK, anchor="start", family=MONO))
    out.append(text_el(40, 352, "Every 95% confidence interval spans the 50% chance baseline.", size=10.5, fill=MUTED))

    # Panel B right
    out.append(rect_el(440, 68, 396, 300, fill=CARD, stroke=GRID, rx=6))
    out.append(text_el(456, 92, "B. Drivers of individual scores (Arm 3B, n = 204)", size=13, weight="bold"))

    out.append(rect_el(456, 104, 10, 10, fill=CLAY, rx=1))
    out.append(text_el(471, 113, "r(score, log length)", size=10.5, fill=CLAY, weight="bold"))
    out.append(rect_el(608, 104, 10, 10, fill=SLATE, rx=1))
    out.append(text_el(623, 113, "r(score, truth alignment)", size=10.5, fill=SLATE, weight="bold"))

    bx0, bx1 = 602, 796
    def rx(v):
        return bx0 + (v - (-0.18)) / (0.50 - (-0.18)) * (bx1 - bx0)

    for tick in [-0.1, 0.0, 0.2, 0.4]:
        tx = rx(tick)
        out.append(line_el(tx, 126, tx, 308, stroke=INK if tick == 0.0 else GRID, width=1.1 if tick == 0.0 else 0.8, dash="4,3" if tick == 0.0 else ""))
        out.append(text_el(tx, 324, f"{tick:+.1f}" if tick != 0 else "0.0", size=10, fill=INK if tick == 0 else MUTED, anchor="middle", family=MONO))

    rows_b = [
        ("Qwen2.5-1.5B (Inst)", arm3["qwen2.5-1.5b"]["arm3b_ind"]["inst_redacted"]),
        ("SmolLM2-1.7B (Inst)", arm3["smollm2-1.7b"]["arm3b_ind"]["inst_redacted"]),
        ("Qwen3-4B (Inst)", arm3["qwen3-4b-2507"]["arm3b_ind"]["inst_redacted"]),
        ("Qwen3-4B (Hard-to-vary)", arm3["qwen3-4b-2507"]["arm3b_ind"]["htv_redacted"]),
    ]
    for i, (lbl, d) in enumerate(rows_b):
        cy = 142 + i * 44
        out.append(text_el(454, cy + 8, lbl, size=11, weight="bold"))
        rl = d["corr_log_length"]["r"]
        rt = d["corr_truth_alignment"]["r"]
        xz = rx(0.0)
        # length bar
        xl = rx(rl)
        out.append(rect_el(min(xz, xl), cy - 6, abs(xl - xz), 12, fill=CLAY, rx=2))
        out.append(text_el(xl + 5, cy + 4, rhu_signed(rl), size=9.8, fill=CLAY, weight="bold", family=MONO))
        # truth bar
        xt = rx(rt)
        bw = max(abs(xt - xz), 2.5)
        out.append(rect_el(min(xz, xt), cy + 10, bw, 12, fill=SLATE, rx=2))
        if rt >= 0:
            out.append(text_el(xt + 6, cy + 20, rhu_signed(rt), size=9.8, fill=SLATE, anchor="start", family=MONO))
        else:
            out.append(text_el(min(xz, xt) - 5, cy + 20, rhu_signed(rt), size=9.8, fill=SLATE, anchor="end", family=MONO))

    out.append(text_el(456, 352, "Longer comments consistently score higher; accurate ones do not.", size=10.5, fill=MUTED))

    # Footer bar for Arm 3A
    q25_3a = arm3["qwen2.5-1.5b"]["arm3a_ind"]["inst_redacted"]["regression"]["predictors"]
    out.append(rect_el(24, 380, 812, 34, fill=CARD, stroke=GRID, rx=4))
    out.append(text_el(
        40,
        401,
        f"Arm 3A superforecasters (442 rationales, 150 Qs, Qwen2.5-1.5B): clustered OLS prior agreement = {q25_3a['prior_agreement']['beta']:+.3f} vs. accuracy = {q25_3a['eventual_accuracy']['beta']:+.3f}, log length = {q25_3a['log_length']['beta']:+.3f}.",
        size=10.8,
        fill=INK,
    ))
    out.append("</svg>\n")
    return "".join(out), w, h


def export_chrome_assets(svg_path: Path, width: int, height: int, png_path: Path, pdf_path: Path):
    chrome = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
    svg_uri = svg_path.resolve().as_uri()
    html_path = Path(f"/tmp/{svg_path.stem}_render.html")
    html_path.write_text(
        f"""<!DOCTYPE html>
<html><head><meta charset="utf-8"><style>
@page {{ size: {width}px {height}px; margin: 0; }}
html, body {{ margin: 0; padding: 0; width: {width}px; height: {height}px; background: {PAPER}; overflow: hidden; }}
img {{ display: block; width: {width}px; height: {height}px; }}
</style></head><body><img src="{svg_uri}" /></body></html>"""
    )
    html_uri = html_path.resolve().as_uri()
    subprocess.run(
        [
            chrome,
            "--headless=new",
            "--disable-gpu",
            f"--window-size={width},{height}",
            "--force-device-scale-factor=2",
            f"--screenshot={png_path}",
            html_uri,
        ],
        check=True,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )
    subprocess.run(
        [
            chrome,
            "--headless=new",
            "--disable-gpu",
            "--no-pdf-header-footer",
            f"--print-to-pdf={pdf_path}",
            html_uri,
        ],
        check=True,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )


def main():
    SVG_DIR.mkdir(parents=True, exist_ok=True)
    PDF_DIR.mkdir(parents=True, exist_ok=True)
    arm1, arm2, arm3, verdict, recomputed = load_data()

    specs = [
        ("fig1-mechanism", build_fig1(arm1)),
        ("fig2-ols-horserace", build_fig2(arm2)),
        ("fig3-measurement-traps", build_fig3(arm2, verdict, recomputed)),
        ("fig4-human-arguments", build_fig4(arm3)),
    ]
    for stem, (svg_text, w, h) in specs:
        svg_path = SVG_DIR / f"{stem}.svg"
        png_path = Path(f"/tmp/{stem}.png")
        pdf_path = PDF_DIR / f"{stem}.pdf"
        svg_path.write_text(svg_text)
        export_chrome_assets(svg_path, w, h, png_path, pdf_path)
        print(f"Wrote {svg_path.name} ({w}x{h}) -> {png_path} & {pdf_path.name}")


if __name__ == "__main__":
    main()
