"""Step 10. Figures (PNG, 200 dpi) from the CSV/JSON in results/.  Each figure is saved separately in figures/ and its
numbered caption (units, normalisation, interpretation, limitations) is written to results/figure_captions.json.
A geometric text-overlap check (after the figure-style rules) is run on every figure and logged.
"""
import os, json, glob
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib as mpl
from common import Tee, event, save_json, load_json, read_csv, RES, FIG

BLUE, ORANGE, VERM, GREEN, SKY, PURPLE, GRAY, BLACK = "#0072B2", "#E69F00", "#D55E00", "#009E73", "#56B4E9", "#CC79A7", "#7A7A7A", "#111111"
mpl.rcParams.update({"font.size": 9, "axes.titlesize": 9, "axes.labelsize": 9, "legend.fontsize": 8, "xtick.labelsize": 7.5, "ytick.labelsize": 7.5,
                     "axes.spines.top": False, "axes.spines.right": False, "axes.titlelocation": "left", "legend.frameon": False, "figure.dpi": 100,
                     "savefig.dpi": 200, "lines.linewidth": 1.4, "font.family": "DejaVu Sans", "mathtext.fontset": "dejavusans"})
XS = 0.2805499261695901; LV = 9.126634025564685; AOPT = 0.2766597045
CAPS = {}
QA = {}


def F(rows, key):
    return np.array([float(r[key]) for r in rows])


def letter(ax, s):
    ax.text(-0.02, 1.06, s, transform=ax.transAxes, fontweight="bold", fontsize=10, va="bottom", ha="right")


def finish(fig, name, caption):
    fig.canvas.draw()
    r = fig.canvas.get_renderer()
    ticks = set()
    for axx in fig.axes:
        ticks |= set(axx.get_xticklabels(which="both") + axx.get_yticklabels(which="both"))
    texts = [(t, t.get_window_extent(r)) for t in fig.findobj(mpl.text.Text) if t.get_text().strip() and t.get_visible() and t not in ticks]
    ov = [(a.get_text()[:25], b.get_text()[:25]) for i, (a, ba) in enumerate(texts) for b, bb in texts[i + 1:] if ba.overlaps(bb)]
    out = [t.get_text()[:25] for t, bb in texts if bb.x0 < 0 or bb.y0 < 0 or bb.x1 > fig.bbox.x1 or bb.y1 > fig.bbox.y1]
    p = os.path.join(FIG, name + ".png")
    fig.savefig(p)
    plt.close(fig)
    QA[name] = {"text_overlaps": ov, "text_outside_canvas": out}
    CAPS[name] = caption
    print(f"  saved figures/{name}.png  overlaps: {len(ov)} {ov[:4]}  outside: {len(out)} {out[:3]}")


def fig01():
    T = read_csv("table2_residuals.csv"); B = read_csv("functional_bounds.csv")
    c = F(T, "c"); ratio = F(T, "ratio"); impl = np.array([r["impl"] for r in T]); r2 = F(T, "resid_two_term"); sig = F(T, "sigma"); D = F(T, "Delta_inf")
    fig, ax = plt.subplots(1, 2, figsize=(10.5, 4.2), gridspec_kw={"wspace": 0.28})
    x = c ** (-2 / 3); cc = np.logspace(np.log10(20), 6, 400); xx = cc ** (-2 / 3)
    a = ax[0]
    a.plot(xx, cc / (cc / LV + AOPT * cc ** (1 / 3)), color=BLUE, label=r"two-term law $c/\Lambda_V+A_{\rm opt}c^{1/3}$ (no fit; Conj. 1a)")
    a.plot(xx, cc / (cc / 9.08 + 0.439 * np.log(cc) - 0.896), color=VERM, ls="--", label="logarithmic fit of AHT, as quoted in [B] Fig. 6")
    a.plot(x[impl == "I"], ratio[impl == "I"], "o", color=BLACK, ms=4.5, label="[B] Table 2, implementation I (published input)")
    a.plot(x[impl == "II"], ratio[impl == "II"], "o", mfc="white", color=BLACK, ms=4.5, label="[B] Table 2, implementation II (published input)")
    fx, fy, pm = [], [], 0
    for cv in (24, 32, 48, 64):
        rr = [r for r in B if int(r["c"]) == cv]; r = max(rr, key=lambda q: int(q["P"])); pm = max(pm, int(r["P"]))
        fx.append(cv ** (-2 / 3)); fy.append(float(r["c_over_Delta1"]))
    a.plot(fx, fy, "^", color=GREEN, ms=6, label=f"fresh optimizer output at finite order $P\\leq {pm}$ (this work)")
    a.axhline(LV, color=BLUE, lw=0.8, ls=":"); a.axhline(9.08, color=VERM, lw=0.8, ls=":")
    a.text(0.119, LV + 0.03, r"$\Lambda_V=9.12663$", color=BLUE, fontsize=8, ha="left"); a.text(0.119, 9.08 - 0.115, "9.08", color=VERM, fontsize=8, ha="left")
    tk = [24, 48, 100, 256, 1024, 1e9]
    a.set_xticks([t ** (-2 / 3) for t in tk]); a.set_xticklabels(["24", "48", "100", "256", "1024", r"$\infty$"])
    a.set_xlim(0.125, -0.004); a.set_ylim(5.55, 9.35)
    a.set_xlabel(r"central charge $c$ (axis linear in $c^{-2/3}$)"); a.set_ylabel(r"slope ratio $c/\Delta_1$")
    a.set_title("Finite-$c$ ratios drift towards $\\Lambda_V$, not 9.08"); a.legend(loc="lower right", fontsize=7.2, handlelength=1.8)
    letter(a, "a")
    b = ax[1]
    b.errorbar(c[impl == "I"], r2[impl == "I"], yerr=sig[impl == "I"], fmt="o", color=BLACK, ms=4.5, capsize=2, lw=0.8)
    b.errorbar(c[impl == "II"], r2[impl == "II"], yerr=sig[impl == "II"], fmt="o", mfc="white", color=BLACK, ms=4.5, capsize=2, lw=0.8)
    cl = np.logspace(np.log10(24), np.log10(2048), 200)
    b.plot(cl, cl / 9.08 + 0.439 * np.log(cl) - 0.896 - cl / LV - AOPT * cl ** (1 / 3), color=VERM, ls="--")
    b.axhline(0, color=BLUE, lw=0.9)
    b.text(700, 0.008, "two-term law", color=BLUE, fontsize=8); b.text(330, 0.047, "AHT logarithmic fit", color=VERM, fontsize=8)
    b.annotate(f"{r2[-1]:+.3f} at $c=2048$", (c[-1], r2[-1]), (260, -0.215), fontsize=8, arrowprops=dict(arrowstyle="-", lw=0.6, color=GRAY))
    b.set_xscale("log"); b.set_xticks([24, 64, 256, 1024, 2048]); b.set_xticklabels(["24", "64", "256", "1024", "2048"]); b.minorticks_off()
    b.set_xlabel(r"central charge $c$"); b.set_ylabel(r"$\Delta_1^{(\infty)}-c/\Lambda_V-A_{\rm opt}c^{1/3}$  (dimensionless)")
    b.set_title("The remainder is $O(1)$ and slowly varying"); letter(b, "b")
    finish(fig, "fig01_slope_drift",
           "Figure 1. Finite-c drift of the spinless gap bound. (a) Ratio c/Δ₁ against c on an axis linear in c^(-2/3). Black circles: the 24 published "
           "P→∞ values of [B] Table 2 (inputs parsed from TeX; filled = implementation I, open = II). Green triangles: fresh optimizer output of this work at finite order "
           "(largest P reached for c = 24, 32, 48, 64); being finite-order bounds they lie below the published limits. Blue: parameter-free two-term law of [B] Conj. 1(a); "
           "red dashed: the logarithmic fit c/9.08 + 0.439 log c − 0.896 quoted in [B] Fig. 6. (b) Remainder Δ₁ − c/Λ_V − A_opt c^(1/3) with the published σ as error bars. "
           "Units: Δ₁ is a scaling dimension (dimensionless). Interpretation: the ratio is still 0.136 below Λ_V at c = 2048, as the c^(1/3) correction predicts (0.141); "
           "the remainder stays between +0.013 and −0.128, while the logarithmic form departs by +0.218 at c = 2048. Limitations: the Table 2 points are not recomputed here; "
           "A_opt is conjectural, and the remainder still drifts (≈ −0.168 + 0.54 c^(-1/3)), so an O(1) or weak log term cannot be excluded by these data.")


