"""Render measured ScriptBots runs into inline SVG figures for scriptbots.org.

Usage: python3 charts.py <data dir> <out dir>

Reads the JSON written by measure.mjs and writes one HTML fragment per figure into <out dir>.
web/build-site.sh calls render() instead and puts each fragment at its `<!-- chart: name -->`
marker in web/index.html, so the page is always drawn from the committed data. The page's CSP
forbids inline style, so every mark carries a class and web/site.css colors it. Each figure has
a legend, direct labels, a JSON block that web/site.mjs reads for the hover crosshair, a note,
and a table view of the same numbers.
"""
import html
import json
import math
import pathlib
import struct
import sys
import tomllib

W, H = 640, 320
L, R, T, B = 60, 112, 22, 40
PW, PH = W - L - R, H - T - B

SEEDS = {42: "k42", 137: "k137", 20260717: "k2026", 11: "k11"}
FAMILIES = [("mlp", "MLP", "fam-mlp"), ("dwraon", "DWRAON", "fam-dwraon"), ("assembly", "Assembly", "fam-asm")]
DIETS = [(0, "Hunters", "diet-hunt"), (1, "Generalists", "diet-gen"), (2, "Grazers", "diet-graze")]


def esc(text):
    return html.escape(str(text), quote=True)


def nice(top):
    """A rounded axis maximum and its step: about four steps of 1, 2, 2.5 or 5 x 10^k."""
    if top <= 0:
        return 1, 1
    raw = top / 4
    mag = 10 ** math.floor(math.log10(raw))
    step = next(m * mag for m in (1, 2, 2.5, 5, 10) if m * mag >= raw)
    return step * math.ceil(top / step), step


def fmt(v):
    if isinstance(v, float) and not v.is_integer():
        return f"{v:,.1f}" if abs(v) >= 10 else f"{v:.2f}"
    return f"{int(v):,}"


def path(points):
    return "M" + " L".join(f"{x:.1f} {y:.1f}" for x, y in points)


def place_labels(ends, lo, hi, gap=16):
    """Spread end labels vertically so none overlap, keeping each near its line."""
    order = sorted(range(len(ends)), key=lambda i: ends[i])
    ys = [ends[i] for i in order]
    for k in range(1, len(ys)):
        ys[k] = max(ys[k], ys[k - 1] + gap)
    if ys and ys[-1] > hi:
        ys[-1] = hi
        for k in range(len(ys) - 2, -1, -1):
            ys[k] = min(ys[k], ys[k + 1] - gap)
    placed = [0.0] * len(ends)
    for k, i in enumerate(order):
        placed[i] = max(lo, ys[k])
    return placed


def axes(xmax, xticks, ymax, ystep, xlabel, ylabel, pct=False, sx=None, sy=None):
    sx = sx or (lambda x: L + PW * x / xmax)
    sy = sy or (lambda y: T + PH * (1 - y / ymax))
    parts = []
    y = 0.0
    while y <= ymax + 1e-9:
        parts.append(f'<line class="grid" x1="{L}" x2="{L + PW}" y1="{sy(y):.1f}" y2="{sy(y):.1f}"/>')
        parts.append(f'<text class="ytick" x="{L - 8}" y="{sy(y) + 4:.1f}">{f"{y:.0f}%" if pct else fmt(y)}</text>')
        y += ystep
    for x in xticks:
        parts.append(f'<text class="xtick" x="{sx(x):.1f}" y="{T + PH + 20}">{fmt(x)}</text>')
    parts.append(f'<line class="axis" x1="{L}" x2="{L + PW}" y1="{T + PH}" y2="{T + PH}"/>')
    parts.append(f'<text class="xlabel" x="{L + PW}" y="{H - 3}">{esc(xlabel)}</text>')
    parts.append(f'<text class="ylabel" x="{L - 8}" y="{T - 10}">{esc(ylabel)}</text>')
    return sx, sy, parts


def ticks_for(xmax):
    step = {1500: 250, 10000: 2000, 50000: 10000}.get(xmax, xmax / 4)
    return [i * step for i in range(int(xmax / step) + 1)]


