#!/usr/bin/env python3
"""Generate 1600x900 SVG/PNG explanatory figures and verify math for CMU ANLP Lecture 15."""

from __future__ import annotations

from pathlib import Path
import html as html_lib
import json
import math
import re
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

ASSETS_DIR = Path(__file__).resolve().parent
REPO_ROOT = ASSETS_DIR.parents[2]
SOURCES_DIR = REPO_ROOT / "output" / "anlp15" / "sources"
FEED_DIR = REPO_ROOT / "output" / "anlp15" / "feed_360"
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 load_notebook_logs() -> dict:
    """Parse exact Episode, Last reward, and Running Average reward from saved course notebooks."""
    results = {}
    for key, fname in [("pg", "pg.ipynb"), ("pg_vf", "pg_vf.ipynb")]:
        nb_path = SOURCES_DIR / fname
        nb = json.loads(nb_path.read_text(encoding="utf-8"))
        rows = []
        solved_msg = None
        for cell in nb["cells"]:
            for out in cell.get("outputs", []):
                txt = "".join(out.get("text", []))
                for m in re.finditer(
                    r"Episode\s+(\d+)\s+Last reward:\s+([\d.]+)\s+Average reward:\s+([\d.]+)",
                    txt,
                ):
                    rows.append(
                        {
                            "episode": int(m.group(1)),
                            "last_reward": float(m.group(2)),
                            "avg_reward": float(m.group(3)),
                        }
                    )
                sm = re.search(
                    r"Solved!\s+Running reward is now\s+([\d.]+)\s+and the last episode runs to\s+(\d+)\s+time steps!",
                    txt,
                )
                if sm:
                    solved_msg = {
                        "running_reward": float(sm.group(1)),
                        "last_steps": int(sm.group(2)),
                    }
        results[key] = {"logged_rows": rows, "solved": solved_msg}
    return results


def compute_verified_math(logs: dict) -> dict:
    """Verify Slide 37-41 equations and CartPole convergence numbers."""
    # Slide 37: gamma = 0.9, terminal +1 at a6
    gamma_37 = 0.9
    slide37_exact = [round(gamma_37 ** (6 - t), 6) for t in range(1, 7)]
    slide37_printed = [0.59, 0.66, 0.73, 0.81, 0.90, 1.00]
    for ex, pr in zip(slide37_exact, slide37_printed):
        assert abs(ex - pr) < 0.006, f"Mismatch {ex} vs {pr}"

    # Slide 38: prompt examples (note printed header says 'B - R', values are R - B)
    slide38_rows = [
        {"prompt": "Summarize A", "R": 0.80, "B": 0.75, "adv": round(0.80 - 0.75, 2)},
        {"prompt": "Summarize B", "R": 0.30, "B": 0.75, "adv": round(0.30 - 0.75, 2)},
        {"prompt": "Prove", "R": 0.30, "B": 0.10, "adv": round(0.30 - 0.10, 2)},
    ]

    # CartPole notebook reconciliation
    pg_last_log = logs["pg"]["logged_rows"][-1]
    pg_vf_last_log = logs["pg_vf"]["logged_rows"][-1]
    # Reconstruct & validate pg_vf solve episode: Ep 570 logs 474.47, next 500-step episode solves at 475.750287
    pg_vf_solved_ep = pg_vf_last_log["episode"] + 1
    pg_vf_final_ema = logs["pg_vf"]["solved"]["running_reward"]
    inferred_prev_ema = (pg_vf_final_ema - 0.05 * 500.0) / 0.95
    assert abs(inferred_prev_ema - pg_vf_last_log["avg_reward"]) < 0.01, (
        f"Reconstructed Ep 570 EMA {inferred_prev_ema:.4f} differs from logged {pg_vf_last_log['avg_reward']}"
    )
    pg_solved_ep = pg_last_log["episode"]

    # PPO clip check at eps = 0.2
    eps = 0.2
    def ppo_obj(r: float, adv: float) -> float:
        return min(r * adv, max(1.0 - eps, min(1.0 + eps, r)) * adv)

    return {
        "slide37_discount_gamma_0_9": {
            "exact": slide37_exact,
            "slide_printed": slide37_printed,
        },
        "slide38_baselines": slide38_rows,
        "cartpole_notebooks": {
            "pg_logged_checkpoints": len(logs["pg"]["logged_rows"]),
            "pg_solved_i_episode": pg_solved_ep,
            "pg_total_episodes": pg_solved_ep + 1,
            "pg_final_running_reward": logs["pg"]["solved"]["running_reward"],
            "pg_vf_logged_checkpoints": len(logs["pg_vf"]["logged_rows"]),
            "pg_vf_last_logged_i_episode": pg_vf_last_log["episode"],
            "pg_vf_last_logged_avg_reward": pg_vf_last_log["avg_reward"],
            "pg_vf_inferred_ep570_exact_ema": round(inferred_prev_ema, 6),
            "pg_vf_solved_i_episode_inferred": pg_vf_solved_ep,
            "pg_vf_total_episodes_inferred": pg_vf_solved_ep + 1,
            "pg_vf_final_running_reward": pg_vf_final_ema,
            "fewer_episodes_pct": round((1.0 - (pg_vf_solved_ep + 1) / (pg_solved_ep + 1)) * 100.0, 1),
        },
        "ppo_clip_eps_0_2": {
            "A_pos_r_0_5": round(ppo_obj(0.5, 1.0), 3),
            "A_pos_r_1_2": round(ppo_obj(1.2, 1.0), 3),
            "A_pos_r_1_5": round(ppo_obj(1.5, 1.0), 3),
            "A_neg_r_0_5": round(ppo_obj(0.5, -1.0), 3),
            "A_neg_r_0_8": round(ppo_obj(0.8, -1.0), 3),
            "A_neg_r_1_5": round(ppo_obj(1.5, -1.0), 3),
        },
    }