def fig02():
    Fi = read_csv("table2_fits.csv"); Dw = read_csv("table2_window_drift.csv")
    fig, ax = plt.subplots(1, 2, figsize=(10.5, 4.0), gridspec_kw={"wspace": 0.3})
    a = ax[0]
    for name, col, mk, lab in (("F3", GREEN, "s", r"$\{1,c^{-2/3},c^{-1}\}$"), ("F4 ", BLUE, "o", r"$\{1,c^{-2/3},c^{-1},c^{-4/3}\}$ ([B] eq. 5-meas)"), ("F4log", ORANGE, "D", r"$\{1,c^{-2/3},\log c/c,c^{-1}\}$")):
        rr = [r for r in Fi if r["form"].startswith(name) and r["weighting"] == "unweighted"]
        a.plot(F(rr, "c_min"), F(rr, "Lambda_fit"), marker=mk, color=col, ms=4.5, label=lab)
    a.axhspan(9.1263 - 0.002, 9.1263 + 0.002, color=GRAY, alpha=0.25, lw=0)
    a.axhline(LV, color=BLACK, lw=0.9, ls=":")
    a.text(250, LV + 0.0006, r"$\Lambda_V$", fontsize=8, ha="right"); a.text(26, 9.1289, "published band 9.1263 ± 0.002", fontsize=7.5, color="#444444")
    a.set_xscale("log"); a.set_xticks([24, 48, 96, 192, 256]); a.set_xticklabels(["24", "48", "96", "192", "256"]); a.minorticks_off()
    a.set_xlabel(r"lower end of fit window $c_{\min}$"); a.set_ylabel(r"extrapolated slope $\Lambda_{\rm fit}$"); a.set_ylim(9.108, 9.1315)
    a.set_title("Refit of Table 2: spread over forms and windows"); a.legend(loc="lower right", fontsize=7.5, title="basis for $t_1/c$", title_fontsize=7.5); letter(a, "a")
    b = ax[1]
    lab = [f"[{int(float(r['c_lo']))},{int(float(r['c_hi']))}]" for r in Dw]; xi = np.arange(len(Dw))
    b.plot(xi, F(Dw, "Lambda_logform"), "o--", color=VERM, ms=5, label=r"$c/\Lambda+\gamma\log c+{\rm const}$")
    b.plot(xi, F(Dw, "Lambda_cuberoot_form"), "s-", color=BLUE, ms=5, label=r"$c/\Lambda+A\,c^{1/3}+{\rm const}$")
    b.axhline(LV, color=BLACK, lw=0.9, ls=":"); b.axhline(9.08, color=VERM, lw=0.8, ls=":")
    b.text(4.3, LV + 0.004, r"$\Lambda_V$", fontsize=8, ha="right"); b.text(4.3, 9.08 - 0.011, "9.08", fontsize=8, color=VERM, ha="right")
    b.set_xticks(xi); b.set_xticklabels(lab); b.set_xlim(-0.4, 4.4)
    b.set_xlabel("window of central charges used in the fit"); b.set_ylabel(r"fitted slope $\Lambda$"); b.set_ylim(8.99, 9.15)
    b.set_title("A logarithmic form drifts with the window"); b.legend(loc="lower center", fontsize=7.5); letter(b, "b")
    finish(fig, "fig02_fit_sensitivity",
           "Figure 2. Sensitivity of the extrapolated slope to fit form and window ([B] Table 2 data, unweighted linear least squares; this work). (a) Λ_fit = 1/(1/12 + ξ_fit) from fits of t₁/c "
           "against the lower end of the window; grey band: the published 9.1263 ± 0.002 of [B] eq. (5-meas); dotted: Λ_V. (b) Three-parameter fits of Δ₁(c) on five windows with a log c term (red) "
           "or a c^(1/3) term (blue). Interpretation: with the paper's basis and all 24 rows we obtain Λ = 9.1254 (inside the published band, 0.0013 below Λ_V); the log form moves from 9.007 to 9.102 "
           "as the window moves up, the c^(1/3) form only from 9.099 to 9.125. Limitations: about 43% of the form/window combinations in (a) fall outside the published ±0.002 band, mostly the "
           "three-term basis on wide windows; the spread, not a statistical error, is the honest uncertainty, and the fits cannot by themselves prove an asymptotic law.")