def table(head, rows):
    th = "".join(f'<th scope="col">{esc(h)}</th>' for h in head)
    body = "".join(
        "<tr>" + "".join(f'<th scope="row">{esc(c)}</th>' if j == 0 else f"<td>{esc(c)}</td>" for j, c in enumerate(r)) + "</tr>"
        for r in rows
    )
    return (f'<details class="chart-table"><summary>Show the numbers</summary><div class="table-scroll">'
            f"<table><thead><tr>{th}</tr></thead><tbody>{body}</tbody></table></div></details>")


def figure(fid, title, note, svg, legend, label, hover, table_html, height=H):
    legend_html = "".join(f'<li><i class="key {cls}" aria-hidden="true"></i>{esc(name)}</li>' for cls, name in legend)
    data = f'<script type="application/json" class="chart-data">{json.dumps(hover, separators=(",", ":"))}</script>' if hover else ""
    focus = ' tabindex="0"' if hover else ""
    xhair = f'<line class="xhair" x1="0" x2="0" y1="{T}" y2="{T + PH}"/>' if hover else ""
    tip = '<div class="chart-tip" hidden></div>' if hover else ""
    return (f'<figure class="chart" id="{fid}">\n'
            f'  <figcaption class="chart-title">{esc(title)}</figcaption>\n'
            f'  <ul class="chart-legend">{legend_html}</ul>\n'
            f'  <div class="chart-plot"><div class="chart-canvas"><svg viewBox="0 0 {W} {height}" role="img" aria-label="{esc(label)}"{focus}>{svg}{xhair}</svg>{tip}</div></div>\n'
            f'  {data}\n'
            f'  <p class="chart-note">{note}</p>\n'
            f'  {table_html}\n'
            f'</figure>\n')


def lines_chart(fid, title, note, series, xmax, label, ylabel, table_every, refs=(), unit="creatures"):
    ymax, ystep = nice(max(max(v for _, v in s["points"]) for s in series) * 1.04)
    sx, sy, parts = axes(xmax, ticks_for(xmax), ymax, ystep, "Tick", ylabel)
    for ref in refs:
        if ref["kind"] == "band":
            parts.insert(0, f'<rect class="band" x="{L}" y="{T}" width="{sx(ref["x"]) - L:.1f}" height="{PH}"/>')
            parts.append(f'<text class="ref-label" x="{L + 6}" y="{T + 14}">{esc(ref["text"])}</text>')
        if ref["kind"] == "hline" and ref["y"] <= ymax:
            parts.append(f'<line class="ref" x1="{L}" x2="{L + PW}" y1="{sy(ref["y"]):.1f}" y2="{sy(ref["y"]):.1f}"/>')
            dy = 16 if ref.get("below") else -6
            parts.append(f'<text class="ref-label" x="{L + 6}" y="{sy(ref["y"]) + dy:.1f}">{esc(ref["text"])}</text>')
    ends = []
    for s in series:
        pts = [(sx(x), sy(v)) for x, v in s["points"]]
        parts.append(f'<path class="line {s["cls"]}" d="{path(pts)}"/>')
        ends.append(pts[-1][1])
    for s, y in zip(series, place_labels(ends, T + 6, T + PH - 2)):
        parts.append(f'<text class="end {s["cls"]}" x="{L + PW + 8}" y="{y + 4:.1f}">{esc(s["label"])}</text>')
    xs = [x for x, _ in series[0]["points"]]
    hover = {"x0": L, "w": PW, "xmax": xmax, "y0": T, "h": PH, "ymax": ymax, "xs": xs, "unit": unit,
             "series": [{"name": s["label"], "cls": s["cls"], "v": [v for _, v in s["points"]]} for s in series]}
    rows = [[fmt(x)] + [fmt(s["points"][k][1]) for s in series]
            for k, x in enumerate(xs) if x % table_every == 0 or k == len(xs) - 1]
    return figure(fid, title, note, "".join(parts), [(s["cls"], s["label"]) for s in series], label, hover,
                  table(["Tick"] + [s["label"] for s in series], rows))


