#!/usr/bin/env python3
"""Generate publication SVG (for blog) and standalone PDF figure (for LaTeX preprint)
directly from verified out/summary_v2.json."""

from __future__ import annotations

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

V2_ROOT = Path(__file__).resolve().parent.parent
OUT_DIR = V2_ROOT / "out"
FIG_DIR = V2_ROOT / "figures"
BLOG_ROOT = V2_ROOT.parents[3]
SVG_DIR = BLOG_ROOT / "public" / "images" / "mistaken-critiques"

PAPER = "#FAF9F5"
CARD = "#F3F1EA"
INK = "#141413"
MUTED = "#6B6A64"
GRID = "#DFDBD0"
CLAY = "#BA6348"
SLATE = "#3D5A6C"
SLATE_LIGHT = "#9CB0BC"
WOBBLE = "#8E8C84"

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


def fmt_pts(v: float) -> str:
    sign = "+" if v > 0 else ("−" if v < 0 else "")
    return f"{sign}{abs(v):.1f}"


def svg_header(w: int, h: int, title: str, desc: str) -> str:
    return (
        f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" '
        f'width="{w}" height="{h}" 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="{w}" height="{h}" fill="{PAPER}"/>\n'
    )


def text_el(x, y, s, size=12, fill=INK, weight="normal", anchor="start", family=SERIF):
    return (
        f'  <text x="{x:.1f}" y="{y:.1f}" font-family="{family}" font-size="{size}" '
        f'font-weight="{weight}" text-anchor="{anchor}" fill="{fill}">{escape(str(s))}</text>\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 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 build_fig1(summary: dict) -> str:
    entries = []
    for mk, lbl in [
        ("qwen2.5-1.5b", "Qwen2.5-1.5B (AF)"),
        ("smollm2-1.7b", "SmolLM2-1.7B (AF)"),
        ("qwen3-4b-2507", "Qwen3-4B (AF)"),
    ]:
        if mk in summary["models"]:
            entries.append((lbl, summary["models"][mk], False))
    if summary.get("reasoning_first_bridge"):
        entries.append(("Qwen3-4B (RF)", summary["reasoning_first_bridge"], True))

    w, h = 880, 500
    out = [
        svg_header(
            w,
            h,
            "Plausible-but-mistaken critiques move models off sound conclusions more than real flaws move them off flawed ones",
            "Left panel compares shifts toward the critic across sound+weak foil, sound+mistaken technical critique, and flawed+strong critique. Right panel compares v1 irrelevant-foil discrimination vs v2 mistaken-foil discrimination alongside T=0.7 wobble.",
        )
    ]

    out.append(text_el(24, 30, "Plausible-but-mistaken jargon outweighs real flaws across every run", size=17, weight="bold"))
    out.append(text_el(24, 50, "Belief drop from neutral baseline (T=0, no pressure) under Answer-First (AF) and Qwen3-4B Reasoning-First (RF).", size=12, fill=MUTED))

    # Left panel
    px1, py1, pw1, ph1 = 24, 68, 420, 408
    out.append(rect_el(px1, py1, pw1, ph1, fill=CARD, stroke=GRID, rx=6))
    out.append(text_el(px1 + 14, py1 + 24, "A. Belief drop toward critic (pts)", size=13, weight="bold"))

    # Top legend cleanly above plot region (no vertical axis line intersects it!)
    lx = px1 + 14
    for lbl, col in [("Sound + weak foil", SLATE_LIGHT), ("Sound + mistaken critique", CLAY), ("Flawed + strong flaw", SLATE)]:
        out.append(rect_el(lx, py1 + 36, 10, 10, fill=col, rx=2))
        out.append(text_el(lx + 14, py1 + 45, lbl, size=10, fill=MUTED))
        lx += 135

    vals_left = []
    for _, md, _ in entries:
        vals_left.extend([
            md["sound"]["move_weak_off"]["mean"],
            md["sound"]["move_mistaken_off"]["mean"],
            md["flawed"]["move_strong_off"]["mean"],
        ])
    v_min = min(-10.0, min(vals_left) - 4.0)
    v_max = max(72.0, max(vals_left) + 12.0)
    plot_top1 = py1 + 60
    plot_bot1 = py1 + ph1 - 44
    x_left, x_right = px1 + 122, px1 + pw1 - 24

    def map_x(val: float) -> float:
        return x_left + (val - v_min) / (v_max - v_min) * (x_right - x_left)

    zero_x = map_x(0.0)
    for tick in range(0, int(v_max) + 1, 20):
        tx = map_x(float(tick))
        if x_left <= tx <= x_right:
            out.append(line_el(tx, plot_top1, tx, plot_bot1, stroke=GRID, width=0.8, dash="3,3"))
            out.append(text_el(tx, plot_bot1 + 15, f"{tick:+d}" if tick != 0 else "0", size=10, fill=MUTED, anchor="middle", family=MONO))
    out.append(line_el(zero_x, plot_top1, zero_x, plot_bot1, stroke=INK, width=1.1))
    out.append(text_el((x_left + x_right) / 2, py1 + ph1 - 12, "Move toward critic (pts; positive = lowered P(true))", size=10, fill=MUTED, anchor="middle"))

    row_gap = (plot_bot1 - plot_top1 - 8) / max(1, len(entries))
    for i, (lbl, md, is_rf) in enumerate(entries):
        top_y = plot_top1 + 6 + i * row_gap
        if is_rf:
            out.append(line_el(px1 + 12, top_y - 6, px1 + pw1 - 12, top_y - 6, stroke=GRID, width=1.0))
        out.append(text_el(px1 + 14, top_y + 29, lbl, size=11.5, weight="bold"))
        bars = [
            md["sound"]["move_weak_off"]["mean"],
            md["sound"]["move_mistaken_off"]["mean"],
            md["flawed"]["move_strong_off"]["mean"],
        ]
        cols = [SLATE_LIGHT, CLAY, SLATE]
        for j, (val, col) in enumerate(zip(bars, cols)):
            by = top_y + j * 18
            bx0, bx1 = zero_x, map_x(val)
            out.append(rect_el(min(bx0, bx1), by, max(1.5, abs(bx1 - bx0)), 13, fill=col, rx=2))
            lbl_x = bx1 + 5 if val >= 0 else bx1 - 5
            anch = "start" if val >= 0 else "end"
            out.append(text_el(lbl_x, by + 10.5, fmt_pts(val), size=10, fill=INK, anchor=anch, family=MONO))

    # Right panel
    px2, py2, pw2, ph2 = 460, 68, 396, 408
    out.append(rect_el(px2, py2, pw2, ph2, fill=CARD, stroke=GRID, rx=6))
    out.append(text_el(px2 + 14, py2 + 24, "B. Real-vs-foil margin & T=0.7 wobble", size=13, weight="bold"))

    lx2 = px2 + 14
    for lbl, col in [("v1 weak foil", SLATE), ("v2 mistaken foil", CLAY), ("T=0.7 neutral SD", WOBBLE)]:
        out.append(rect_el(lx2, py2 + 36, 10, 10, fill=col, rx=2))
        out.append(text_el(lx2 + 14, py2 + 45, lbl, size=10, fill=MUTED))
        lx2 += 126

    vals_right = []
    for _, md, _ in entries:
        m = md["margins"]
        wb = md.get("wobble") or {}
        vals_right.extend([
            m["v1_irrelevant_foil_p_off"]["diff"],
            m["v2_mistaken_foil_p_off"]["diff"],
            (wb.get("sound_none_off") or {}).get("mean_within_item_sd") or 0.0,
        ])
    r_min = min(-62.0, min(vals_right) - 10.0)
    r_max = max(18.0, max(vals_right) + 12.0)
    rx_left, rx_right = px2 + 122, px2 + pw2 - 22

    def map_rx(val: float) -> float:
        return rx_left + (val - r_min) / (r_max - r_min) * (rx_right - rx_left)

    r_zero = map_rx(0.0)
    for tick in range(-60, int(r_max) + 1, 20):
        tx = map_rx(float(tick))
        if rx_left <= tx <= rx_right:
            out.append(line_el(tx, plot_top1, tx, plot_bot1, stroke=GRID, width=0.8, dash="3,3"))
            out.append(text_el(tx, plot_bot1 + 15, f"{tick:+d}" if tick != 0 else "0", size=10, fill=MUTED, anchor="middle", family=MONO))
    out.append(line_el(r_zero, plot_top1, r_zero, plot_bot1, stroke=INK, width=1.1))
    out.append(text_el((rx_left + rx_right) / 2, py2 + ph2 - 12, "Flawed − Sound margin / wobble SD (pts)", size=10, fill=MUTED, anchor="middle"))

    for i, (lbl, md, is_rf) in enumerate(entries):
        top_y = plot_top1 + 6 + i * row_gap
        if is_rf:
            out.append(line_el(px2 + 12, top_y - 6, px2 + pw2 - 12, top_y - 6, stroke=GRID, width=1.0))
        out.append(text_el(px2 + 14, top_y + 29, lbl, size=11.5, weight="bold"))
        v1_m = md["margins"]["v1_irrelevant_foil_p_off"]["diff"]
        v2_m = md["margins"]["v2_mistaken_foil_p_off"]["diff"]
        wb = (md.get("wobble") or {}).get("sound_none_off") or {}
        wob = wb.get("mean_within_item_sd")
        bars_r = [(v1_m, SLATE, fmt_pts(v1_m)), (v2_m, CLAY, fmt_pts(v2_m))]
        if wob is not None:
            bars_r.append((wob, WOBBLE, f"{wob:.1f} SD"))
        for j, (val, col, txt) in enumerate(bars_r):
            by = top_y + j * 18
            bx0, bx1 = r_zero, map_rx(val)
            out.append(rect_el(min(bx0, bx1), by, max(1.5, abs(bx1 - bx0)), 13, fill=col, rx=2))
            lbl_x = bx1 + 5 if val >= 0 else bx1 - 5
            anch = "start" if val >= 0 else "end"
            out.append(text_el(lbl_x, by + 10.5, txt, size=10, fill=INK, anchor=anch, family=MONO))
        if wob is None:
            out.append(text_el(px2 + 126, top_y + 47, "(T=0 deterministic bridge)", size=9.5, fill=MUTED))

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


def main() -> None:
    summary = json.loads((OUT_DIR / "summary_v2.json").read_text(encoding="utf-8"))
    SVG_DIR.mkdir(parents=True, exist_ok=True)
    FIG_DIR.mkdir(parents=True, exist_ok=True)
    svg_text = build_fig1(summary)
    svg_path = SVG_DIR / "fig1-harness.svg"
    svg_path.write_text(svg_text, encoding="utf-8")
    (FIG_DIR / "fig1-harness.svg").write_text(svg_text, encoding="utf-8")

    chrome = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
    png_out = FIG_DIR / "fig1-harness.png"
    pdf_out = FIG_DIR / "fig1-harness.pdf"
    if Path(chrome).exists():
        html_tmp = FIG_DIR / "_render.html"
        html_tmp.write_text(
            f"<html><body style='margin:0;padding:0;background:#FAF9F5;'>{svg_text}</body></html>",
            encoding="utf-8",
        )
        subprocess.run(
            [
                chrome,
                "--headless",
                "--disable-gpu",
                "--window-size=880,500",
                f"--screenshot={png_out}",
                "--force-device-scale-factor=2",
                f"file://{html_tmp}",
            ],
            check=True,
            capture_output=True,
        )
        # Render exact page-sized PDF matching 880x500 SVG viewport
        pdf_html = FIG_DIR / "_render_pdf.html"
        pdf_html.write_text(
            "<html><head><style>@page{size:880px 500px;margin:0;}body{margin:0;background:#FAF9F5;}</style></head>"
            f"<body>{svg_text}</body></html>",
            encoding="utf-8",
        )
        subprocess.run(
            [
                chrome,
                "--headless",
                "--disable-gpu",
                "--no-pdf-header-footer",
                f"--print-to-pdf={pdf_out}",
                f"file://{pdf_html}",
            ],
            check=True,
            capture_output=True,
        )
        html_tmp.unlink(missing_ok=True)
        pdf_html.unlink(missing_ok=True)
        print(f"Rendered {png_out} and {pdf_out}")


if __name__ == "__main__":
    main()