def fig03():
    d = np.load(os.path.join(RES, "fd_field_xstar.npz")); x, y, U = d["x"], d["y"], d["U"]
    ax_rows = read_csv("potential_axes.csv"); fd = read_csv("fd_axes.csv")
    fig = plt.figure(figsize=(10.5, 6.6)); gs = fig.add_gridspec(2, 2, height_ratios=[1, 1.15], hspace=0.42, wspace=0.28)
    a = fig.add_subplot(gs[0, :])
    Xf = np.concatenate([-x[::-1], x[1:]]); Uh = np.concatenate([U[::-1, :], U[1:, :]], axis=0)
    Yf = np.concatenate([-y[::-1], y[1:]]); Uf = np.concatenate([Uh[:, ::-1], Uh[:, 1:]], axis=1)
    cs = a.contourf(Xf, Yf, Uf.T, levels=np.arange(-2.6, 0.01, 0.1), cmap="viridis")
    a.contour(Xf, Yf, Uf.T, levels=[-0.388748], colors="white", linewidths=0.9, linestyles="--")
    a.plot([XS, 1.2], [0, 0], color="white", lw=2.2); a.plot([-1.2, -XS], [0, 0], color="white", lw=2.2)
    a.plot([XS, -XS], [0, 0], "o", color="white", ms=4); a.plot([0, 0], [0.5, -0.5], "o", mfc="none", color=VERM, ms=6, clip_on=False)
    a.text(0.78, 0.045, "slit: $U=-L(x)$", color="white", fontsize=8); a.text(-0.21, 0.4, "edge: $U=0$", color="white", fontsize=8)
    a.text(0.03, 0.41, "vacuum $b=i/2$", color=VERM, fontsize=8); a.text(-1.17, -0.33, "dashed: level $U_0$ through $b=0$", color="white", fontsize=7.5)
    a.set_xlim(-1.2, 1.2); a.set_ylim(-0.5, 0.5); a.set_xlabel(r"Re $b$,  $b=\sqrt{3t/c'}$"); a.set_ylabel(r"Im $b$")
    cb = fig.colorbar(cs, ax=a, pad=0.015, ticks=[-2.5, -2, -1.5, -1, -0.5, 0]); cb.set_label(r"$U$ (finite differences)", fontsize=8)
    a.set_title("Finite-difference solution of the slit-strip Dirichlet problem (no conformal map, no closed form)"); letter(a, "a")
    b = fig.add_subplot(gs[1, 0])
    xa = F(ax_rows, "x")
    b.plot(xa, F(ax_rows, "U_closed_form"), color=BLUE, label="closed form, [B] eq. (6-axes)")
    xf = F(fd, "x"); b.plot(xf[::4], F(fd, "U_fd")[::4], "o", color=ORANGE, ms=3.5, label="finite differences (this work)")
    xl = np.linspace(0, 0.34, 50); b.plot(xl, -2 * np.pi * xl / 3, color=BLACK, ls="--", lw=1, label=r"Cardy line $-L(x)=-2\pi x/3$")
    b.axvline(XS, color=GRAY, lw=0.8, ls=":"); b.text(XS - 0.004, -0.2, r"$x_1^*$", fontsize=8, ha="right", color="#444444")
    b.annotate(r"$U_0=-0.388748$", (0, -0.388748), (0.03, -0.3), fontsize=8, arrowprops=dict(arrowstyle="-", lw=0.6, color=GRAY))
    b.set_xlabel(r"$x$ (real axis, $t=c'x^2/3$)"); b.set_ylabel(r"potential $\frac{1}{c'}\log(|G|/M)$ bound"); b.set_xlim(-0.005, 0.34); b.set_ylim(-0.72, 0.03)
    b.set_title("The majorant meets the Cardy line tangentially at $x_1^*$"); b.legend(loc="lower left", fontsize=7.5); letter(b, "b")
    c = fig.add_subplot(gs[1, 1])
    dl = XS - xa[:-1]; kap = -F(ax_rows, "U_plus_L")[:-1]
    c.loglog(dl, kap, color=BLUE, label=r"Cardy deficit $\kappa(\delta)=-(U+L)(x_1^*-\delta)$")
    dd = np.logspace(-2.6, np.log10(XS), 50)
    c.loglog(dd, 2.6497 * dd ** 1.5, color=GREEN, ls="--", lw=1, label=r"$2.650\,\delta^{3/2}$ (tip asymptote)")
    c.loglog(dd, 2.2281 * dd ** 1.5, color=VERM, ls=":", lw=1.2, label=r"$2.228\,\delta^{3/2}$ (lower bound used in Thm 4)")
    for dv, kv in ((0.01, 0.0026), (0.05, 0.029), (0.1, 0.083), (0.2, 0.23)):
        c.plot(dv, kv, "s", mfc="none", color=BLACK, ms=5)
    c.plot([], [], "s", mfc="none", color=BLACK, ms=5, label="values printed in [B] Lemma 6.7")
    c.set_xlabel(r"distance from the tip $\delta=x_1^*-x$"); c.set_ylabel(r"$\kappa(\delta)$"); c.set_title("Deficit below the Cardy line: $3/2$ power law"); c.legend(loc="upper left", fontsize=7.5)
    letter(c, "c")
    finish(fig, "fig03_extremal_potential",
           "Figure 3. The extremal potential of [B] Lemma 6.5 obtained by a second method. (a) Second-order finite-difference solution of Laplace's equation on the strip |Im b| < 1/2 slit along "
           "|x| ≥ x₁* (grid h = 1/400 in Im b; quarter strip mirrored), with U = 0 on the edges and U = −L on the slits; dashed white: the level U₀ through the BTZ threshold b = 0. "
           "(b) U on the real axis: closed form (blue) versus finite differences (orange) and the Cardy line −2πx/3. (c) Cardy deficit κ(δ) with the two 3/2-power laws and the four values "
           "printed in Lemma 6.7. All quantities are dimensionless (potential in units of c′ = c − 1). Interpretation: the finite-difference U(0) converges with order 2.0 to −0.388748 "
           "(Richardson value agrees to 10⁻⁹) and κ(δ) ≥ 2.228 δ^(3/2) holds on the whole grid (minimum ratio 2.613). Limitations: floating-point numerics, not interval arithmetic; "
           "the potential-theoretic lemmas that turn U into a bound on every functional ([B] Prop. 6.4, App. B) are not re-proved here.")