def share_chart(fid, title, note, xs, layers, label, table_every):
    """100% stacked areas, bottom-up in the given order; the surface-colored stroke makes the 2px gaps."""
    sx, sy, parts = axes(xs[-1], ticks_for(xs[-1]), 100, 25, "Tick", "Share of the living", pct=True)
    totals = [sum(layer["v"][k] for layer in layers) or 1 for k in range(len(xs))]
    base = [0.0] * len(xs)
    mids = []
    for layer in layers:
        top = [base[k] + 100 * layer["v"][k] / totals[k] for k in range(len(xs))]
        upper = [(sx(x), sy(t)) for x, t in zip(xs, top)]
        lower = [(sx(x), sy(b)) for x, b in zip(xs, base)][::-1]
        parts.append(f'<path class="area {layer["cls"]}" d="{path(upper + lower)} Z"/>')
        mids.append(sy((top[-1] + base[-1]) / 2))
        base = top
    for layer, y in zip(layers, place_labels(mids, T + 6, T + PH - 2)):
        parts.append(f'<text class="end {layer["cls"]}" x="{L + PW + 8}" y="{y + 4:.1f}">{esc(layer["label"])}</text>')
    hover = {"x0": L, "w": PW, "xmax": xs[-1], "xs": xs, "pct": True, "unit": "creatures",
             "series": [{"name": l["label"], "cls": l["cls"], "v": [round(100 * l["v"][k] / totals[k], 1) for k in range(len(xs))],
                         "n": l["v"]} for l in layers]}
    rows = [[fmt(x)] + [f'{100 * l["v"][k] / totals[k]:.0f}% ({l["v"][k]:,})' for l in layers]
            for k, x in enumerate(xs) if x % table_every == 0 or k == len(xs) - 1]
    return figure(fid, title, note, "".join(parts), [(l["cls"], l["label"]) for l in layers], label, hover,
                  table(["Tick"] + [l["label"] for l in layers], rows))


def bars_chart(fid, title, note, runs, groups, label):
    """Horizontal 100% segmented bars, one per run, with a 2px surface gap between segments."""
    row_h, bar_h, top = 40, 22, 12
    x0, x1, nx = 168, 560, 568
    height = top + row_h * len(runs) + 8
    parts = []
    for i, run in enumerate(runs):
        y = top + i * row_h
        total = sum(run["counts"]) or 1
        parts.append(f'<text class="bar-label" x="{x0 - 10}" y="{y + bar_h / 2 + 4:.1f}">{esc(run["label"])}</text>')
        parts.append(f'<text class="bar-total" x="{nx}" y="{y + bar_h / 2 + 4:.1f}">{run["total_label"]}</text>')
        x = x0
        for (key, name, cls), count in zip(groups, run["counts"]):
            w = (x1 - x0) * count / total
            if w <= 0:
                continue
            drawn = max(w - 2, 0.5)
            share = 100 * count / total
            parts.append(f'<rect class="seg {cls}" x="{x:.1f}" y="{y}" width="{drawn:.1f}" height="{bar_h}" rx="3">'
                         f'<title>{esc(run["label"])} · {esc(name)}: {count:,} ({share:.0f}%)</title></rect>')
            if drawn >= 34:
                parts.append(f'<text class="seg-label" x="{x + drawn / 2:.1f}" y="{y + bar_h / 2 + 4:.1f}">{share:.0f}%</text>')
            x += w
    rows = [[run["label"]] + [f"{c:,} ({100 * c / (sum(run['counts']) or 1):.0f}%)" for c in run["counts"]] for run in runs]
    return figure(fid, title, note, "".join(parts), [(cls, name) for _, name, cls in groups], label, None,
                  table(["Run"] + [name for _, name, _ in groups], rows), height=height)