def save_mpl_outputs(fig: plt.Figure, stem: str) -> None:
    """Save crisp SVG and opaque RGB 1600x900 PNG from Matplotlib figure."""
    svg_path = ASSETS_DIR / f"{stem}.svg"
    png_path = ASSETS_DIR / f"{stem}.png"
    fig.savefig(svg_path, format="svg", facecolor=PALETTE["background"], edgecolor="none")
    fig.savefig(png_path, format="png", dpi=200, facecolor=PALETTE["background"], edgecolor="none")
    plt.close(fig)

    with Image.open(png_path) as im:
        rgb = im.convert("RGB")
        assert rgb.size == (1600, 900), f"Expected 1600x900, got {rgb.size}"
        rgb.save(png_path, format="PNG", dpi=(200, 200))

        FEED_DIR.mkdir(parents=True, exist_ok=True)
        feed_w = 360
        feed_h = int(round(900 * feed_w / 1600))
        feed = rgb.resize((feed_w, feed_h), Image.Resampling.LANCZOS)
        feed.save(FEED_DIR / f"{stem}-360px.png", format="PNG")


def figure_1_cartpole_and_baselines(logs: dict, verified: dict) -> None:
    """Lead figure: CartPole single-run convergence (pg vs pg_vf) + Slide 38 advantage centering."""
    vf_solved_ep = verified["cartpole_notebooks"]["pg_vf_solved_i_episode_inferred"]
    vf_total_ep = verified["cartpole_notebooks"]["pg_vf_total_episodes_inferred"]
    pg_solved_ep = verified["cartpole_notebooks"]["pg_solved_i_episode"]
    pg_total_ep = verified["cartpole_notebooks"]["pg_total_episodes"]
    with mpl.rc_context(STYLE_RC):
        fig = plt.figure(figsize=(8.0, 4.5), dpi=200, facecolor=PALETTE["background"])
        gs = fig.add_gridspec(1, 2, width_ratios=[1.34, 1.0], left=0.075, right=0.975, top=0.79, bottom=0.17, wspace=0.28)
        ax1 = fig.add_subplot(gs[0, 0])
        ax2 = fig.add_subplot(gs[0, 1])

        fig.text(
            0.035,
            0.93,
            "Saved CartPole Runs Solved in 572 vs. 1,141 Episodes",
            fontsize=14.4,
            fontweight="bold",
            color=PALETTE["ink"],
        )
        fig.text(
            0.035,
            0.875,
            "Single saved runs (pg.ipynb vs. pg_vf.ipynb; CartPole-v1, gamma=0.99, policy lr=1e-3) and Slide 38 advantages",
            fontsize=9.1,
            color=PALETTE["muted"],
        )

        # Panel A: Measured CartPole-v1 running average rewards
        ax1.set_facecolor(PALETTE["background"])
        pg_ep = np.array([r["episode"] for r in logs["pg"]["logged_rows"]])
        pg_avg = np.array([r["avg_reward"] for r in logs["pg"]["logged_rows"]])

        vf_ep = np.array([r["episode"] for r in logs["pg_vf"]["logged_rows"]] + [vf_solved_ep])
        vf_avg = np.array(
            [r["avg_reward"] for r in logs["pg_vf"]["logged_rows"]]
            + [round(logs["pg_vf"]["solved"]["running_reward"], 2)]
        )

        ax1.axhline(475.0, color=PALETTE["ochre_text"], linestyle="--", linewidth=1.3, zorder=2)
        ax1.text(25, 488, "Solved threshold (475)", fontsize=8.3, fontweight="bold", color=PALETTE["ochre_text"])

        ax1.plot(
            pg_ep,
            pg_avg,
            color=PALETTE["terracotta"],
            linewidth=2.4,
            linestyle="-",
            marker="o",
            markersize=3.3,
            markevery=12,
            label="REINFORCE, no baseline (pg.ipynb)",
            zorder=3,
        )
        ax1.plot(
            vf_ep,
            vf_avg,
            color=PALETTE["blue"],
            linewidth=2.6,
            linestyle="-",
            marker="s",
            markersize=3.5,
            markevery=6,
            label="REINFORCE + VF baseline (pg_vf.ipynb)",
            zorder=4,
        )

        ax1.scatter([pg_solved_ep], [475.14], color=PALETTE["terracotta"], edgecolor=PALETTE["background"], s=60, zorder=5)
        ax1.scatter([vf_solved_ep], [475.75], color=PALETTE["blue"], edgecolor=PALETTE["background"], s=62, marker="s", zorder=5)

        ax1.annotate(
            f"Ep {vf_solved_ep} ({vf_total_ep} eps)",
            xy=(vf_solved_ep, 475.75),
            xytext=(435, 535),
            fontsize=8.8,
            fontweight="bold",
            color=PALETTE["blue"],
            arrowprops=dict(arrowstyle="-|>", color=PALETTE["blue"], lw=1.2),
            bbox=dict(boxstyle="round,pad=0.25", fc=PALETTE["card"], ec=PALETTE["blue"], lw=0.8),
        )
        ax1.annotate(
            f"Ep {pg_solved_ep:,} ({pg_total_ep:,} eps)",
            xy=(pg_solved_ep, 475.14),
            xytext=(845, 535),
            fontsize=8.8,
            fontweight="bold",
            color=PALETTE["terracotta_text"],
            arrowprops=dict(arrowstyle="-|>", color=PALETTE["terracotta"], lw=1.2),
            bbox=dict(boxstyle="round,pad=0.25", fc=PALETTE["card"], ec=PALETTE["terracotta"], lw=0.8),
        )

        ax1.annotate(
            "",
            xy=(vf_solved_ep, 130),
            xytext=(pg_solved_ep, 130),
            arrowprops=dict(arrowstyle="<->", color=PALETTE["sage_text"], lw=1.4),
        )
        ax1.text(855, 148, "49.9% fewer episodes", ha="center", fontsize=8.6, fontweight="bold", color=PALETTE["sage_text"])

        ax1.set_title("A. Saved CartPole-v1 Running Reward", loc="left", fontsize=10.6, fontweight="bold", pad=8)
        ax1.set_xlabel("Episode index (10-ep checkpoints + Ep 571)", fontsize=9.1, labelpad=6)
        ax1.set_ylabel("Running EMA reward (steps)", fontsize=9.1)
        ax1.set_xlim(0, 1220)
        ax1.set_ylim(0, 585)
        ax1.grid(axis="y", color=PALETTE["grid"], linewidth=0.7)
        ax1.spines["top"].set_visible(False)
        ax1.spines["right"].set_visible(False)
        ax1.tick_params(labelsize=8.5)
        ax1.legend(loc="lower right", frameon=True, facecolor=PALETTE["card"], edgecolor=PALETTE["grid"], fontsize=8.1)

        # Panel B: Slide 38 raw reward vs centered advantage
        ax2.set_facecolor(PALETTE["background"])
        labels = ["Summarize\n(R = 0.80,\nb = 0.75)", "Summarize\n(R = 0.30,\nb = 0.75)", "Prove\n(R = 0.30,\nb = 0.10)"]
        raw_r = np.array([0.80, 0.30, 0.30])
        adv_r = np.array([0.05, -0.45, 0.20])
        x = np.arange(len(labels))
        w = 0.34

        ax2.axhline(0.0, color=PALETTE["ink"], linewidth=1.2, zorder=2)
        bars_raw = ax2.bar(
            x - w / 2,
            raw_r,
            width=w,
            color=PALETTE["blue"],
            edgecolor=PALETTE["ink"],
            linewidth=0.7,
            label="Slide 38 reward R (>= 0)",
            zorder=3,
        )
        adv_colors = [PALETTE["sage"], PALETTE["terracotta"], PALETTE["sage"]]
        bars_adv = ax2.bar(
            x + w / 2,
            adv_r,
            width=w,
            color=adv_colors,
            edgecolor=PALETTE["ink"],
            linewidth=0.7,
            hatch="///",
            label="Advantage R - b(s) (signed)",
            zorder=3,
        )

        for rect, val in zip(bars_raw, raw_r):
            ax2.text(
                rect.get_x() + rect.get_width() / 2,
                val + 0.025,
                f"+{val:.2f}",
                ha="center",
                va="bottom",
                fontsize=8.2,
                fontweight="bold",
                color=PALETTE["blue"],
            )
        for rect, val in zip(bars_adv, adv_r):
            y_pos = val + 0.025 if val >= 0 else val - 0.035
            va = "bottom" if val >= 0 else "top"
            txt_col = PALETTE["sage_text"] if val >= 0 else PALETTE["terracotta_text"]
            sign = "+" if val >= 0 else ""
            ax2.text(
                rect.get_x() + rect.get_width() / 2,
                y_pos,
                f"{sign}{val:.2f}",
                ha="center",
                va=va,
                fontsize=8.2,
                fontweight="bold",
                color=txt_col,
            )

        ax2.set_title("B. Advantage Centering (Slide 38)", loc="left", fontsize=10.6, fontweight="bold", pad=8)
        ax2.set_ylabel("Policy-gradient weight (R or R - b)", fontsize=9.1)
        ax2.set_xticks(x)
        ax2.set_xticklabels(labels, fontsize=8.3)
        ax2.set_ylim(-0.62, 1.02)
        ax2.grid(axis="y", color=PALETTE["grid"], linewidth=0.7)
        ax2.spines["top"].set_visible(False)
        ax2.spines["right"].set_visible(False)
        ax2.tick_params(axis="y", labelsize=8.5)
        ax2.legend(loc="upper right", frameon=True, facecolor=PALETTE["card"], edgecolor=PALETTE["grid"], fontsize=7.9)

        fig.text(
            0.035,
            0.032,
            "Source: Single saved runs in pg.ipynb (Ep 0-1140) and pg_vf.ipynb (Ep 0-570, Ep 571 reconstructed); Slide 38 (printed header 'B - R' shows R - b).",
            fontsize=7.7,
            color=PALETTE["muted"],
        )
        save_mpl_outputs(fig, "cartpole-baseline-convergence")