def fig04():
    g = read_csv("gamma_tip.csv"); fd = read_csv("fd_general_s.csv"); pr = read_csv("Us_plus_L_profiles.csv")
    fig, ax = plt.subplots(1, 2, figsize=(10.5, 4.0), gridspec_kw={"wspace": 0.3})
    a = ax[0]
    a.plot(F(g, "s"), F(g, "gamma_tip"), color=BLUE, label="Poisson integral, 50 digits (this work)")
    a.plot(F(fd, "s"), F(fd, "gamma_tip_fd"), "o", color=ORANGE, ms=5, label="finite differences (this work)")
    pp = [(float(r["s"]), float(r["gamma_tip_paper"])) for r in g if r["gamma_tip_paper"] not in ("", None)]
    a.plot([p[0] for p in pp], [p[1] for p in pp], "s", mfc="none", color=BLACK, ms=7, label="values quoted in [B] section 6.6")
    a.axhline(0, color=GRAY, lw=0.8); a.axvline(XS, color=GRAY, lw=0.8, ls=":")
    a.annotate(r"tangency: $s=\mathrm{arcsinh}(1)/\pi$" + "\n" + r"(root agrees to $3\times10^{-26}$)", (XS, 0), (0.286, -0.2), fontsize=8, arrowprops=dict(arrowstyle="-", lw=0.6, color=GRAY))
    a.set_xlabel("slit position $s$"); a.set_ylabel(r"tip coefficient $\gamma_{\rm tip}(s)$ of $U_s+L\simeq\gamma_{\rm tip}\sqrt{s-x}$")
    a.set_title("The tip coefficient changes sign exactly once"); a.legend(loc="upper left", fontsize=7.5); letter(a, "a")
    b = ax[1]
    for s, col in ((0.24, GREEN), (0.26, SKY), (XS, BLACK), (0.30, ORANGE), (0.32, VERM)):
        rr = [r for r in pr if abs(float(r["s"]) - s) < 1e-4]
        xx = F(rr, "x"); vv = F(rr, "U_s_plus_L")
        b.plot(s - xx, vv, color=col, lw=1.8 if s == XS else 1.2, label=f"$s={s:.2f}$" if s != XS else "$s=x_1^*=0.2805$")
    b.axhline(0, color=GRAY, lw=0.8)
    b.set_xlim(0.075, -0.002); b.set_ylim(-0.062, 0.022); b.legend(loc="lower right", fontsize=7.5, title="slit position", title_fontsize=7.5)
    b.set_xlabel("distance inside the tip, $s-x$"); b.set_ylabel(r"height above the Cardy line, $U_s(x)+L(x)$")
    b.set_title("Beyond $x_1^*$ the majorant rises above the Cardy line"); letter(b, "b")
    finish(fig, "fig04_tangency",
           "Figure 4. Independent solution of the endpoint condition. For a slit starting at a general s the harmonic majorant U_s was computed from a Poisson integral derived for this reproduction "
           "(map w = sinh πb, ζ = w², Möbius map and square root to a half-plane; see code/s02_slope_endpoint.py), without using the closed form of [B] Lemma 6.5. (a) Coefficient γ_tip(s) of the "
           "square-root term of U_s + L at the tip: Poisson integral (line), finite differences (circles) and the four values quoted in [B] §6.6 (squares). (b) U_s + L just inside the tip for five slit "
           "positions. Dimensionless. Interpretation: γ_tip vanishes at s = 0.280549926169590…, equal to arcsinh(1)/π to 3×10⁻²⁶; for s < x₁* the majorant stays below the Cardy line on all of (−s, s) "
           "(weaker bound, e.g. Λ ≤ 9.45 at s = 0.26), for s > x₁* it rises above it and excludes nothing near the tip. Limitations: this verifies the free-boundary (tangency) characterisation that "
           "[B] labels as orientation, not the proof of optimality itself.")


def fig05():
    B = read_csv("functional_bounds.csv"); E = load_json("functional_analysis.json")
    fig, ax = plt.subplots(1, 2, figsize=(10.5, 4.1), gridspec_kw={"wspace": 0.28})
    a = ax[0]
    cols = {4: BLUE, 12: GREEN, 24: ORANGE, 48: VERM, 64: PURPLE}
    for cv, ref, lab in ((4, 1.0, "exact optimum 1"), (12, 2.0, "exact optimum 2"), (24, 3.440977, "Table 2"), (48, 6.244701, "Table 2"), (64, 8.086588, "Table 2")):
        rr = sorted([r for r in B if int(r["c"]) == cv], key=lambda q: int(q["P"]))
        P = F(rr, "P"); D = F(rr, "Delta1_P")
        a.semilogy(np.sqrt(P / cv), D - ref, "o-", color=cols[cv], ms=3, lw=1, label=f"$c={cv}$, reference: {lab}")
    xs_ = np.linspace(2.2, 4.4, 10); a.semilogy(xs_, 2.0 * np.exp(-5.0 * xs_), color=GRAY, ls="--", lw=1); a.text(2.75, 4e-8, r"$\propto e^{-5\sqrt{P/c}}$", color="#444444", fontsize=8)
    a.legend(loc="upper right", fontsize=7.5); a.set_xlim(0, 5.1); a.set_xlabel(r"$\sqrt{P/c}$  (order $P$ of the derivative functional)"); a.set_ylabel(r"$\Delta_1^{(P)}(c)-\Delta_1^{\rm ref}(c)$")
    a.set_title("Fresh order-$P$ bounds converge as a stretched exponential"); letter(a, "a")
    b = ax[1]
    allc = sorted(set(int(r["c"]) for r in B)); cm = plt.get_cmap("viridis")
    for i, cv in enumerate(allc):
        rr = sorted([r for r in B if int(r["c"]) == cv], key=lambda q: int(q["P"]))
        col = cm(0.92 * i / (len(allc) - 1))
        b.plot(F(rr, "P"), F(rr, "c_over_Delta1"), "-", color=col, lw=1.2, marker="o", ms=2.2)
        b.text(F(rr, "P")[-1] + 2, F(rr, "c_over_Delta1")[-1], f"$c={cv}$", color=col, fontsize=7.5, va="center")
    for cv, ref in ((24, 6.9748), (48, 7.6865), (64, 7.914339)):
        b.plot([104], [ref], marker="<", color=BLACK, ms=5)
    b.plot([], [], marker="<", color=BLACK, ms=5, ls="", label=r"[B] Table 2, $P\to\infty$ (published input)")
    b.axhline(6, color=GRAY, lw=0.8, ls=":"); b.text(109, 5.62, "dotted: Hellerman slope 6\n(fixed order, $c\\to\\infty$)", fontsize=7.5, color="#444444", ha="right", va="center")
    b.set_xlim(0, 112); b.set_ylim(3.8, 8.9); b.set_xlabel("order $P$"); b.set_ylabel(r"$c/\Delta_1^{(P)}(c)$"); b.set_title("At fixed order the ratio saturates; larger $c$ needs larger $P$")
    b.legend(loc="upper left", fontsize=7.5); letter(b, "b")
    finish(fig, "fig05_functional_convergence",
           "Figure 5. Fresh optimizer output: extremal derivative functionals of order P computed in this session with an independent multiprecision Newton solver (code/s04*, up to 290 digits). "
           f"(a) Excess of the order-P gap bound over a reference value: the exact optima Δ₁ = 1 (c = 4) and Δ₁ = 2 (c = 12) quoted in [B] §2.2, and the published P→∞ values of [B] Table 2 "
           "for c = 24, 48, 64 (inputs). Dashed: slope of exp(−5√(P/c)). (b) Ratio c/Δ₁^(P) against P for all eight central charges; black markers: Table 2 limits. Dimensionless. "
           f"Interpretation: the anchors are reproduced from above (excess {E['anchor_c4']['excess']:.1e} at c = 4, {E['anchor_c12']['excess']:.1e} at c = 12), every fresh bound lies above the published limit, "
           f"and the decay rates k = {E['k_range'][0]:.2f}–{E['k_range'][1]:.2f} match the empirical law [B] eq. (5-conv) (k ≈ 4.7–5.7). Limitations: our orders (P ≤ 96, P/c ≤ 4 for c ≥ 24) are far below the "
           "paper's P ≤ 3072; Table 2 itself is not reproduced beyond a three-digit extrapolation check at c = 24.")


