"""Site figures for β(I) on the sphere: light + dark PNGs (colormap is quantitative,
so we do not rely on automatic lightness inversion)."""
from pathlib import Path
import json, sys
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.patches import FancyBboxPatch
import matplotlib.ticker as mticker

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from groups import group, classes

FIG = HERE.parent / "figures"
EX = json.loads((HERE / "exact.json").read_text())
DARK_PNG = Path("/workspace/math/zeta-zeros-build/darkmode-20261111/png")

VMIN, VMAX = 0.06, 0.34
TITLES = {
    "2T": "binary tetrahedral 2T  (24 elements)",
    "2O": "binary octahedral 2O  (48 elements)",
    "2I": "binary icosahedral 2I  (120 elements)",
}
TITLES_M = {
    "2T": "binary tetrahedral 2T",
    "2O": "binary octahedral 2O",
    "2I": "binary icosahedral 2I",
}

# Light: deep teal-blue → green → gold, on paper #faf8f2.
# Dark: mid teal (visible on #27211c) → green → bright gold; same direction (low=cool, high=warm).
LIGHT_RAMP = [
    "#1f3b4d", "#23485a", "#2a5a68", "#336e70", "#3f7763",
    "#4d8a62", "#64965a", "#7ea34f", "#97ab4c", "#b28b4e",
    "#c4a05a", "#d4b56a", "#e0c57c", "#e8d396", "#eee3b0",
]
DARK_RAMP = [
    "#3d6f86", "#3f7f80", "#4a8f7a", "#5aa070", "#6eaf66",
    "#86b85c", "#9fc057", "#b8a85a", "#c9b06a", "#d8bc78",
    "#e4c888", "#eed49a", "#f3e0b0", "#f6ebd0", "#f8f2e4",
]
THEMES = {
    "light": dict(paper="#faf8f2", ink="#233d36", muted="#65746c", star="#a8553a",
                  edge="#faf8f2", ramp=LIGHT_RAMP, cbar_outline="#233d36"),
    "dark":  dict(paper="#27211c", ink="#dfd9d4", muted="#bcb1a6", star="#e18781",
                  edge="#27211c", ramp=DARK_RAMP, cbar_outline="#dfd9d4"),
}

def beta_on(name, P):
    G = group(name)
    cl = classes(G)
    N = len(G)
    B = np.zeros(len(P))
    for C in cl:
        s2 = 1 - C[0][0] ** 2
        if s2 < 1e-12:
            continue
        a = np.array([c[1:] / np.linalg.norm(c[1:]) for c in C])
        B += (len(C) / N) * s2 * (1 - ((P @ a.T) ** 2).max(1))
    return B

def grid(nlon=720, nlat=360):
    lon = np.linspace(-np.pi, np.pi, nlon)
    lat = np.linspace(-np.pi / 2, np.pi / 2, nlat)
    LON, LAT = np.meshgrid(lon, lat)
    P = np.stack([np.cos(LAT) * np.cos(LON), np.cos(LAT) * np.sin(LON), np.sin(LAT)], -1).reshape(-1, 3)
    return LON, LAT, P

def star_lonlat(name):
    I = np.array([float(x) for x in EX[name]["argmin"]])
    I = I / np.linalg.norm(I)
    return np.arctan2(I[1], I[0]), np.arcsin(np.clip(I[2], -1, 1))

def style_ax(ax, th):
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.grid(False)
    ax.set_facecolor(th["paper"])
    for sp in ax.spines.values():
        sp.set_visible(False)
    # hide the default degree ticks fully
    ax.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False)
    ax.grid(False)
    ax.xaxis.set_major_formatter(matplotlib.ticker.NullFormatter())
    ax.yaxis.set_major_formatter(matplotlib.ticker.NullFormatter())
    ax.xaxis.set_major_locator(matplotlib.ticker.NullLocator())
    ax.yaxis.set_major_locator(matplotlib.ticker.NullLocator())

