#!/usr/bin/env python3
"""Diagrams for the E₄₇ formalism page, in the City visual grammar (dark ground).

Every number drawn here is recomputed from first principles or read from the
bundle's own outputs before it is drawn:
  fig_chain.svg   the generating chain, 3 lines → 125 → 7 sectors → μ∓σ → 47
  fig_census.svg  Clebsch–Gordan census of V₂^⊗3 (exact weight count)
  fig_energy.svg  spectrum of H = g·K² (schematic ladder, exact labels)
  fig_aes.svg     energy census of the 39 AES S-box relations over GF(2)¹⁶
"""
from collections import Counter
from pathlib import Path
import itertools
import re

HERE = Path(__file__).parent
BG, SURF, RAISED, LINE = "#0b0c0e", "#121518", "#171c1f", "#283035"
FG, MUTED, FAINT = "#f0eee8", "#9aa5a8", "#6f7a7d"
LIVE, LOCK, GHOST = "#62d5cc", "#b9e6c8", "#b88352"
SANS = "IBM Plex Sans, system-ui, sans-serif"
SERIF = "Newsreader, Georgia, serif"
MONO = "IBM Plex Mono, DejaVu Sans Mono, monospace"

# ── exact census of V₂^⊗3 from the weight multiset ──────────────────────────
weights = Counter(a + b + c for a, b, c in itertools.product(range(-2, 3), repeat=3))
copies = {J: weights[J] - weights.get(J + 1, 0) for J in range(7)}
dims = {J: copies[J] * (2 * J + 1) for J in range(7)}
assert [copies[J] for J in range(7)] == [1, 3, 5, 4, 3, 2, 1] and sum(dims.values()) == 125
lam = {J: J * (J + 1) for J in range(7)}
tau = lambda f: sum(dims[J] * f(lam[J]) for J in range(7)) / 125
mu = tau(lambda x: x)
sig = (tau(lambda x: x * x) - mu * mu) ** 0.5
assert (mu, sig) == (18, 12)
kept = {J for J in range(7) if lam[J] in (mu - sig, mu + sig)}
assert kept == {2, 5} and sum(dims[J] for J in kept) == 47
energy = {J: ((lam[J] - 6) * (lam[J] - 30)) ** 2 for J in range(7)}


def svg(w, h, body, title):
    return (f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" role="img" '
            f'aria-label="{title}"><title>{title}</title>'
            f'<rect width="{w}" height="{h}" rx="14" fill="{SURF}"/>{body}</svg>\n')


def text(x, y, s, size=14, fill=FG, anchor="middle", family=SANS, weight=400, style=""):
    return (f'<text x="{x}" y="{y}" font-family="{family}" font-size="{size}" fill="{fill}" '
            f'text-anchor="{anchor}" font-weight="{weight}" {style}>{s}</text>')


def arrow(x1, y1, x2, y2, color=FAINT):
    return (f'<line x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}" stroke="{color}" stroke-width="1.4"/>'
            f'<path d="M{x2},{y2} l-7,-4 v8 z" fill="{color}" '
            f'transform="rotate({0 if y1 == y2 else 90 if y2 > y1 else -90},{x2},{y2})"/>')