def fig06():
    best = {}
    for fn in glob.glob(os.path.join(RES, "functional_homotopy_P*.json")):
        for r in json.load(open(fn))["results"]:
            if "u_g_profile" in r and (r["c"] not in best or r["P"] > best[r["c"]]["P"]):
                best[r["c"]] = r
    axr = read_csv("potential_axes.csv")
    fig, ax = plt.subplots(1, 2, figsize=(10.5, 4.1), gridspec_kw={"wspace": 0.28})
    a = ax[0]
    a.plot(F(axr, "x"), F(axr, "U_closed_form"), color=BLACK, lw=2, label="majorant $U$ ([B] Lemma 6.5)")
    xl = np.linspace(0, 0.72, 50); a.plot(xl, -2 * np.pi * xl / 3, color=BLACK, ls="--", lw=1, label="Cardy line $-L(x)$")
    for cv, col in ((16, SKY), (32, ORANGE), (64, VERM)):
        if cv in best:
            pr = [(p[0], p[1]) for p in best[cv]["u_g_profile"] if p[1] is not None]
            a.plot([p[0] for p in pr], [p[1] for p in pr], "-", color=col, lw=1.2, label=f"fresh $u_g$, $c={cv}$, $P={best[cv]['P']}$")
    a.axvline(XS, color=GRAY, lw=0.8, ls=":"); a.text(XS + 0.006, -0.03, "$x_1^*$", fontsize=8, color="#444444")
    a.set_xlim(0, 0.72); a.set_ylim(-1.6, 0.0); a.set_xlabel(r"$x=\sqrt{3t/c'}$"); a.set_ylabel(r"$u_g=\frac{1}{c'}\log\left(|g|/M[g]\right)$")
    a.set_title("Fresh functionals approach the majorant from below"); a.legend(loc="lower left", fontsize=7.5); letter(a, "a")
    b = ax[1]
    for cv, col, mk in ((16, SKY, "o"), (32, ORANGE, "s"), (64, VERM, "^")):
        if cv in best:
            z = np.array(best[cv]["complex_roots_b"])
            b.plot(np.abs(z[:, 0]), np.abs(z[:, 1]), mk, color=col, ms=3.8, mfc="none", label=f"$c={cv}$, $P={best[cv]['P']}$ (median $2|{{\\rm Im}}\\,b|$ = {best[cv]['cardy_height_2ImB_median']:.3f})")
    b.axhline(0.5, color=BLACK, ls="--", lw=1); b.text(0.02, 0.507, "strip edge Im $b=1/2$ (Cardy height 1)", fontsize=7.5)
    b.set_xlabel(r"$|{\rm Re}\,b|$"); b.set_ylabel(r"$|{\rm Im}\,b|$ of the non-real zeros of $p_P$"); b.set_ylim(0.42, 0.72)
    b.set_title("Complex zeros condense towards the strip edge as $c$ grows"); b.legend(loc="upper left", fontsize=7.5); letter(b, "b")
    finish(fig, "fig06_functional_anatomy",
           "Figure 6. Anatomy of the fresh extremal functionals (this work). (a) Profile u_g = (1/c′) log(|g|/M[g]) on the real axis, normalised by the Cardy-weighted mass M[g] computed with the full "
           "three-Bessel weight V of [B] eq. (2-rhoC), for c = 16, 32, 64 at the largest order reached; black: the extremal potential U (for |x| ≤ x₁*) and the Cardy line. Downward spikes are zeros of g. "
           "(b) Non-real zeros of the polynomial p_P in the variable b = √(3t/c′). Dimensionless. Interpretation: u_g(0) = −0.448 at c = 64 lies below U₀ = −0.3887 and moves towards it as c grows "
           "(U₀ − u_g(0) = 0.105, 0.079, 0.060 at c = 16, 32, 64); the complex zeros sit near |Im b| = 1/2, the median 2|Im b| falling from 1.14 (c = 16) to 1.04 (c = 64), consistent with [B] §5.3. "
           "Limitations: at these modest c and P the corrections are large (x₁ = 0.376 at c = 64 versus x₁* = 0.2805); the paper's Cardy-height fit 1.0000 ± 0.0005 uses 64 ≤ c ≤ 500 and is not reproduced.")


def fig07():
    S = read_csv("hp_temperature_sweep.csv"); M = read_csv("hp_modesum_convergence.csv"); G = read_csv("hp_growth.csv")
    fig, ax = plt.subplots(1, 3, figsize=(11.5, 3.8), gridspec_kw={"wspace": 0.36})
    a = ax[0]; T = F(S, "T")
    a.plot(T, F(S, "z1"), color=BLUE); a.plot(T, F(S, "z2"), color=ORANGE); a.plot(T, F(S, "z3"), color=GREEN)
    a.text(0.452, 1.92, "$z_1$", color=BLUE, fontsize=9); a.text(0.47, 0.2, "$z_2$", color=ORANGE, fontsize=9); a.text(0.47, -0.12, "$z_3$", color=GREEN, fontsize=9)
    a.axhline(1, color=GRAY, lw=0.8, ls=":"); a.axvline(0.3796628588, color=GRAY, lw=0.8, ls=":")
    a.annotate("$T_H^{(0)}=0.379663$", (0.3796628588, 1.0), (0.215, 1.45), fontsize=8, arrowprops=dict(arrowstyle="-", lw=0.6, color=GRAY))
    a.set_xlabel("temperature $T$ (units of $1/R$)"); a.set_ylabel("single-letter functions $z_n(x)$, $x=e^{-1/T}$"); a.set_ylim(-0.3, 2.4)
    a.set_title("Only $u_1$ goes soft at $T_H$"); letter(a, "a")
    b = ax[1]
    nm = F(M, "n_max"); er = np.abs(F(M, "x_root_minus_closed_form")); m = er > 1e-37
    b.semilogy(nm[m], er[m], "o-", color=BLUE, ms=4)
    b.set_xlabel(r"mode cut-off $n_{\max}=2j_{\max}+1$"); b.set_ylabel(r"$|x_{\rm root}-(7-4\sqrt{3})|$"); b.set_title("Mode-sum root converges geometrically"); letter(b, "b")
    c = ax[2]
    k = F(G, "power_of_y"); rt = np.array([float(r["ratio_to_previous"]) if r["ratio_to_previous"] else np.nan for r in G])
    c.plot(k, rt, "-", color=BLUE, lw=1); c.axhline(2 + np.sqrt(3), color=BLACK, ls="--", lw=1); c.text(88, 3.80, r"$1/y_H=2+\sqrt{3}$", fontsize=8, ha="right")
    c.set_ylim(2.5, 5.0); c.set_xlabel("power $k$ of $y=\\sqrt{x}$ (energy $k/2$)"); c.set_ylabel("ratio of successive state counts $\\Omega_k/\\Omega_{k-1}$")
    c.set_title("Exact state counting grows at the Hagedorn rate"); letter(c, "c")
    finish(fig, "fig07_hagedorn",
           "Figure 7. The free single-letter Hagedorn equation of [HP] §2, solved independently. (a) z_n(x) = z_B(xⁿ) + (−1)ⁿ⁺¹ z_F(xⁿ) for n = 1, 2, 3 against temperature (unit sphere, T in units "
           "of 1/R). (b) Error of the root of z(x) = 1 obtained by bisection on an explicit enumeration of the S³ oscillator modes of [HP] Table 1 truncated at n_max. (c) Ratio of successive coefficients "
           "of the confined partition function ∏ₙ(1 − zₙ)⁻¹ expanded exactly (integer arithmetic) in y = √x. Interpretation: the mode-sum root equals 7 − 4√3 to 10⁻³⁸, giving β₀ = 2.6339158 and "
           "T_H⁽⁰⁾ = 0.3796629; x z′(x) = 3/2 exactly; z₂(x_H) = 0.0257 so the second moment has mass² 0.487 ≈ 1/2; the counting ratio reaches 3.732051 = 2 + √3 at y⁹⁰. Limitations: free theory, "
           "leading order in 1/N; panel (c) tests the growth rate only, not sub-leading power corrections.")