def figure_2_mdp_score_function_svg() -> None:
    """Explicit SVG diagram: MDP trajectory factorization & score-function gradient split."""
    w, h = 1600, 900
    esc = html_lib.escape

    def box(x: float, y: float, bw: float, bh: float, fill: str, stroke: str, sw: float = 2.0, rx: float = 12) -> str:
        return (
            f'<rect x="{x}" y="{y}" width="{bw}" height="{bh}" rx="{rx}" '
            f'fill="{fill}" stroke="{stroke}" stroke-width="{sw}"/>'
        )

    def txt(x: float, y: float, s: str, size: int = 20, weight: str = "400", fill: str = PALETTE["ink"], anchor: str = "start") -> str:
        return (
            f'<text x="{x}" y="{y}" font-family="{FONT}" font-size="{size}" '
            f'font-weight="{weight}" fill="{fill}" text-anchor="{anchor}">{esc(s)}</text>'
        )

    def arrow(x1: float, y1: float, x2: float, y2: float, col: str, sw: float = 2.6, dashed: bool = False) -> str:
        dx, dy = x2 - x1, y2 - y1
        L = math.hypot(dx, dy)
        ux, uy = dx / L, dy / L
        # Pull back line endpoint by 10px so arrowhead tip sits cleanly at (x2, y2)
        lx2, ly2 = x2 - 10 * ux, y2 - 10 * uy
        px, py = -uy, ux
        ah = 13.0
        aw = 5.5
        bx, by = x2 - ah * ux, y2 - ah * uy
        p1 = f"{x2:.1f},{y2:.1f}"
        p2 = f"{bx + aw * px:.1f},{by + aw * py:.1f}"
        p3 = f"{bx - aw * px:.1f},{by - aw * py:.1f}"
        dash_attr = ' stroke-dasharray="7,5"' if dashed else ""
        return (
            f'<line x1="{x1:.1f}" y1="{y1:.1f}" x2="{lx2:.1f}" y2="{ly2:.1f}" '
            f'stroke="{col}" stroke-width="{sw}"{dash_attr}/>'
            f'<polygon points="{p1} {p2} {p3}" fill="{col}"/>'
        )

    parts = [
        f'<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}" viewBox="0 0 {w} {h}">',
        f'<rect width="{w}" height="{h}" fill="{PALETTE["background"]}"/>',
        # Header
        txt(48, 64, "Policy Gradients Differentiate Action Log-Probs, Not Environment Transitions", 30, "700", PALETTE["ink"]),
        txt(48, 98, "MDP trajectory rollout, score-function factorization (Slides 19-20, 29-31, 48-50), and LLM vs. CartPole grounding", 19, "400", PALETTE["muted"]),
        # Stage 1 Card: MDP Rollout
        box(48, 134, 460, 560, PALETTE["card"], PALETTE["blue"], 2.2),
        txt(74, 178, "1. MDP Interaction Loop", 23, "700", PALETTE["blue"]),
        txt(74, 206, "Slides 14-20: S, A, E(s'|s,a), R(s,a)", 16, "600", PALETTE["muted"]),
        box(76, 232, 404, 108, PALETTE["background"], PALETTE["blue"], 1.8, 10),
        txt(278, 268, "Agent / Policy pi_theta(a_t | s_t)", 20, "700", PALETTE["blue"], "middle"),
        txt(278, 298, "Samples action a_t from current state s_t", 17, "400", PALETTE["ink"], "middle"),
        txt(278, 323, "LLM: next token y_t | (x, y_<t)", 16, "600", PALETTE["muted"], "middle"),
        box(76, 406, 404, 114, PALETTE["background"], PALETTE["ochre"], 1.8, 10),
        txt(278, 442, "Environment E(s_{t+1} | s_t, a_t)", 20, "700", PALETTE["ochre_text"], "middle"),
        txt(278, 472, "Unknown dynamics; emits s_{t+1} and r_{t+1}", 17, "400", PALETTE["ink"], "middle"),
        txt(278, 498, "LLM: appends y_t; scores terminal r_T", 16, "600", PALETTE["muted"], "middle"),
        arrow(175, 340, 175, 406, PALETTE["blue"]),
        txt(188, 379, "action a_t", 16, "700", PALETTE["blue"]),
        arrow(382, 406, 382, 340, PALETTE["ochre_text"]),
        txt(394, 379, "s_{t+1}, r_{t+1}", 16, "700", PALETTE["ochre_text"]),
        box(76, 548, 404, 120, PALETTE["background"], PALETTE["grid"], 1.6, 10),
        txt(96, 582, "Trajectory distribution (0-based):", 17, "700", PALETTE["ink"]),
        txt(96, 613, "p(tau | theta) = E(s0) * prod_{t=0}^{T-1} [", 17, "600", PALETTE["ink"]),
        txt(116, 643, "pi_theta(a_t | s_t) * E(s_{t+1} | s_t, a_t) ]", 17, "600", PALETTE["blue"]),
        # Arrow 1 -> 2
        arrow(508, 414, 560, 414, PALETTE["ink"], 3.0),
        # Stage 2 Card: Score Function Split
        box(560, 134, 520, 560, PALETTE["card"], PALETTE["terracotta"], 2.2),
        txt(586, 178, "2. Score-Function Cancellation", 23, "700", PALETTE["terracotta_text"]),
        txt(586, 206, "Slides 29-30, 48-50: Why no env gradient needed", 16, "600", PALETTE["muted"]),
        box(588, 232, 464, 124, PALETTE["background"], PALETTE["terracotta"], 1.8, 10),
        txt(608, 266, "Log-derivative identity:", 18, "700", PALETTE["terracotta_text"]),
        txt(608, 298, "grad log p(tau | theta) =", 18, "600", PALETTE["ink"]),
        txt(624, 330, "sum_{t=0}^{T-1} grad log pi_theta(a_t | s_t) + 0", 17, "700", PALETTE["blue"]),
        box(588, 378, 464, 102, PALETTE["background"], PALETTE["ochre"], 1.8, 10),
        txt(608, 412, "Environment terms drop out (grad E = 0):", 18, "700", PALETTE["ochre_text"]),
        txt(608, 442, "grad log E(s0) = 0 and grad log E(s_{t+1}|s_t,a_t) = 0", 16, "400", PALETTE["ink"]),
        txt(608, 466, "Valid even for non-differentiable text/verifiers", 16, "600", PALETTE["muted"]),
        box(588, 502, 464, 166, PALETTE["background"], PALETTE["sage"], 1.8, 10),
        txt(608, 536, "Causality reduction (Slide 50):", 18, "700", PALETTE["sage_text"]),
        txt(608, 568, "Future actions cannot change past rewards.", 17, "400", PALETTE["ink"]),
        txt(608, 602, "g_hat_t = A_hat_t * grad log pi_theta(a_t | s_t)", 18, "700", PALETTE["sage_text"]),
        txt(608, 634, "A_hat_t = R_t (0-based sum_{k=t+1}^T r_k),", 16, "600", PALETTE["muted"]),
        txt(608, 656, "R_t - v_phi(s_t), TD, or GAE (Slides 37-40)", 16, "600", PALETTE["muted"]),
        # Arrow 2 -> 3
        arrow(1080, 414, 1132, 414, PALETTE["ink"], 3.0),
        # Stage 3 Card: Optimization + Grounding
        box(1132, 134, 420, 560, PALETTE["card"], PALETTE["sage"], 2.2),
        txt(1158, 178, "3. Loss & Two Groundings", 23, "700", PALETTE["sage_text"]),
        txt(1158, 206, "Slides 18, 24, 31, 41-43", 16, "600", PALETTE["muted"]),
        box(1160, 232, 364, 138, PALETTE["background"], PALETTE["sage"], 1.8, 10),
        txt(1180, 266, "Surrogate objective (Slides 31, 41):", 18, "700", PALETTE["sage_text"]),
        txt(1180, 298, "L_PG = - sum_t A_hat_t log pi_theta(a_t|s_t)", 16, "700", PALETTE["ink"]),
        txt(1180, 328, "PPO clips gain outside [1-e, 1+e] ratio band", 16, "400", PALETTE["ink"]),
        txt(1180, 354, "Backprop updates theta via SGD / Adam", 16, "600", PALETTE["muted"]),
        box(1160, 392, 364, 132, PALETTE["background"], PALETTE["blue"], 1.8, 10),
        txt(1180, 425, "CartPole-v1 (pg.ipynb / pg_vf.ipynb):", 17, "700", PALETTE["blue"]),
        txt(1180, 454, "s_t in R^4, a_t in {Left, Right}, r_t = +1", 16, "400", PALETTE["ink"]),
        txt(1180, 481, "gamma = 0.99; policy lr = 1e-3, VF lr = 1e-2", 16, "400", PALETTE["ink"]),
        txt(1180, 507, "Single runs: 1,141 (PG) vs 572 eps (PG+VF)", 16, "700", PALETTE["blue"]),
        box(1160, 544, 364, 124, PALETTE["background"], PALETTE["terracotta"], 1.8, 10),
        txt(1180, 577, "LLM Math (Slide 24, RLVR):", 17, "700", PALETTE["terracotta_text"]),
        txt(1180, 606, "s_t = (x, y_<t), a_t = y_t (next token)", 16, "400", PALETTE["ink"]),
        txt(1180, 633, "r_{t+1} = 0 (t < T-1), r_T in {0, 1} verifier", 16, "400", PALETTE["ink"]),
        txt(1180, 658, "Directly optimizes task reward (Slides 8-12)", 16, "600", PALETTE["muted"]),
        # Bottom feedback bar
        box(48, 730, 1504, 108, PALETTE["card"], PALETTE["ink"], 1.8, 12),
        txt(76, 768, "Feedback Update Loop: Updated parameters theta' change future trajectory distribution d_{tau_pi} -> sample new rollouts -> recompute returns and advantages", 18, "700", PALETTE["ink"]),
        txt(76, 804, "Key shift vs. SFT (Slides 3-12): MLE imitates fixed human data (exposure bias); RL trains on model-generated rollouts weighted by task reward.", 17, "400", PALETTE["muted"]),
        arrow(1342, 730, 1342, 694, PALETTE["ink"], 2.2, dashed=True),
        arrow(278, 730, 278, 694, PALETTE["ink"], 2.4, dashed=True),
        txt(48, 874, "Source: Author synthesis of CMU CS11-711 Fall 2025 Lecture 15 Slides 3-31, 37-43, 48-50 and course notebooks pg.ipynb / pg_vf.ipynb.", 15, "400", PALETTE["muted"]),
        "</svg>",
    ]

    svg_text = "\n".join(parts)
    ET.fromstring(svg_text)  # Validate strict XML
    svg_path = ASSETS_DIR / "mdp-score-function-loop.svg"
    png_path = ASSETS_DIR / "mdp-score-function-loop.png"
    svg_path.write_text(svg_text, encoding="utf-8")

    with tempfile.TemporaryDirectory() as tmpdir:
        raw_png = Path(tmpdir) / "raw.png"
        html_file = Path(tmpdir) / "render.html"
        html_file.write_text(
            f'<!DOCTYPE html><html><body style="margin:0;padding:0;background:{PALETTE["background"]};">'
            f'<img src="file://{svg_path.resolve()}" style="width:1600px;height:900px;display:block;"/>'
            f"</body></html>",
            encoding="utf-8",
        )
        subprocess.run(
            [
                CHROME,
                "--headless=new",
                "--disable-gpu",
                "--window-size=1600,900",
                "--force-device-scale-factor=1",
                "--hide-scrollbars",
                f"--screenshot={raw_png}",
                f"file://{html_file}",
            ],
            check=True,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        )
        with Image.open(raw_png) as im:
            rgb = im.convert("RGB")
            assert rgb.size == (1600, 900)
            rgb.save(png_path, format="PNG", dpi=(200, 200))
            FEED_DIR.mkdir(parents=True, exist_ok=True)
            feed = rgb.resize((360, 203), Image.Resampling.LANCZOS)
            feed.save(FEED_DIR / "mdp-score-function-loop-360px.png", format="PNG")


