#!/usr/bin/env python3
"""Generate low-text 1600x900 SVG/PNG figures for MIT 6.874 Lecture 22 (v1 r3)."""

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

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": "#6B655B",
    "blue": "#356482",
    "terracotta": "#B5493A",
    "sage": "#4B6B46",
    "ochre": "#A87919",
}


def arrow_polygon(
    tip_x: float,
    tip_y: float,
    dx: float,
    dy: float,
    length: float = 15.0,
    half_w: float = 6.5,
) -> str:
    """Return explicit <polygon> points for an arrowhead at (tip_x, tip_y)."""
    norm = math.hypot(dx, dy)
    ux, uy = dx / norm, dy / norm
    px, py = -uy, ux
    bx, by = tip_x - length * ux, tip_y - length * uy
    p1 = (bx + half_w * px, by + half_w * py)
    p2 = (bx - half_w * px, by - half_w * py)
    return f"{tip_x:.1f},{tip_y:.1f} {p1[0]:.1f},{p1[1]:.1f} {p2[0]:.1f},{p2[1]:.1f}"


def draw_arrow(
    x1: float,
    y1: float,
    x2: float,
    y2: float,
    color: str = "#4B5558",
    width: float = 3.2,
    dashed: bool = False,
) -> str:
    """Draw a straight line ending with an explicit <polygon> arrowhead at (x2, y2)."""
    dx, dy = x2 - x1, y2 - y1
    norm = math.hypot(dx, dy)
    ux, uy = dx / norm, dy / norm
    lx2, ly2 = x2 - 11.0 * ux, y2 - 11.0 * uy
    dash_attr = ' stroke-dasharray="9,7"' if dashed else ""
    return (
        f'<line x1="{x1:.1f}" y1="{y1:.1f}" x2="{lx2:.1f}" y2="{ly2:.1f}" '
        f'stroke="{color}" stroke-width="{width:.1f}" stroke-linecap="round"{dash_attr} />'
        f'<polygon points="{arrow_polygon(x2, y2, dx, dy)}" fill="{color}" />'
    )


def box(
    x: float,
    y: float,
    w: float,
    h: float,
    title: str,
    subtitle: str = "",
    fill: str = "#F3EEE3",
    stroke: str = "#7A7367",
    title_color: str = "#1F2A2E",
    sub_color: str = "#4B5558",
    title_size: int = 24,
    sub_size: int = 19,
    rx: int = 14,
) -> str:
    """Render a centered rounded box with 1-line title and optional 1-line subtitle."""
    cx = x + w / 2.0
    parts = [
        f'<rect x="{x:.1f}" y="{y:.1f}" width="{w:.1f}" height="{h:.1f}" rx="{rx}" '
        f'fill="{fill}" stroke="{stroke}" stroke-width="2.4" />'
    ]
    if subtitle:
        ty = y + h * 0.42
        sy = y + h * 0.74
        parts.append(
            f'<text x="{cx:.1f}" y="{ty:.1f}" text-anchor="middle" font-size="{title_size}" '
            f'font-weight="700" fill="{title_color}">{title}</text>'
        )
        parts.append(
            f'<text x="{cx:.1f}" y="{sy:.1f}" text-anchor="middle" font-size="{sub_size}" '
            f'fill="{sub_color}">{subtitle}</text>'
        )
    else:
        ty = y + h * 0.56
        parts.append(
            f'<text x="{cx:.1f}" y="{ty:.1f}" text-anchor="middle" font-size="{title_size}" '
            f'font-weight="700" fill="{title_color}">{title}</text>'
        )
    return "\n    ".join(parts)