def fig08():
    R = read_csv("hp_series_resum.csv"); T = read_csv("hp_series_truncation.csv"); Q = load_json("hp_quartic.json")
    fig, ax = plt.subplots(1, 3, figsize=(11.5, 3.9), gridspec_kw={"wspace": 0.38})
    a = ax[0]
    for w, col, lab in (("a", BLUE, "$|a_n y_H^n|$ tree kernel"), ("b", VERM, "$|b_n y_H^n|$ loop kernel")):
        rr = [r for r in R if r["series"] == w]; n = F(rr, "n"); t = np.abs(F(rr, "term_at_yH")); ex = np.array([r["exact_rational"] == "True" for r in rr])
        a.semilogy(n, t, "-", color=col, lw=1); a.semilogy(n[ex], t[ex], "o", color=col, ms=5, label=lab + " (exact rational)")
        if (~ex).any():
            a.semilogy(n[~ex], t[~ex], "o", mfc="white", color=col, ms=5, label="same, floating-point coefficient")
    a.axvspan(6.5, 10.5, color=VERM, alpha=0.08, lw=0); a.text(8.5, 0.62, "$b_n$: single engine", color=VERM, fontsize=7.5, ha="center")
    a.set_ylim(1e-4, 1.2)
    a.set_xlabel("power $n$ of $y=\\sqrt{x}$"); a.set_ylabel("term size at $y_H=2-\\sqrt{3}$"); a.set_title("Terms of the two App. B series"); a.legend(loc="lower left", fontsize=7); letter(a, "a")
    for axx, w, pv, pe, ttl, lt in ((ax[1], "a", -0.7340, 1e-4, "Tree kernel $q_4^{(a)}$: tail models agree", "b"), (ax[2], "b", -1.500, 3e-3, "Loop kernel $q_4^{(b)}$: 0.005 spread", "c")):
        rr = [r for r in T if r["series"] == w]; n = F(rr, "truncated_at_n")
        axx.axhspan(pv - pe, pv + pe, color=GRAY, alpha=0.3, lw=0)
        axx.plot(n, F(rr, "partial_sum"), "o-", color=BLACK, ms=3.5, lw=1, label="partial sum")
        axx.plot(n, F(rr, "plus_geometric_tail"), "s--", color=ORANGE, ms=3.5, lw=1, label="+ geometric tail")
        axx.plot(n, F(rr, "plus_power_law_tail"), "D-", color=BLUE, ms=3.5, lw=1, label="+ power-law tail")
        pt = list(Q["series"][w]["pade_top"].values()); axx.plot([n[-1] + 0.45] * len(pt), pt, "_", color=GREEN, ms=9, mew=1.6, label="Padé, all coefficients")
        axx.set_ylim(pv - (0.004 if w == "a" else 0.022), pv + (0.004 if w == "a" else 0.022)); axx.set_xlabel("series truncated after $y^n$"); axx.set_ylabel("estimate of the sum")
        axx.set_title(ttl); axx.legend(loc="lower right" if w == "a" else "upper left", fontsize=7); letter(axx, lt)
    ax[1].text(8.1, -0.73385, "grey: paper value ± quoted error", fontsize=7, color="#444444")
    finish(fig, "fig08_series",
           "Figure 8. Re-summation of the two series of [HP] App. B at the independently computed root y_H = 2 − √3. (a) Magnitude of each term; filled markers are exact rational coefficients, open "
           "markers the floating-point coefficients a₁₃…a₁₆; the shaded range marks the b_n produced by a single engine ([HP] §6.4). (b, c) Estimates of the sum as the series is truncated: partial "
           "sum, geometric tail from the last ratio, tail from a fitted power-law growth of the coefficients (nearest singularity y = 1), and Padé approximants using all coefficients; grey bands: "
           "q₄⁽ᵃ⁾ = −0.7340(1) and q₄⁽ᵇ⁾ = −1.500(3) of [HP] eqs. (q4a), (q4b). Dimensionless. Interpretation: we obtain q₄⁽ᵃ⁾ = −0.73402 (all estimators within 10⁻⁵) and q₄⁽ᵇ⁾ = −1.4993 with estimators "
           "spanning [−1.5033, −1.4984]; the last term ratios (0.365, 0.360) are still above the asymptotic value y_H = 0.268, so the geometric tail is an upper bound in magnitude. Limitations: "
           "the coefficients are the paper's microscopic output and are not recomputed; with 7 terms the q₄⁽ᵇ⁾ tail (−0.007) rests on an assumed growth law.")