# ── fig 1: the generating chain ─────────────────────────────────────────────
def fig_chain():
    W, H = 980, 380
    b = []
    b.append(text(32, 44, "From three particles to one number, with nothing fitted",
                  20, FG, "start", SERIF, 500))
    stages = [("Carrier V<tspan dy=\"4\" font-size=\"11\">2</tspan><tspan dy=\"-11\" font-size=\"11\" font-family=\"Latin Modern Math, STIX Two Math, Cambria Math, serif\">⊗3</tspan><tspan dy=\"7\"> </tspan>", "125 states"), ("Casimir C", "7 sectors"),
              ("Moments μ ∓ σ", "18 ∓ 12 = 6, 30"), ("Kernel of K", "25 + 22 = 47"),
              ("Ω<tspan dy=\"4\" font-size=\"11\">c</tspan><tspan dy=\"-4\" dx=\"5\">= 47/125</tspan>", "0.376 exactly")]
    x0, y0, bw, bh, gap = 32, 160, 164, 74, 20
    for i, (t, s) in enumerate(stages):
        x = x0 + i * (bw + gap)
        goal = i == 4
        b.append(f'<rect x="{x}" y="{y0}" width="{bw}" height="{bh}" rx="9" '
                 f'fill="{"#10302d" if goal else RAISED}" stroke="{LIVE if goal else LINE}" '
                 f'stroke-width="{1.6 if goal else 1}"/>')
        b.append(text(x + bw / 2, y0 + 31, t, 15.5, LIVE if goal else FG, weight=500))
        b.append(text(x + bw / 2, y0 + 54, s, 13, MUTED, family=MONO))
        if i < 4:
            b.append(arrow(x + bw + 3, y0 + bh / 2, x + bw + gap - 3, y0 + bh / 2))
    # forced box
    b.append(f'<rect x="{x0}" y="68" width="520" height="62" rx="9" fill="{BG}" stroke="{LINE}"/>')
    b.append(text(x0 + 16, 90, "FORCED BY ARITHMETIC", 11.5, GHOST, "start", MONO, 500,
                  'letter-spacing="1.5"'))
    b.append(text(x0 + 16, 110, "n = 3: first tensor order with σ rational  ·  "
                  "j = 2: first proper spin with μ + σ a sector", 13, MUTED, "start"))
    b.append(arrow(x0 + bw / 2, 130, x0 + bw / 2, y0 - 3))
    # definition box
    cx = x0 + 2 * (bw + gap) + bw / 2
    b.append(f'<rect x="{cx - 130}" y="280" width="260" height="62" rx="9" fill="none" '
             f'stroke="{LINE}" stroke-dasharray="5 4"/>')
    b.append(text(cx, 304, "ONE DEFINITION", 11.5, GHOST, family=MONO, weight=500,
                  style='letter-spacing="1.5"'))
    b.append(text(cx, 325, "the selector rule (S)", 13, MUTED))
    b.append(arrow(cx, 280, cx, y0 + bh + 3))
    return svg(W, H, "".join(b), "The generating chain: two forced choices, one definition, five stages")


# ── fig 2: census ───────────────────────────────────────────────────────────
def fig_census():
    W, H = 980, 400
    b = [text(32, 44, "The selector keeps two of the seven Casimir sectors", 20, FG, "start", SERIF, 500),
         text(32, 70, "25 + 22 = 47 of 125 states · occupancy 47/125 = 0.376", 13.5, MUTED, "start", MONO)]
    base, scale, x0, step, bw = 318, 7.2, 92, 130, 74
    b.append(f'<line x1="40" y1="{base}" x2="{W - 40}" y2="{base}" stroke="{LINE}"/>')
    for J in range(7):
        x = x0 + J * step
        d = dims[J]
        k = J in kept
        h = d * scale
        b.append(f'<rect x="{x - bw / 2}" y="{base - h}" width="{bw}" height="{h}" rx="3" '
                 f'fill="{LIVE if k else RAISED}" stroke="{LIVE if k else LINE}"/>')
        b.append(text(x, base - h - 9, d, 15, LIVE if k else MUTED, family=MONO,
                      weight=600 if k else 400))
        b.append(text(x, base + 24, f"λ = {lam[J]}", 14, LIVE if k else FG, family=MONO))
        b.append(text(x, base + 44, f"spin {J} · {copies[J]}×V{J}", 12, FAINT))
    return svg(W, H, "".join(b), "Clebsch–Gordan census of V₂⊗³: seven sectors, 125 states, two kept")