def fig_amortized_registration() -> str:
    """Figure 1: Pairwise optimization vs amortized VoxelMorph forward pass."""
    parts = [
        # Row 1: Classical pairwise optimization
        '<text x="75" y="210" font-size="26" font-weight="700" fill="#7A2D22">Pairwise Optimization</text>',
        box(75, 240, 220, 120, "Scans (m, f)", "", "#F3EEE3", "#6B655B", "#1F2A2E", "#5A554E", 25, 19),
        draw_arrow(295, 300, 365, 300, "#B5493A", 3.4),
        box(370, 240, 310, 120, "Iterative Solver", "Optimize φ per pair", "#FAECE9", "#B5493A", "#7A2D22", "#52322D", 25, 20),
        draw_arrow(680, 300, 750, 300, "#B5493A", 3.4),
        box(755, 240, 260, 120, "Warp m ∘ φ", "", "#FAECE9", "#B5493A", "#7A2D22", "#52322D", 25, 20),
        draw_arrow(1015, 300, 1085, 300, "#B5493A", 3.4),
        box(1090, 240, 435, 120, "~2,350–9,000 s", "NiftyReg / ANTs CPU", "#F3EEE3", "#B5493A", "#7A2D22", "#52322D", 25, 20),

        # Divider
        '<line x1="75" y1="435" x2="1525" y2="435" stroke="#DDD5C7" stroke-width="2" />',

        # Row 2: Amortized learning (VoxelMorph)
        '<text x="75" y="505" font-size="26" font-weight="700" fill="#23475E">Amortized VoxelMorph</text>',
        box(75, 535, 220, 120, "Scans (m, f)", "", "#F3EEE3", "#6B655B", "#1F2A2E", "#5A554E", 25, 19),
        draw_arrow(295, 595, 365, 595, "#356482", 3.4),
        box(
            370,
            535,
            310,
            120,
            'CNN g<tspan baseline-shift="sub" font-size="18">θ</tspan>(m, f)',
            "Shared weights",
            "#EBF1F5",
            "#356482",
            "#23475E",
            "#33434A",
            25,
            20,
        ),
        draw_arrow(680, 595, 750, 595, "#356482", 3.4),
        box(
            755,
            535,
            260,
            120,
            'Field φ<tspan baseline-shift="sub" font-size="18">z</tspan>',
            "Integrate v",
            "#EBF1F5",
            "#356482",
            "#23475E",
            "#33434A",
            25,
            20,
        ),
        draw_arrow(1015, 595, 1085, 595, "#4B6B46", 3.4),
        box(1090, 535, 435, 120, "0.5 s GPU", "51 s CPU", "#ECF2EB", "#4B6B46", "#344E30", "#364635", 25, 20),

        '<text x="75" y="818" font-size="21" fill="#6B655B">3D brain MRI runtimes (Part A, p. 25)</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="75" y="102" font-size="42" font-weight="700" fill="#1F2A2E">Amortized Networks Replace Per-Pair Optimization</text>
    {"".join(parts)}
  </g>
</svg>
"""


def fig_ynet_dual_encoder() -> str:
    """Figure 2: Y-Net dual-encoder polyp segmentation Recall vs F1 (%) on ASU-Mayo (pp. 19-20)."""
    rows = [
        ("Y-Net (Dual Encoders)", 84.4, 85.9, "#356482"),
        ("U-Net (VGG19 Only)", 68.2, 79.8, "#4B6B46"),
        ("Fusion (3D CNN)", 71.0, 78.6, "#A87919"),
        ("U-Net (Scratch)", 39.2, 54.7, "#B5493A"),
    ]
    top_y = 265.0
    row_step = 118.0
    bar_h = 48.0

    rec_x0 = 410.0
    rec_w = 460.0
    f1_x0 = 1010.0
    f1_w = 460.0

    elems = [
        '<text x="640" y="218" text-anchor="middle" font-size="25" font-weight="700" fill="#1F2A2E">Recall (%)</text>',
        '<text x="1240" y="218" text-anchor="middle" font-size="25" font-weight="700" fill="#1F2A2E">F1-Score (%)</text>',
    ]

    for tick in (0, 20, 40, 60, 80, 100):
        tx1 = rec_x0 + (tick / 100.0) * rec_w
        tx2 = f1_x0 + (tick / 100.0) * f1_w
        stroke = "#4B5558" if tick == 0 else "#DDD5C7"
        sw = "2.2" if tick == 0 else "1.4"
        elems.append(f'<line x1="{tx1:.1f}" y1="242" x2="{tx1:.1f}" y2="725" stroke="{stroke}" stroke-width="{sw}" />')
        elems.append(f'<text x="{tx1:.1f}" y="762" text-anchor="middle" font-size="20" fill="#5A554E">{tick}</text>')
        elems.append(f'<line x1="{tx2:.1f}" y1="242" x2="{tx2:.1f}" y2="725" stroke="{stroke}" stroke-width="{sw}" />')
        elems.append(f'<text x="{tx2:.1f}" y="762" text-anchor="middle" font-size="20" fill="#5A554E">{tick}</text>')

    for idx, (label, rec, f1, color) in enumerate(rows):
        cy = top_y + idx * row_step
        elems.append(
            f'<text x="385" y="{cy + 32:.1f}" text-anchor="end" font-size="24" font-weight="700" fill="#1F2A2E">{label}</text>'
        )
        bw1 = (rec / 100.0) * rec_w
        elems.append(f'<rect x="{rec_x0:.1f}" y="{cy:.1f}" width="{bw1:.1f}" height="{bar_h:.1f}" rx="7" fill="{color}" />')
        lx1 = rec_x0 + bw1 + 10.0
        elems.append(f'<rect x="{lx1 - 3:.1f}" y="{cy + 8:.1f}" width="72" height="32" rx="4" fill="#FAF6EE" />')
        elems.append(
            f'<text x="{lx1 + 2:.1f}" y="{cy + 32:.1f}" text-anchor="start" font-size="22" font-weight="700" fill="{color}">{rec:.1f}%</text>'
        )

        bw2 = (f1 / 100.0) * f1_w
        elems.append(f'<rect x="{f1_x0:.1f}" y="{cy:.1f}" width="{bw2:.1f}" height="{bar_h:.1f}" rx="7" fill="{color}" opacity="0.90" />')
        lx2 = f1_x0 + bw2 + 10.0
        elems.append(f'<rect x="{lx2 - 3:.1f}" y="{cy + 8:.1f}" width="72" height="32" rx="4" fill="#FAF6EE" />')
        elems.append(
            f'<text x="{lx2 + 2:.1f}" y="{cy + 32:.1f}" text-anchor="start" font-size="22" font-weight="700" fill="{color}">{f1:.1f}%</text>'
        )

    elems.append(
        '<text x="75" y="838" font-size="21" fill="#6B655B">ASU-Mayo Clinic polyp benchmark (Mohammed et al., Part B, pp. 19–20)</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="75" y="102" font-size="42" font-weight="700" fill="#1F2A2E">Dual Encoders Lift Polyp Recall and F1 Over Single-Backbone U-Nets</text>
    {"".join(elems)}
  </g>
</svg>
"""


def fig_ps_devcem_mil_ablation() -> str:
    """Figure 3: Weakly supervised video MIL F1-score progression (Part B, pp. 35-36)."""
    rows = [
        ("EndoscopicMIL (Proposed)", 0.551, 0.616, "#356482"),
        ("EndoscopicMIL (No Self-Sup)", 0.540, 0.606, "#4B6B46"),
        ("STPN (Temporal Baseline)", 0.536, 0.592, "#A87919"),
        ("AttenLSTM (Hidden State)", 0.487, 0.529, "#6B655B"),
        ("AttenConv (Frame Only)", 0.246, 0.229, "#B5493A"),
        ("SIL (Instance Label Copy)", 0.066, 0.235, "#B5493A"),
    ]
    top_y = 245.0
    row_step = 86.0
    bar_h = 40.0

    f1_x0 = 435.0
    f1_w = 450.0
    pr_x0 = 1015.0
    pr_w = 450.0
    max_val = 0.70

    elems = [
        '<text x="660" y="210" text-anchor="middle" font-size="25" font-weight="700" fill="#1F2A2E">Mean F1-Score</text>',
        '<text x="1240" y="210" text-anchor="middle" font-size="25" font-weight="700" fill="#1F2A2E">Mean Precision</text>',
    ]

    for tick in (0.0, 0.2, 0.4, 0.6):
        tx1 = f1_x0 + (tick / max_val) * f1_w
        tx2 = pr_x0 + (tick / max_val) * pr_w
        stroke = "#4B5558" if tick == 0.0 else "#DDD5C7"
        sw = "2.2" if tick == 0.0 else "1.4"
        elems.append(f'<line x1="{tx1:.1f}" y1="230" x2="{tx1:.1f}" y2="740" stroke="{stroke}" stroke-width="{sw}" />')
        elems.append(f'<text x="{tx1:.1f}" y="775" text-anchor="middle" font-size="20" fill="#5A554E">{tick:.1f}</text>')
        elems.append(f'<line x1="{tx2:.1f}" y1="230" x2="{tx2:.1f}" y2="740" stroke="{stroke}" stroke-width="{sw}" />')
        elems.append(f'<text x="{tx2:.1f}" y="775" text-anchor="middle" font-size="20" fill="#5A554E">{tick:.1f}</text>')

    for idx, (label, f1, prec, color) in enumerate(rows):
        cy = top_y + idx * row_step
        elems.append(
            f'<text x="410" y="{cy + 27:.1f}" text-anchor="end" font-size="22" font-weight="700" fill="#1F2A2E">{label}</text>'
        )
        bw1 = (f1 / max_val) * f1_w
        elems.append(f'<rect x="{f1_x0:.1f}" y="{cy:.1f}" width="{bw1:.1f}" height="{bar_h:.1f}" rx="6" fill="{color}" />')
        lx1 = f1_x0 + bw1 + 10.0
        elems.append(f'<rect x="{lx1 - 3:.1f}" y="{cy + 4:.1f}" width="66" height="30" rx="4" fill="#FAF6EE" />')
        elems.append(
            f'<text x="{lx1 + 2:.1f}" y="{cy + 27:.1f}" text-anchor="start" font-size="21" font-weight="700" fill="{color}">{f1:.3f}</text>'
        )

        bw2 = (prec / max_val) * pr_w
        elems.append(f'<rect x="{pr_x0:.1f}" y="{cy:.1f}" width="{bw2:.1f}" height="{bar_h:.1f}" rx="6" fill="{color}" opacity="0.88" />')
        lx2 = pr_x0 + bw2 + 10.0
        elems.append(f'<rect x="{lx2 - 3:.1f}" y="{cy + 4:.1f}" width="66" height="30" rx="4" fill="#FAF6EE" />')
        elems.append(
            f'<text x="{lx2 + 2:.1f}" y="{cy + 27:.1f}" text-anchor="start" font-size="21" font-weight="700" fill="{color}">{prec:.3f}</text>'
        )

    elems.append(
        '<text x="75" y="842" font-size="21" fill="#6B655B">Averaged across 14 capsule classes (Part B, PDF pp. 34–35)</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="75" y="102" font-size="40" font-weight="700" fill="#1F2A2E">Temporal Attention and Self-Supervision Outperform Naïve MIL</text>
    {"".join(elems)}
  </g>
</svg>
"""


def count_svg_words(svg_str: str) -> int:
    root = ET.fromstring(svg_str)
    texts = [
        " ".join("".join(el.itertext()).split())
        for el in root.iter()
        if el.tag.endswith("}text") or el.tag == "text"
    ]
    return sum(len(t.split()) for t in texts)


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 compute_verified_math() -> dict:
    """Compute all reported checks and constructed worked examples directly."""
    # Part A: HyperMorph GPU-hour savings (Slide 48)
    vm_gpu_hrs = 765.0
    hm_gpu_hrs = 147.0
    hm_speedup = vm_gpu_hrs / hm_gpu_hrs
    hm_reduction_pct = (vm_gpu_hrs - hm_gpu_hrs) / vm_gpu_hrs * 100.0

    # Part A: Constructed 1D diffeomorphic scaling-and-squaring check
    # Linear velocity v(x) = -1.2 * x
    direct_deriv = 1.0 - 1.2
    substep_deriv = 1.0 - 1.2 / 4.0  # T=2 -> 2^2 = 4 substeps
    composed_deriv = substep_deriv ** 4

    # Part B: Verify Slide 20 polyp confusion counts (ASU-Mayo)
    slide20_rows = [
        ("PLS", 1594, 10103, 2719),
        ("CVC-CLINIC", 1578, 3456, 2735),
        ("OUS", 2222, 229, 2091),
        ("ASU", 2636, 184, 1677),
        ("CUMED", 3081, 769, 1232),
        ("Fusion", 3062, 414, 1251),
        ("Y-Net(Ours)", 3582, 513, 662),
    ]
    slide20_metrics = {}
    for name, tp, fp, fn in slide20_rows:
        p = tp / (tp + fp)
        r = tp / (tp + fn)
        f1 = 2 * p * r / (p + r)
        f2 = 5 * p * r / (4 * p + r)
        slide20_metrics[name] = {
            "tp": tp,
            "fp": fp,
            "fn": fn,
            "gt_sum_tp_fn": tp + fn,
            "prec_pct": round(p * 100, 1),
            "rec_pct": round(r * 100, 1),
            "f1_pct": round(f1 * 100, 1),
            "f2_pct": round(f2 * 100, 1),
        }

    # Part B: Constructed 4-pixel Y-Net loss check (Slide 16)
    g = [1.0, 1.0, 0.0, 0.0]
    p = [0.8, 0.5, 0.2, 0.1]
    lam = 1.0
    eps = 1e-6
    ce_fg_term = -sum((lam / 2.0) * gi * math.log(pi) for gi, pi in zip(g, p) if gi > 0) / len(g)
    dice_num = 2.0 * sum(gi * pi for gi, pi in zip(g, p)) + eps
    dice_den = sum(p) + sum(g) + eps
    soft_dice = dice_num / dice_den
    dice_loss = 1.0 - soft_dice

    # Part B: Constructed 4-frame Attention-MIL check (Slides 31-32)
    scores = [0.1, 2.2, 1.5, -0.5]
    exps = [math.exp(s) for s in scores]
    z_sum = sum(exps)
    alphas = [e / z_sum for e in exps]
    thresh = 1.0 / len(scores)
    pos_frames = [i + 1 for i, a in enumerate(alphas) if a > thresh]

    # Part B: PDF p. 32 (printed slide 33) CVE video counts sum check
    train_counts = [54, 72, 17, 16, 27, 17, 22, 45, 5, 1, 32, 28, 8, 32]
    test_counts = [64, 84, 16, 21, 28, 20, 24, 41, 7, 1, 30, 29, 3, 45]

    return {
        "hypermorph_gpu_hours": {
            "voxelmorph_10_models": vm_gpu_hrs,
            "hypermorph": hm_gpu_hrs,
            "speedup_x": round(hm_speedup, 2),
            "reduction_pct": round(hm_reduction_pct, 2),
        },
        "constructed_1d_scaling_squaring": {
            "direct_deriv": round(direct_deriv, 4),
            "substep_deriv": round(substep_deriv, 4),
            "composed_4_steps_deriv": round(composed_deriv, 4),
            "exact_continuous_flow_deriv": round(math.exp(-1.2), 4),
        },
        "slide20_polyp_metrics_from_counts": slide20_metrics,
        "constructed_ynet_4px_loss": {
            "ce_fg_term": round(ce_fg_term, 4),
            "soft_dice": round(soft_dice, 4),
            "dice_loss": round(dice_loss, 4),
            "total_loss": round(ce_fg_term + dice_loss, 4),
        },
        "constructed_mil_4frame_attention": {
            "alphas": [round(a, 4) for a in alphas],
            "threshold_1_over_N": thresh,
            "pos_subbag_frames": pos_frames,
        },
        "pdf_p32_cve_video_totals": {
            "train_sum_over_classes": sum(train_counts),
            "test_sum_over_classes": sum(test_counts),
            "reported_train_total": 227,
            "reported_test_total": 228,
        },
    }


def main() -> None:
    specs = [
        ("amortized-registration-vs-pairwise", fig_amortized_registration()),
        ("ynet-dual-encoder-tradeoff", fig_ynet_dual_encoder()),
        ("ps-devcem-temporal-mil-ablation", fig_ps_devcem_mil_ablation()),
    ]
    word_counts = {}
    for name, svg_str in specs:
        words = count_svg_words(svg_str)
        assert words <= 60, f"{name} exceeds 60 words: {words}"
        svg_path = OUT_DIR / f"{name}.svg"
        png_path = OUT_DIR / f"{name}.png"
        svg_path.write_text(svg_str, encoding="utf-8")
        rasterize_svg(svg_str, png_path)
        w, h = png_dimensions(png_path)
        assert (w, h) == (1600, 900), f"{name} unexpected PNG size {w}x{h}"
        word_counts[name] = words
        print(f"{name}: words={words} size={w}x{h}")

    manifest = {
        "lecture": "MIT 6.874 Deep Learning in the Life Sciences (Spring 2021) — Lecture 22: Image Registration and Automatic Pathology Detection",
        "version": "v1 r3",
        "figures": [f"{name}.png" for name, _ in specs],
        "svg_word_counts": word_counts,
        "verified_math": compute_verified_math(),
        "palette": PALETTE,
    }
    (OUT_DIR / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")


if __name__ == "__main__":
    main()