def fig09():
    Bu = read_csv("hp_budget.csv"); Sc = read_csv("hp_sign_scenarios.csv"); Q = load_json("hp_quartic.json")["quartic"]
    fig, ax = plt.subplots(1, 2, figsize=(10.5, 3.9), gridspec_kw={"wspace": 0.42, "width_ratios": [1, 1.15]})
    a = ax[0]
    names = ["square of the one-loop\noperator ($Q_4$)", "exchange of $u_2$\n($c_3^2/A_2$)", "two-loop operator,\ntree part ($q_4^{(a)}$)", "two-loop operator,\nloop part ($q_4^{(b)}$)"]
    v = F(Bu, "value_in_g4_units"); yv = np.arange(4)[::-1]
    a.barh(yv, v, color=[BLUE, BLUE, VERM, VERM], height=0.6)
    a.plot(F(Bu, "paper_value"), yv, "|", color=BLACK, ms=16, mew=1.6, label="value printed in [HP] §7.1")
    for i in range(4):
        a.text(v[i] - 0.5, yv[i], f"{v[i]:.2f}", ha="right", va="center", fontsize=8)
    a.set_yticks(yv); a.set_yticklabels(names, fontsize=7.5); a.set_xlim(-37, 1.5); a.axvline(0, color=BLACK, lw=0.8)
    a.set_xlabel("contribution to $b$ in units of $g^4$"); a.set_title("All four pieces of $b$ are negative"); a.legend(loc="lower left", fontsize=7.5); letter(a, "a")
    b = ax[1]
    q = np.linspace(-6, 15, 50); b.plot(q, -4 * Q["beta0"] ** 2 * Q["I"] + Q["beta0"] * q, color=BLUE)
    b.axhline(0, color=BLACK, lw=0.8); b.axvline(Q["q4_crit"], color=GRAY, ls=":", lw=0.9)
    b.plot(Q["q4"], Q["b_over_g4"], "o", color=VERM, ms=7); b.annotate("paper inputs: $q_4=-2.234$,\n$b=-36.94\\,g^4$", (Q["q4"], Q["b_over_g4"]), (-0.5, -46.5), fontsize=8, arrowprops=dict(arrowstyle="-", lw=0.6, color=GRAY))
    pts = [s for s in Sc if s["scenario"].startswith(("drop", "flip", "two-loop", "shift"))]
    b.plot(F(pts, "q4"), F(pts, "b_over_g4"), "s", mfc="white", color=BLACK, ms=4.5, label="stress scenarios (results/hp_sign_scenarios.csv)")
    b.annotate("", (Q["q4_crit"], 6), (Q["q4"], 6), arrowprops=dict(arrowstyle="<->", lw=0.9, color=BLACK)); b.text((Q["q4"] + Q["q4_crit"]) / 2, 8, f"sign margin {Q['margin']:.2f}", ha="center", fontsize=8)
    b.text(Q["q4_crit"] + 0.25, -30, f"$b=0$ at\n$q_4={Q['q4_crit']:.2f}$", fontsize=8)
    b.set_xlabel("two-loop coefficient $q_4(x_H)$"); b.set_ylabel("quartic coefficient $b/g^4$"); b.set_ylim(-52, 14); b.set_title("The sign of $b$ survives large errors in $q_4$")
    b.legend(loc="lower right", fontsize=7.5); letter(b, "b")
    finish(fig, "fig09_quartic_budget",
           "Figure 9. Assembly of the quartic coefficient b = g⁴[−4β₀²I + β₀q₄] of [HP] eq. (master2) from the paper's inputs c₃ = 0.16821(1), Q₄ = 2.1222(3), q₄⁽ᵃ⁾ = −0.7340(1), q₄⁽ᵇ⁾ = −1.500(3), "
           "with A₂ and β₀ recomputed here. (a) The four contributions in units of g⁴ (g² = λ/16π²); black ticks: values printed in [HP] §7.1. (b) b/g⁴ as a function of q₄ with the paper's point, "
           "the zero crossing and stress scenarios (dropping or flipping the single-engine terms of q₄⁽ᵇ⁾, switching the two-loop operator off, shifting q₄ by ±0.8, the size of the unresolved "
           "pure-Yang–Mills discrepancy). Interpretation: b = −36.942 ± 0.009 g⁴ = −1.481×10⁻³ λ²; b would vanish only at q₄ = +11.79, a margin of 14.03 (about 4700 quoted standard errors). "
           "Limitations: this is arithmetic on the paper's microscopic coefficients; an error in I (84% of b) would matter far more than one in q₄, and I is checked here only through the scheme "
           "comparison 1.11918 versus 1.1200.")


def fig10():
    Cu = read_csv("hp_potential_curves.csv"); Sc = read_csv("hp_landau_scan.csv"); Te = read_csv("hp_temperatures.csv")
    fig, ax = plt.subplots(1, 3, figsize=(11.8, 4.0), gridspec_kw={"wspace": 0.4})
    a = ax[0]
    sel = [("m2=0.08 (T<T_min)", SKY, "$T<T_{\\min}$"), ("m2=m2_min", GREEN, "$T_{\\min}$"), ("m2=m2_c (T_c)", BLACK, "$T_c$"), ("m2=0 (T_H)", ORANGE, "$T_H$"), ("m2=-0.02 (T>T_H)", VERM, "$T>T_H$")]
    for lab, col, tx in sel:
        rr = [r for r in Cu if r["label"] == lab]; u = F(rr, "u"); s = F(rr, "S_full_restricted_domain")
        a.plot(u, s * 100, color=col, lw=1.8 if "T_c" in lab else 1.2, label=tx)
    rr = [r for r in Cu if r["label"] == "m2=m2_c (T_c)"]
    a.plot(F(rr, "u"), F(rr, "S_truncated_quartic_no_wall") * 100, color=BLACK, ls=":", lw=1.2, label="$T_c$, quartic only\n(no gapped branch)")
    a.axvline(0.5, color=GRAY, ls="--", lw=0.8); a.text(0.015, -0.9, "dashed: gap opens at $u=1/2$", fontsize=7.5, ha="left", color="#444444"); a.axhline(0, color=GRAY, lw=0.6)
    a.legend(loc="upper left", fontsize=7.2, ncol=3, columnspacing=0.8, handlelength=1.4)
    a.set_xlim(0, 0.8); a.set_ylim(-1.0, 3.3); a.set_xlabel("Polyakov loop $u=|u_1|$"); a.set_ylabel("$10^2\\times S(u)/N^2$  at $|b|=0.1$")
    a.set_title("Potential on the restricted domain $0\\leq u<1$"); letter(a, "a")
    b = ax[1]; ab = F(Sc, "abs_b")
    b.semilogx(ab, F(Sc, "m2_min_over_b"), color=GREEN); b.semilogx(ab, F(Sc, "m2_c_over_b"), color=BLACK)
    b.axhline(0.5, color=GREEN, ls=":", lw=1); b.axhline(0.25, color=BLACK, ls=":", lw=1)
    b.text(2e-6, 0.515, "$m^2_{\\min}/|b|$  (leading 1/2)", color=GREEN, fontsize=8); b.text(2e-6, 0.215, "$m^2_c/|b|$  (leading 1/4)", color=BLACK, fontsize=8)
    b.plot([0.1, 0.1], [0.53, 0.32], "s", mfc="none", color=VERM, ms=6); b.text(0.075, 0.42, "caption of\n[HP] Fig. 2", fontsize=7.5, color=VERM, ha="right")
    b.set_ylim(0.18, 0.62); b.set_xlabel("$|b|$"); b.set_ylabel("exact threshold / $|b|$"); b.set_title("Wall corrections grow like $\\sqrt{|b|}$"); letter(b, "b")
    c = ax[2]; lam = F(Te, "lambda")
    c.loglog(lam, F(Te, "window_min_exact"), "o-", color=GREEN, ms=4, label="$(T_H-T_{\\min})/T_H$, exact inversion")
    c.loglog(lam, F(Te, "window_c_exact"), "o-", color=BLACK, ms=4, label="$(T_H-T_c)/T_H$, exact inversion")
    c.loglog(lam, F(Te, "window_min_leading"), ":", color=GREEN); c.loglog(lam, F(Te, "window_c_leading"), ":", color=BLACK, label="leading order, [HP] eq. (window)")
    c.set_xlabel("'t Hooft coupling $\\lambda$"); c.set_ylabel("relative width of the metastability window"); c.set_title("$T_{\\min}<T_c<T_H$ at every coupling tested"); c.legend(loc="upper left", fontsize=7.2); letter(c, "c")
    finish(fig, "fig10_landau_transition",
           "Figure 10. The first-order transition on the paper's actual holonomy domain. (a) S(u)/N² = V(u) − u² + m₁²u² + b u⁴ with the Gross–Witten–Wadia branch V(u) = 1/4 − ½ ln[2(1 − u)] for "
           "u ≥ 1/2 ([HP] eqs. V, Sfull), at |b| = 0.1 (exaggerated, as in [HP] Fig. 2) for five values of m₁²; dotted: the quartic truncation without the gapped branch at T_c, which is unbounded "
           "below. (b) Exact thresholds m²_min (birth of the second minimum) and m²_c (degeneracy) divided by |b|; squares: values in the caption of [HP] Fig. 2. (c) Relative width of the window "
           "from an exact inversion of m₁²(T) through two loops with b = −36.94 g⁴, against the leading formulas |b|/3β₀ and |b|/6β₀. u is dimensionless; T in units of 1/R. Interpretation: "
           "at |b| = 0.1 we find m²_min = 0.05262 and m²_c = 0.03164 (caption: 0.053, 0.032); the jump is to u_c = 0.598, on the gapped branch; m²_c/|b| − 1/4 ≈ 0.172 |b|^0.50; the ordering "
           "T_min < T_c < T_H holds for λ = 0.01…5, and at λ = 1 the window is 1.03×10⁻⁴ (9.5% above the leading 9.37×10⁻⁵). Limitations: the potential keeps only u₁, the quartic term and the exact "
           "measure; beyond small λ the neglected O(λ³) terms and higher moments are comparable to the corrections shown, so panel (c) at λ ≳ 2 illustrates sensitivity, not a prediction. "
           "The conclusion 'first order' is conditional on the paper's b < 0.")