# ── fig 3: energy ladder of H = gK² ─────────────────────────────────────────
def fig_energy():
    W, H = 980, 430
    levels = sorted({energy[J] for J in range(7)})
    deg = {e: sum(dims[J] for J in range(7) if energy[J] == e) for e in levels}
    spins = {e: [J for J in range(7) if energy[J] == e] for e in levels}
    assert levels == [0, 11664, 12544, 19600, 32400, 186624]
    assert [deg[e] for e in levels] == [47, 28, 9, 27, 1, 13]
    b = [text(32, 44, "Spectrum of the energy H = g·K²", 20, FG, "start", SERIF, 500),
         text(32, 70, "levels E_J = g[J(J+1) − 6]²[J(J+1) − 30]² · schematic heights, exact labels",
              13, MUTED, "start", MONO)]
    ys = [372, 300, 252, 204, 156, 100]
    for e, y in zip(levels, ys):
        wide = 40 + 4.4 * deg[e]
        ground = e == 0
        col = LIVE if ground else (GHOST if e == 186624 else LOCK)
        b.append(f'<line x1="300" y1="{y}" x2="{300 + wide}" y2="{y}" stroke="{col}" '
                 f'stroke-width="{4 if ground else 2.4}" stroke-linecap="round"/>')
        lab = "0 · ground manifold E₄₇" if ground else f"{e:,} g".replace(",", " ")
        b.append(text(282, y + 5, lab, 14, col if ground else FG, "end", MONO, 500 if ground else 400))
        js = " + ".join(f"J={J}" for J in spins[e])
        b.append(text(300 + wide + 16, y + 5, f"×{deg[e]}  ({js})", 13, MUTED, "start", MONO))
    b.append(f'<line x1="250" y1="{ys[0] - 8}" x2="250" y2="{ys[1] + 8}" stroke="{GHOST}" '
             f'stroke-width="1.2" stroke-dasharray="3 3"/>')
    b.append(text(240, (ys[0] + ys[1]) / 2 + 5, "Δ = 108² g", 13, GHOST, "end", MONO))
    b.append(text(W - 36, 408, "κ = M/Δ = 186624/11664 = 16  ·  ε⋆ = 1/99144  ·  rate (κ−1)/(κ+1) = 15/17",
                  12.5, FAINT, "end", MONO))
    return svg(W, H, "".join(b), "Energy spectrum of H = gK²: 47 zero-energy states, gap 11664 g, top 186624 g")


# ── fig 4: AES S-box relation census over GF(2)^16 ──────────────────────────
def fig_aes():
    mq = (HERE.parent / "aes-spectrum" / "aes_sbox_mq.txt").read_text().splitlines()
    names = [f"{a}{i}" for a in "xy" for i in range(8)]
    eqs = [[0 if t == "1" else sum(1 << names.index(v) for v in t.split("*"))
            for t in line.split(" =")[0].split(" + ")] for line in mq]
    census = Counter()
    for z in range(1 << 16):
        census[sum(sum((z & m) == m for m in t) % 2 for t in eqs)] += 1
    assert census[0] == 256 and min(e for e in census if e) == 7 and max(census) == 34
    import math
    W, H = 980, 420
    b = [text(32, 44, "Energy census of the 39 AES S-box relations over GF(2)¹⁶", 20, FG, "start", SERIF, 500),
         text(32, 70, "E(x, y) = number of violated relations · 65 536 states · log scale",
              13, MUTED, "start", MONO)]
    base, top, x0, step = 340, 100, 70, 25.2
    lg = lambda n: (math.log10(n) / math.log10(10000)) * (base - top)
    for t in (1, 10, 100, 1000, 10000):
        y = base - lg(t)
        b.append(f'<line x1="{x0 - 14}" y1="{y}" x2="{x0 + 35 * step}" y2="{y}" stroke="{LINE}" '
                 f'stroke-width="0.6"/>')
        b.append(text(x0 - 20, y + 4, f"{t:,}".replace(",", " "), 11, FAINT, "end", MONO))
    for e in range(35):
        x = x0 + e * step
        n = census.get(e, 0)
        if n:
            h = max(lg(n), 2)
            col = LIVE if e == 0 else RAISED
            b.append(f'<rect x="{x + 2}" y="{base - h}" width="{step - 4}" height="{h}" rx="2" '
                     f'fill="{col}" stroke="{LIVE if e == 0 else LINE}"/>')
        if e % 5 == 0 or e in (7, 34):
            b.append(text(x + step / 2, base + 20, e, 11.5, LIVE if e == 0 else MUTED, family=MONO))
    b.append(text(x0 + step / 2, base - lg(256) - 10, "256", 13, LIVE, family=MONO, weight=600))
    b.append(text(x0 + 4 * step, base - 40, "gap 1…6 empty", 12, GHOST, family=MONO))
    b.append(text(W - 36, 398, "kernel = graph of the S-box (256 states) · gap 7 · top 34 · ε⋆ = 2/41 · rate 27/41",
                  12.5, FAINT, "end", MONO))
    return svg(W, H, "".join(b), "AES S-box relation census: 256 zero-energy states, gap 7, maximum 34")


if __name__ == "__main__":
    for name, fn in (("fig_chain", fig_chain), ("fig_census", fig_census),
                     ("fig_energy", fig_energy), ("fig_aes", fig_aes)):
        (HERE / f"{name}.svg").write_text(fn(), encoding="utf-8")
        print("wrote", name)