def figure_3_discounting_and_ppo() -> None:
    """Two-panel exact mathematical chart: Slide 37 temporal discounting + Slide 41 PPO clipping."""
    with mpl.rc_context(STYLE_RC):
        fig = plt.figure(figsize=(8.0, 4.5), dpi=200, facecolor=PALETTE["background"])
        gs = fig.add_gridspec(1, 2, width_ratios=[1.0, 1.1], left=0.075, right=0.975, top=0.80, bottom=0.17, wspace=0.28)
        ax1 = fig.add_subplot(gs[0, 0])
        ax2 = fig.add_subplot(gs[0, 1])

        fig.text(
            0.035,
            0.93,
            "Discounting Weights Future Rewards; PPO Clips Surrogate Gain",
            fontsize=14.0,
            fontweight="bold",
            color=PALETTE["ink"],
        )
        fig.text(
            0.035,
            0.875,
            "Author evaluations of Slide 37 terminal +1 weights (gamma^(6-t)) and Slide 41 PPO objective (eps=0.2, A in {+1,-1})",
            fontsize=9.0,
            color=PALETTE["muted"],
        )

        # Panel A: Discounted return weights on 6-action trajectory
        ax1.set_facecolor(PALETTE["background"])
        steps = np.arange(1, 7)
        for gamma, col, mk, ls, lbl in [
            (0.99, PALETTE["sage"], "^", "--", "gamma = 0.99 (author; CartPole)"),
            (0.90, PALETTE["blue"], "o", "-", "gamma = 0.90 (Slide 37)"),
            (0.50, PALETTE["terracotta"], "s", ":", "gamma = 0.50 (author; short)"),
        ]:
            vals = gamma ** (6 - steps)
            ax1.plot(steps, vals, color=col, marker=mk, linestyle=ls, linewidth=2.2, markersize=5.2, label=lbl, zorder=3)

        # Label Slide 37 exact values (0.59, 0.66, 0.73, 0.81, 0.90, 1.00)
        slide37_lbls = ["0.59", "0.66", "0.73", "0.81", "0.90", "1.00"]
        for t, s_lbl in zip(steps, slide37_lbls):
            val = 0.90 ** (6 - t)
            if t < 6:
                ax1.text(t, val - 0.055, s_lbl, ha="center", va="top", fontsize=7.9, fontweight="bold", color=PALETTE["blue"])
            else:
                ax1.text(t - 0.06, val + 0.045, s_lbl, ha="right", va="bottom", fontsize=7.9, fontweight="bold", color=PALETTE["blue"])

        ax1.set_title("A. Discounted Credit for Terminal +1 at a6", loc="left", fontsize=10.5, fontweight="bold", pad=8)
        ax1.set_xlabel("Action index t in 6-step episode", fontsize=9.0, labelpad=6)
        ax1.set_ylabel("Discounted return weight R_t", fontsize=9.0)
        ax1.set_xticks(steps)
        ax1.set_xticklabels([f"a{t}" for t in steps], fontsize=8.5)
        ax1.set_xlim(0.7, 6.3)
        ax1.set_ylim(0.0, 1.12)
        ax1.grid(axis="y", color=PALETTE["grid"], linewidth=0.7)
        ax1.spines["top"].set_visible(False)
        ax1.spines["right"].set_visible(False)
        ax1.tick_params(labelsize=8.3)
        ax1.legend(
            loc="center left",
            bbox_to_anchor=(0.02, 0.34),
            frameon=True,
            facecolor=PALETTE["card"],
            edgecolor=PALETTE["grid"],
            fontsize=7.1,
        )

        # Panel B: PPO clipped objective for A = +1 and A = -1 at eps = 0.2
        ax2.set_facecolor(PALETTE["background"])
        r = np.linspace(0.4, 1.6, 241)
        eps = 0.2
        r_clip = np.clip(r, 1.0 - eps, 1.0 + eps)
        ppo_pos = np.minimum(r * 1.0, r_clip * 1.0)
        ppo_neg = np.minimum(r * (-1.0), r_clip * (-1.0))

        ax2.axvspan(0.8, 1.2, color=PALETTE["card"], alpha=0.85, zorder=1)
        ax2.axvline(0.8, color=PALETTE["muted"], linestyle=":", linewidth=1.0, zorder=2)
        ax2.axvline(1.0, color=PALETTE["muted"], linestyle="--", linewidth=1.0, zorder=2)
        ax2.axvline(1.2, color=PALETTE["muted"], linestyle=":", linewidth=1.0, zorder=2)
        ax2.axhline(0.0, color=PALETTE["ink"], linewidth=0.9, zorder=2)

        ax2.plot(r, r, color=PALETTE["blue"], linestyle="--", linewidth=1.5, label="Unclipped r * A (A = +1)")
        ax2.plot(r, ppo_pos, color=PALETTE["blue"], linewidth=2.6, label="PPO objective (A = +1)", zorder=4)
        ax2.plot(r, -r, color=PALETTE["terracotta_text"], linestyle="--", linewidth=1.5, label="Unclipped r * A (A = -1)")
        ax2.plot(r, ppo_neg, color=PALETTE["terracotta"], linewidth=2.6, label="PPO objective (A = -1)", zorder=4)

        ax2.scatter([1.2, 0.8], [1.2, -0.8], color=[PALETTE["blue"], PALETTE["terracotta"]], edgecolor=PALETTE["background"], s=48, zorder=5)
        ax2.text(
            1.0,
            0.26,
            "Clip band\n[0.8, 1.2]",
            ha="center",
            va="center",
            fontsize=7.6,
            fontweight="bold",
            color=PALETTE["muted"],
            bbox=dict(boxstyle="round,pad=0.2", fc=PALETTE["card"], ec=PALETTE["grid"], lw=0.8),
            zorder=6,
        )
        ax2.annotate(
            "Flat at +1.20 (max)\n(no gain for r > 1.2)",
            xy=(1.38, 1.20),
            xytext=(1.19, 0.48),
            fontsize=7.5,
            fontweight="bold",
            color=PALETTE["blue"],
            arrowprops=dict(arrowstyle="-|>", color=PALETTE["blue"], lw=1.0),
            bbox=dict(boxstyle="round,pad=0.22", fc=PALETTE["card"], ec=PALETTE["blue"], lw=0.7),
            zorder=6,
        )
        ax2.annotate(
            "Flat at -0.80 (max for A=-1)\n(no gain below r = 0.8)",
            xy=(0.62, -0.80),
            xytext=(0.42, -1.48),
            fontsize=7.4,
            fontweight="bold",
            color=PALETTE["terracotta_text"],
            arrowprops=dict(arrowstyle="-|>", color=PALETTE["terracotta"], lw=1.0),
            bbox=dict(boxstyle="round,pad=0.22", fc=PALETTE["card"], ec=PALETTE["terracotta"], lw=0.7),
            zorder=6,
        )

        ax2.set_title("B. PPO Clipped Surrogate (Slide 41, eps = 0.2)", loc="left", fontsize=10.5, fontweight="bold", pad=8)
        ax2.set_xlabel("Probability ratio r = p_theta(y|x) / p_old(y|x)", fontsize=9.0, labelpad=6)
        ax2.set_ylabel("Clipped surrogate objective L_PPO", fontsize=9.0)
        ax2.set_xlim(0.4, 1.6)
        ax2.set_ylim(-1.65, 1.65)
        ax2.grid(axis="y", color=PALETTE["grid"], linewidth=0.7)
        ax2.spines["top"].set_visible(False)
        ax2.spines["right"].set_visible(False)
        ax2.tick_params(labelsize=8.3)
        ax2.legend(loc="upper left", frameon=True, facecolor=PALETTE["card"], edgecolor=PALETTE["grid"], fontsize=6.9)

        fig.text(
            0.035,
            0.032,
            "Source: Slide 37 (gamma=0.90) and Slide 41 (symbolic eps). Curves for gamma in {0.50, 0.99} and eps=0.2, A in {+1,-1} are author evaluations.",
            fontsize=7.7,
            color=PALETTE["muted"],
        )
        save_mpl_outputs(fig, "discounting-and-ppo-clipping")