def draw(path, theme, stacked=False):
    th = THEMES[theme]
    cmap = LinearSegmentedColormap.from_list("beta", th["ramp"], N=256)
    names = ["2T", "2O", "2I"]
    titles = TITLES_M if stacked else TITLES
    LON, LAT, P = grid()
    Bs = {n: beta_on(n, P).reshape(LAT.shape) for n in names}

    if stacked:
        fig, axs = plt.subplots(3, 1, figsize=(6.2, 12.2), subplot_kw=dict(projection="mollweide"))
        top = 0.86
        bottom = 0.07
        title_y, kicker_y, tag_y = 0.945, 0.985, 0.915
        cbar_pos = [0.18, 0.022, 0.64, 0.012]
    else:
        fig, axs = plt.subplots(1, 3, figsize=(12.4, 5.6), subplot_kw=dict(projection="mollweide"))
        top = 0.78
        bottom = 0.18
        title_y, kicker_y, tag_y = 0.90, 0.96, 0.90
        cbar_pos = [0.28, 0.07, 0.44, 0.025]

    fig.patch.set_facecolor(th["paper"])
    fig.subplots_adjust(left=0.04, right=0.96, top=top, bottom=bottom, wspace=0.08, hspace=0.28)

    fig.text(0.04, kicker_y, "BINARY POLYHEDRAL GROUPS  ·  BARRIER EXPONENT  β(I)",
             fontsize=8, color=th["muted"], fontname="DejaVu Sans", ha="left", va="top")
    fig.text(0.04, title_y, "How the barrier changes with the choice of axis",
             fontsize=16 if not stacked else 13.5, color=th["ink"], fontname="DejaVu Serif", ha="left", va="top")
    if stacked:
        fig.text(0.04, tag_y, "[project; 2O/2I minima by scan]",
                 fontsize=8, color=th["muted"], fontname="DejaVu Sans", ha="left", va="top")
    else:
        fig.text(0.96, tag_y, "[project; 2O/2I minima by scan]",
                 fontsize=8, color=th["muted"], fontname="DejaVu Sans", ha="right", va="top")

    last_m = None
    for ax, name in zip(np.atleast_1d(axs), names):
        style_ax(ax, th)
        last_m = ax.pcolormesh(LON, LAT, Bs[name], cmap=cmap, shading="auto", vmin=VMIN, vmax=VMAX)
        lon, lat = star_lonlat(name)
        ax.plot(lon, lat, marker="*", markersize=13, color=th["star"],
                markeredgecolor=th["edge"], markeredgewidth=0.7, zorder=5)
        bmin = float(EX[name]["beta_min"])
        ax.set_title(f"{titles[name]}\nmin β = {bmin:.4f}",
                     fontsize=10, color=th["ink"], fontname="DejaVu Serif", pad=8)
        # title color: matplotlib title uses default; set_title color should work
        ax.title.set_color(th["ink"])

    cax = fig.add_axes(cbar_pos)
    cb = fig.colorbar(last_m, cax=cax, orientation="horizontal")
    cb.set_label("barrier exponent  β(I)", color=th["muted"], fontsize=8, fontname="DejaVu Sans")
    cb.ax.tick_params(colors=th["muted"], labelsize=8, length=3)
    cb.outline.set_edgecolor(th["cbar_outline"])
    cb.outline.set_linewidth(0.6)
    cb.set_ticks([0.08, 0.12, 0.16, 0.20, 0.24, 0.28, 0.32])
    for lab in cb.ax.get_xticklabels():
        lab.set_fontname("DejaVu Sans")
        lab.set_color(th["muted"])

    fig.savefig(path, dpi=140, facecolor=th["paper"], edgecolor="none")
    plt.close(fig)
    print(f"wrote {path} ({path.stat().st_size} bytes)")

def main():
    DARK_PNG.mkdir(parents=True, exist_ok=True)
    light = FIG / "binary-polyhedral-beta-site.png"
    light_m = FIG / "binary-polyhedral-beta-site-mobile.png"
    dark = FIG / "binary-polyhedral-beta-site-dark.png"
    dark_m = FIG / "binary-polyhedral-beta-site-mobile-dark.png"
    draw(light, "light", stacked=False)
    draw(light_m, "light", stacked=True)
    draw(dark, "dark", stacked=False)
    draw(dark_m, "dark", stacked=True)
    # fallbacks consumed by dark_figs when no same-stem dark SVG exists
    import shutil
    shutil.copy(dark, DARK_PNG / "hyper-binary-polyhedral-beta-dark.png")
    shutil.copy(dark_m, DARK_PNG / "hyper-binary-polyhedral-beta-mobile-dark.png")
    print("copied dark fallbacks to", DARK_PNG)

if __name__ == "__main__":
    main()