def scatter_chart(fid, title, note, sets, label):
    xmax, xstep = nice(max(p[0] for s in sets for p in s["points"]) * 1.04)
    ymax, ystep = nice(max(p[1] for s in sets for p in s["points"]) * 1.06)
    xticks = [i * xstep for i in range(int(round(xmax / xstep)) + 1)]
    sx, sy, parts = axes(xmax, xticks, ymax, ystep, "Living creatures", "Milliseconds per tick")
    for s in sets:
        for px, py in s["points"]:
            parts.append(f'<circle class="dot {s["cls"]}" cx="{sx(px):.1f}" cy="{sy(py):.1f}" r="4">'
                         f'<title>{esc(s["label"])}: {px:,} creatures, {py:.1f} ms a tick</title></circle>')
    rows = []
    for s in sets:
        for px, py in s["points"][:: max(1, len(s["points"]) // 8)]:
            rows.append([s["label"], f"{px:,}", f"{py:.2f}"])
    return figure(fid, title, note, "".join(parts), [(s["cls"], s["label"]) for s in sets], label, None,
                  table(["Run", "Living creatures", "ms per tick"], rows))


def render(data):
    """Return {marker name: figure HTML} for the runs in the data directory."""
    load = lambda name: json.loads((data / name).read_text())
    meadow = {seed: load(f"meadow-{seed}.json") for seed in (42, 137, 20260717)}
    ffm = {seed: load(f"ffm-{seed}.json") for seed in (11, 42, 137)}
    em = {seed: load(f"em-{seed}.json") for seed in (42, 137, 11)}
    figures = {}

    figures["em-population"] = lines_chart(
        "chart-em", "Evolution Meadow: living creatures over 50,000 ticks",
        "One run per seed, every 250 ticks. Arrivals keep at least 64 alive and add one creature every 100 ticks. "
        "The scenario’s own check asks for 64 to 1,024 alive at tick 10,000; the seeds had 73, 71 and 67.",
        [{"label": f"Seed {seed}", "cls": SEEDS[seed], "points": [(r["tick"], r["population"]) for r in em[seed]["rows"]]}
         for seed in (42, 137, 11)],
        50000, "Line chart of Evolution Meadow’s population over 50,000 ticks for seeds 42, 137 and 11. "
               "All three stay between 64 and 114 creatures.", "Living creatures", 5000,
        refs=[{"kind": "hline", "y": 64, "text": "Floor of 64", "below": True}])

    def windows(rows, size=5000):
        by = {r["tick"]: r for r in rows}
        return [(t, by[t]["births"] - by[t - size]["births"]) for t in range(size, rows[-1]["tick"] + 1, size)]

    figures["em-births"] = lines_chart(
        "chart-em-births", "Evolution Meadow: births in each 5,000 ticks",
        "Births counted in consecutive 5,000-tick windows; each point sits at the window’s end. Scheduled "
        "arrivals add 50 creatures per window, and the floor adds more while the count is below 64.",
        [{"label": f"Seed {seed}", "cls": SEEDS[seed], "points": windows(em[seed]["rows"])} for seed in (42, 137, 11)],
        50000, "Line chart of births per 5,000 ticks in Evolution Meadow for seeds 42, 137 and 11. "
               "Births rise from 9 to 15 in the first window to 64 to 91 in the last.", "Births per 5,000 ticks", 5000,
        refs=[{"kind": "hline", "y": 50, "text": "Scheduled arrivals"}], unit="births")

    em42 = em[42]["rows"]
    figures["em-diet"] = share_chart(
        "chart-em-diet", "Evolution Meadow, seed 42: the diet mix of the living",
        "The Observatory’s groups: hunters have diet below ⅓, grazers above ⅔. Remember that only diet below "
        "½ can stab. Shares every 250 ticks; hover or open the table for counts.",
        [r["tick"] for r in em42],
        [{"label": name, "cls": cls, "v": [r["diets"][i] for r in em42]} for i, name, cls in DIETS],
        "Stacked area chart of the diet mix in Evolution Meadow seed 42 over 50,000 ticks. "
        "Grazers grow from under half to about seven in ten.", 5000)

    figures["meadow-population"] = lines_chart(
        "chart-meadow", "Timed Meadow: living creatures, three declared seeds",
        "One run per seed, every 25 ticks. The shaded span is the scenario’s own check, which asks for 10 to 250 "
        "creatures alive at tick 360; with solid bodies the three seeds end tick 360 with 301, 359 and 307.",
        [{"label": f"Seed {seed}", "cls": SEEDS[seed], "points": [(r["tick"], r["population"]) for r in meadow[seed]["rows"]]}
         for seed in (42, 137, 20260717)],
        1500, "Line chart of Timed Meadow’s population over 1,500 ticks for seeds 42, 137 and 20260717. "
              "All three grow from 64 to about 13,000.", "Living creatures", 100,
        refs=[{"kind": "band", "x": 360, "text": "Check at tick 360"}])

    figures["ffm-population"] = lines_chart(
        "chart-ffm", "Food-funded Meadow: living creatures over 10,000 ticks",
        "One run per seed, every 100 ticks. No seed died out. Each lost most of its 64 founders first, "
        "then births caught up on seeds 42 and 137.",
        [{"label": f"Seed {seed}", "cls": SEEDS[seed], "points": [(r["tick"], r["population"]) for r in ffm[seed]["rows"]]}
         for seed in (11, 42, 137)],
        10000, "Line chart of Food-funded Meadow’s population over 10,000 ticks for seeds 11, 42 and 137. "
               "They end at 8, 80 and 45 creatures.", "Living creatures", 500)

    end_runs = ([{"label": f"Evolution · {seed}", "src": em[seed]} for seed in (42, 137, 11)]
                + [{"label": f"Timed · {seed}", "src": meadow[seed]} for seed in (42, 137, 20260717)]
                + [{"label": f"Food-funded · {seed}", "src": ffm[seed]} for seed in (11, 42, 137)])
    fam_runs, diet_runs = [], []
    for run in end_runs:
        last = run["src"]["rows"][-1]
        total = f'{last["population"]:,}'
        fam_runs.append({"label": run["label"], "total_label": total, "counts": [last["families"][k] for k, _, _ in FAMILIES]})
        diet_runs.append({"label": run["label"], "total_label": total, "counts": [last["diets"][i] for i, _, _ in DIETS]})
    figures["end-families"] = bars_chart(
        "chart-families", "Brain families alive at the end of each run",
        "Every run starts with 22 MLP, 21 DWRAON and 21 Assembly brains. Evolution runs end at tick 50,000, "
        "Timed at 1,500 and Food-funded at 10,000; the number after each bar is how many were alive then.",
        fam_runs, FAMILIES, "Segmented bar chart of the brain-family mix at the end of nine runs.")
    figures["end-diets"] = bars_chart(
        "chart-diets", "Diet groups alive at the end of each run",
        "The same nine runs, sorted into hunters, generalists and grazers.",
        diet_runs, DIETS, "Segmented bar chart of the diet mix at the end of nine runs.")

    figures["cost"] = scatter_chart(
        "chart-cost", "Cost of a tick as Timed Meadow fills up",
        "Each dot is the mean wall time of 25 consecutive ticks against the living count at their end, every "
        "50 ticks, for the serial browser build on one core.",
        [{"label": f"Seed {seed}", "cls": SEEDS[seed],
          "points": [(r["population"], r["msPerTick"]) for r in meadow[seed]["rows"]
                     if r["msPerTick"] is not None and r["tick"] % 50 == 0]}
         for seed in (42, 137, 20260717)],
        "Scatter chart of milliseconds per tick against living creatures for three Timed Meadow runs.")
    return figures


# The parameter reference: settings that change what happens in a world, grouped by the section
# that explains them. Logging, storage, archive, render and agent-control settings are left out.
PARAMETER_GROUPS = [
    ("World and bodies", "body-title", "01.1", [
        ("world_width", "World width in units"),
        ("world_height", "World height in units"),
        ("closed", "No arrivals at all, floor included"),
        ("bot_radius", "Body radius"),
        ("bot_speed", "Wheel speed at full output"),
        ("boost_multiplier", "Wheel speed multiplier while boosting"),
        ("locomotion_model", "How wheel outputs move the body"),
        ("sense_radius", "Reach of smell, sound, hearing and blood"),
        ("topography_enabled", "Let slopes change speed and cost"),
        ("topography_speed_gain", "Speed gained per unit of downhill slope, lost uphill"),
        ("topography_energy_penalty", "Drain per unit of uphill slope, when enabled"),
    ]),
    ("Moving and paying", "moving-title", "04.2", [
        ("metabolism_drain", "Basal drain each tick"),
        ("movement_drain", "Drain per unit of wheel effort"),
        ("metabolism_boost_penalty", "Extra drain on each boosted tick"),
        ("metabolism_ramp_floor", "Reserve above which the ramp applies"),
        ("metabolism_ramp_rate", "Extra drain per unit of reserve above the floor"),
        ("temperature_discomfort_rate", "Health drain from temperature discomfort"),
        ("temperature_comfort_band", "Temperature difference felt as comfortable"),
        ("temperature_gradient_exponent", "Shape of the temperature gradient across the map"),
        ("temperature_discomfort_exponent", "Power applied to discomfort beyond the band"),
        ("aging_tick_interval", "Ticks between age increments"),
        ("aging_health_decay_start", "Age at which old-age health decay starts"),
        ("aging_health_decay_rate", "Old-age health decay per tick beyond that age"),
        ("aging_health_decay_max", "Cap on old-age health decay per tick"),
        ("aging_energy_penalty_rate", "Extra energy drain per unit of old-age decay"),
    ]),
    ("Grazing and giving", "grazing-title", "04.3", [
        ("food_intake_rate", "Most food eaten in a tick"),
        ("food_waste_rate", "Food a grazer removes from its cell each tick"),
        ("food_requires_stillness", "Graze only when nearly still"),
        ("stillness_speed_threshold", "Speed counted as still, when required"),
        ("food_transfer_rate", "Most energy given to each neighbor in a tick"),
        ("food_sharing_rate", "Most of the giver’s reserve given to each neighbor"),
        ("food_sharing_distance", "How close a neighbor must be to receive"),
        ("food_sharing_radius", "Upper bound on that distance"),
    ]),
    ("Spikes and meat", "meat-title", "04.4", [
        ("carnivore_threshold", "Diet below which a spike does damage"),
        ("spike_radius", "Hit reach beyond the spike’s length"),
        ("spike_alignment_cosine", "Cosine of the widest hit angle off the spike’s line"),
        ("spike_damage", "Base damage of a hit"),
        ("spike_length_damage_bonus", "Extra damage per unit of spike length"),
        ("spike_speed_damage_bonus", "Extra damage per unit of the faster wheel"),
        ("spike_min_length", "Second minimum length for a hit, after the fixed 0.5"),
        ("spike_growth_rate", "How far the spike moves toward its target each tick"),
        ("spike_energy_cost", "Energy per tick per unit of spike output, when extended"),
        ("carcass_distribution_radius", "Reach of a kill’s meat"),
        ("carcass_health_reward", "Meat shared out, before weighting"),
        ("carcass_energy_share_rate", "Energy gained per unit of meat"),
        ("carcass_reproduction_reward", "Progress shared out, before weighting"),
        ("carcass_maturity_age", "Victim age, in units, that leaves full meat"),
        ("carcass_neighbor_exponent", "Power of the number sharing that divides each share"),
    ]),
    ("Breeding", "breeding-title", "04.5", [
        ("reproduction_cooldown", "Progress a child costs"),
        ("reproduction_rate_herbivore", "Progress from time each tick, for a pure grazer"),
        ("reproduction_rate_carnivore", "Progress from time each tick, for a pure hunter"),
        ("reproduction_food_bonus", "Progress per unit of food eaten"),
        ("reproduction_fertility_bonus", "Extra progress on fertile cells (b in 04.3)"),
        ("reproduction_energy_threshold", "Reserve needed to breed"),
        ("reproduction_energy_cost", "Reserve the parent pays per child"),
        ("reproduction_child_energy", "Child’s starting reserve"),
        ("reproduction_attempt_interval", "Ticks between breeding attempts"),
        ("reproduction_attempt_chance", "Chance an attempt succeeds"),
        ("reproduction_partner_chance", "Chance of a second parent"),
        ("reproduction_mutation_scale", "Body-trait step as a share of the inherited rate"),
        ("reproduction_meta_mutation_chance", "Chance the mutation rates themselves mutate"),
        ("reproduction_meta_mutation_scale", "Size of that change"),
        ("reproduction_color_jitter", "Color change per channel at birth"),
        ("reproduction_spawn_back_distance", "How far behind the parent a child appears"),
        ("reproduction_spawn_jitter", "Random scatter of that position"),
    ]),
    ("Population", "worlds-title", "04.1", [
        ("population_minimum", "Floor kept by arrivals"),
        ("population_spawn_interval", "Ticks between scheduled arrivals"),
        ("population_spawn_count", "Creatures per scheduled arrival"),
        ("population_crossover_chance", "Share of arrivals bred from two living creatures"),
    ]),
    ("The food field", "field-rules-title", "04.6", [
        ("food_cell_size", "Side of one food cell"),
        ("initial_food", "Food in every cell at tick 0"),
        ("food_max", "Food a cell can hold before fertility"),
        ("food_growth_rate", "Regrowth rate (g in 04.6)"),
        ("food_decay_rate", "Decay rate (d in 04.6)"),
        ("food_diffusion_rate", "Share moved toward the neighbors’ mean each tick"),
        ("food_respawn_interval", "Ticks between random refills"),
        ("food_respawn_amount", "Food added to the refilled cell"),
        ("food_fertility_base", "Fertility before terrain"),
        ("food_moisture_weight", "Fertility per unit of moisture"),
        ("food_elevation_weight", "Fertility lost per unit of elevation"),
        ("food_slope_weight", "Fertility lost per unit of slope"),
        ("food_capacity_base", "Capacity share at fertility 0"),
        ("food_capacity_fertility", "Capacity share added at fertility 1"),
        ("food_growth_fertility", "How much fertility speeds regrowth"),
        ("food_decay_infertility", "How much infertility speeds decay"),
    ]),
]
WORLDS = [("evolution_meadow_v1", "Evolution"), ("meadow", "Timed"), ("food_funded_meadow_v1", "Food-funded")]


def setting(value):
    """A setting as its scenario file would write it. f32 values arrive widened to f64, so print the
    shortest decimal that names the same f32."""
    if isinstance(value, bool):
        return "true" if value else "false"
    if isinstance(value, str):
        return value
    if isinstance(value, int) or float(value).is_integer():
        return str(int(value))
    target = struct.unpack("<f", struct.pack("<f", value))[0]
    for digits in range(1, 10):
        text = f"{value:.{digits}g}"
        if struct.unpack("<f", struct.pack("<f", float(text)))[0] == target:
            return text
    return repr(value)


def parameters(defaults, scenarios):
    """The homepage's parameter reference: every listed setting's Rust default, read from the
    packaged Wasm, and what each browser scenario changes. Fails the build if a listed setting
    disappears or a browser scenario changes a setting the table does not list."""
    listed = [key for _, _, _, rows in PARAMETER_GROUPS for key, _ in rows]
    missing = [key for key in listed if key not in defaults]
    if missing or len(set(listed)) != len(listed):
        raise ValueError(f"parameter table lists unknown or repeated settings: {missing}")
    for world, _ in WORLDS:
        unlisted = sorted(set(scenarios[world]) - set(listed))
        if unlisted:
            raise ValueError(f"{world} changes settings the parameter table omits: {unlisted}")
    head = "".join(f'<th scope="col">{esc(h)}</th>' for h in ("Setting", "Meaning", "Default", *(n for _, n in WORLDS)))
    groups = []
    for title, anchor, number, rows in PARAMETER_GROUPS:
        body = [f'<tr class="group"><th scope="colgroup" colspan="6">{esc(title)} · <a href="#{anchor}">{number}</a></th></tr>']
        for key, meaning in rows:
            default = setting(defaults[key])
            cells = [f'<td class="v" data-label="Default">{esc(default)}</td>']
            for world, name in WORLDS:
                if key in scenarios[world] and setting(scenarios[world][key]) != default:
                    cells.append(f'<td class="v set" data-label="{esc(name)}">{esc(setting(scenarios[world][key]))}</td>')
                else:
                    cells.append(f'<td class="v same" data-label="{esc(name)}"><span aria-hidden="true">·</span>'
                                 f'<span class="sr-only">default</span></td>')
            body.append(f'<tr><th scope="row"><code>{esc(key)}</code></th><td class="m">{esc(meaning)}</td>{"".join(cells)}</tr>')
        groups.append("<tbody>" + "".join(body) + "</tbody>")
    return (f'<details class="params-wrap"><summary>Show all {len(listed)} settings</summary>'
            f'<div class="table-scroll"><table class="params"><thead><tr>{head}</tr></thead>{"".join(groups)}</table></div>'
            f'</details>\n')


# The workspace map (07.4). Roles are written by hand; dependencies and sizes are read from the
# checkout at build time, and the build fails if a crate is added or removed without a role here.
CRATE_TIERS = [
    ("Programs and views", [
        ("scriptbots-app", "The desktop program: terminal lab, front-end selection, scenarios and config layers, experiment runner, MCP and REST control servers."),
        ("scriptbots-bevy", "The 3D Bevy view, the iPhone and iPad app, and the exporter that bakes this page’s terrain."),
        ("scriptbots-render", "The GPUI desktop view."),
        ("scriptbots-web", "This page’s simulation: the WebAssembly build, its worker API and frame packets."),
        ("scriptbots-analytics", "sb-analyze: read-only reports over finished run databases."),
    ]),
    ("Host and records", [
        ("scriptbots-runtime", "The renderer-neutral host every front end drives: commands, snapshots, events and the deterministic owner of a world."),
        ("scriptbots-storage", "Run databases on FrankenSQLite."),
        ("scriptbots-world-gfx", "Offscreen wgpu rendering of the world, with framebuffer readback."),
    ]),
    ("Brains", [
        ("scriptbots-brain", "The brain interface and the MLP, DWRAON and Assembly families."),
        ("scriptbots-brain-neuro", "NeuroFlow, a feed-forward family, behind a feature."),
        ("scriptbots-brain-ml", "Candle evaluation and the Frankentorch FtBrain family, behind features."),
    ]),
    ("Simulation", [
        ("scriptbots-core", "The world: settings, the fifteen-stage tick, bodies, food, combat, birth, ancestry, checkpoints and replay."),
        ("scriptbots-index", "The spatial index behind every neighbor query."),
    ]),
]


def crate_map(root):
    """Cards for every workspace crate: its role, its size in lines of Rust under src/, and the
    workspace crates it depends on (dev-dependencies excluded)."""
    members = [pathlib.Path(m).name for m in tomllib.loads((root / "Cargo.toml").read_text())["workspace"]["members"]]
    described = [name for _, crates in CRATE_TIERS for name, _ in crates]
    if sorted(members) != sorted(described):
        raise ValueError(f"crate map out of date: workspace {sorted(members)} vs map {sorted(described)}")
    tiers = []
    total = 0
    for title, crates in CRATE_TIERS:
        cards = []
        for name, role in crates:
            manifest = tomllib.loads((root / "crates" / name / "Cargo.toml").read_text())
            tables = [manifest.get("dependencies", {})]
            tables += [target.get("dependencies", {}) for target in manifest.get("target", {}).values()]
            uses = sorted({dep.removeprefix("scriptbots-") for table in tables for dep in table if dep.startswith("scriptbots-")})
            lines = sum(path.read_bytes().count(b"\n") for path in (root / "crates" / name / "src").rglob("*.rs"))
            total += lines
            meta = f"{lines:,} lines of Rust" + (f" · uses {', '.join(uses)}" if uses else " · no workspace dependencies")
            cards.append(f'<li><code>{esc(name)}</code><p>{esc(role)}</p><small>{esc(meta)}</small></li>')
        tiers.append(f'<div class="tier"><h4>{esc(title)}</h4><ul class="crates">{"".join(cards)}</ul></div>')
    return (f'<div class="tiers">{"".join(tiers)}</div>\n'
            f'<p class="tiers-total">{total:,} lines of Rust across {len(members)} crates in this release.</p>\n')


if __name__ == "__main__":
    out = pathlib.Path(sys.argv[2])
    out.mkdir(parents=True, exist_ok=True)
    figures = render(pathlib.Path(sys.argv[1]))
    for name, fragment in figures.items():
        (out / f"{name}.html").write_text(fragment)
    print("wrote", ", ".join(sorted(figures)))