def fig11():
    Gv = read_csv("hp_gravity_branches.csv")
    import s08_hp_landau as L8
    fig, ax = plt.subplots(1, 2, figsize=(10.5, 3.9), gridspec_kw={"wspace": 0.3})
    a = ax[0]
    T = F(Gv, "T_times_R"); Fv = F(Gv, "F_in_units_pi_over_8G_R2"); br = np.array([r["branch"] for r in Gv])
    a.plot(T[br == "small"], Fv[br == "small"], color=VERM, ls="--", label="small black hole (unstable)"); a.plot(T[br == "large"], Fv[br == "large"], color=BLUE, label="large black hole")
    a.axhline(0, color=BLACK, lw=1.2); a.text(0.515, 0.02, "thermal AdS ($F=O(1)$)", fontsize=8)
    a.axvline(np.sqrt(2) / np.pi, color=GRAY, ls=":", lw=0.8); a.axvline(1.5 / np.pi, color=GRAY, ls=":", lw=0.8)
    a.text(np.sqrt(2) / np.pi - 0.004, -0.5, "$T_{\\min}=\\sqrt{2}/\\pi R$", fontsize=8, rotation=90, va="center", ha="right"); a.text(1.5 / np.pi + 0.004, -0.5, "$T_{\\rm HP}=3/2\\pi R$", fontsize=8, rotation=90, va="center")
    a.set_xlim(0.43, 0.6); a.set_ylim(-0.9, 0.35); a.set_xlabel("$T R$"); a.set_ylabel("free energy, units of $\\pi R^2/8G_N$")
    a.set_title("Gravity: Schwarzschild–AdS$_5$ branches"); a.legend(loc="lower left", fontsize=7.5); letter(a, "a")
    b = ax[1]
    m2s = np.linspace(-0.02, 0.07, 181); mn, mx = [], []
    for m2 in m2s:
        sd = L8.saddles(m2, -0.1, 6001)
        mins = [s for s in sd if s[2] == "min"]; maxs = [s for s in sd if s[2] == "max"]
        mn.append(mins[-1][1] if mins else np.nan); mx.append(maxs[0][1] if maxs else np.nan)
    b.plot(m2s, np.array(mx) * 100, color=VERM, ls="--", label="unstable saddle $u_s$"); b.plot(m2s, np.array(mn) * 100, color=BLUE, label="deconfined saddle $u\\gtrsim 1/2$")
    b.axhline(0, color=BLACK, lw=1.2); b.text(0.047, -0.07, "confined, $u=0$", fontsize=8)
    for xv, tx in ((0.05262, "$T_{\\min}$"), (0.03164, "$T_c$"), (0.0, "$T_H$")):
        b.axvline(xv, color=GRAY, ls=":", lw=0.8); b.text(xv - 0.001, -0.62, tx, fontsize=8, ha="left")
    b.set_xlim(0.07, -0.02); b.set_ylim(-0.75, 0.3); b.set_xlabel("$m_1^2$ (decreasing = heating)"); b.set_ylabel("$10^2\\times S/N^2$ at the saddle, $|b|=0.1$")
    b.set_title("Weak coupling: the same three saddles, plus $T_H$"); b.legend(loc="upper right", fontsize=7.5); letter(b, "b")
    finish(fig, "fig11_gravity_comparison",
           "Figure 11. Phase competition in gravity and at weak coupling. (a) Free energy of the small and large Schwarzschild–AdS₅ black holes relative to thermal AdS, from the textbook relations "
           "T = (2r₊² + R²)/(2πR²r₊) and F ∝ r₊²(R² − r₊²) (computed here; [HP] §1 quotes only T_min = √2/πR and T_HP = 3/2πR). (b) Action of the three saddles of the Polyakov-loop potential "
           "of [HP] eq. (Sfull) at |b| = 0.1 against m₁² (heating is to the right). Interpretation: both systems show a swallow-tail — two saddles born together at T_min, the stable one overtaking the "
           "confined/thermal-AdS phase at T_c or T_HP; the weak-coupling side has one extra feature, the merger of the unstable saddle with u = 0 at the Hagedorn temperature. In gravity "
           "T_min/T_HP = 0.943, at weak coupling T_min/T_c = 1 − 2.34 g⁴. Limitations: a structural analogy between two limits, with |b| exaggerated; nothing here shows that the two lines are connected "
           "at intermediate coupling ([HP] §1.6 makes the same disclaimer).")


if __name__ == "__main__":
    with Tee("s10_figures"):
        for f in (fig01, fig02, fig03, fig04, fig05, fig06, fig07, fig08, fig09, fig10, fig11):
            f()
        save_json("figure_captions.json", {"captions": CAPS, "qa": QA})
        nov = sum(len(v["text_overlaps"]) for v in QA.values()); nout = sum(len(v["text_outside_canvas"]) for v in QA.values())
        print(f"SUMMARY: {len(CAPS)} figures; text overlaps flagged: {nov}; text outside canvas: {nout}")
        event("figures", "Figures rendered from data", f"{len(CAPS)} PNG figures in figures/; geometric QA: {nov} text overlaps, {nout} off-canvas", outputs=[f"figures/{k}.png" for k in CAPS])