def main() -> None:
    logs = load_notebook_logs()
    verified = compute_verified_math(logs)

    figure_1_cartpole_and_baselines(logs, verified)
    figure_2_mdp_score_function_svg()
    figure_3_discounting_and_ppo()

    manifest = {
        "lecture": "CMU CS11-711 Advanced NLP (Fall 2025) — Lecture 15: Reinforcement Learning Fundamentals",
        "version": "v1 r2",
        "figures": [
            {
                "png": "cartpole-baseline-convergence.png",
                "svg": "cartpole-baseline-convergence.svg",
                "generator": "matplotlib 200dpi (8x4.5 in) -> opaque RGB 1600x900 PNG",
                "role": "lead_cover",
                "sources": [
                    "pg.ipynb single saved run (Ep 0-1140)",
                    "pg_vf.ipynb single saved run (Ep 0-570 logged + Ep 571 reconstructed via EMA)",
                    "Slide 38 baseline prompt values",
                ],
            },
            {
                "png": "mdp-score-function-loop.png",
                "svg": "mdp-score-function-loop.svg",
                "generator": "explicit SVG + Chrome headless raster (1600x900)",
                "role": "architecture_diagram",
                "sources": [
                    "Author synthesis of Slides 3-31, 37-43, 48-50 (0-based indexing)",
                    "pg.ipynb and pg_vf.ipynb",
                ],
            },
            {
                "png": "discounting-and-ppo-clipping.png",
                "svg": "discounting-and-ppo-clipping.svg",
                "generator": "matplotlib 200dpi (8x4.5 in) -> opaque RGB 1600x900 PNG",
                "role": "discounting_and_ppo_mechanics",
                "sources": [
                    "Slide 37 discounting formula (gamma = 0.90); author evaluation for gamma in {0.50, 0.99}",
                    "Slide 41 PPO clipped surrogate objective; author evaluation at epsilon = 0.2, A in {+1, -1}",
                ],
            },
        ],
        "verified_math": verified,
    }
    (ASSETS_DIR / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
    print("Generated 3 figures + manifest.json successfully.")
    print(json.dumps(verified, indent=2))


if __name__ == "__main__":
    main()
