"""Compile the measured crossings into the compact deck the Crossing Desk embeds.

Each card: what the player can see before the crossing (readout, gauge), what a real
house rule says, and what the oracle measured afterwards (holds, harm, undeclared shift).
"""
import hashlib
import json
import math
from pathlib import Path

audio = json.loads(Path("audio_crossings.json").read_text())
numeric = json.loads(Path("numeric_crossings.json").read_text())
clamp = lambda x: max(0, min(100, round(x)))
cards = []
FF = audio["meta"]["ffmpeg"].split(" Copyright")[0].replace("ffmpeg version ", "ffmpeg ")

# Where each stand-in stops resembling what it stands for. Written per input, so every card says it.
SIGNAL_STOPS = {
    "Sine 997 Hz": "A single steady tone has none of the transients or dense spectrum of real music, so it is the easiest case for a codec.",
    "Bright sawtooth": "Two fixed sawtooth waves are harmonically rich but static; real mixes change from moment to moment.",
    "Pink noise": "Steady pink noise matches a music-like spectrum on average but has no rhythm, silence or structure.",
    "Drum transients": "Synthetic decaying bursts at a fixed tempo stand in for drums; real kits have room sound and varied hits.",
    "Chord pad": "Four sustained sine partials stand in for a pad; real instruments carry noise, vibrato and envelopes.",
    "Bass and hats": "A two-partial bass and noise-burst hats stand in for a groove; real low end and cymbals are far more complex.",
}
CODEC_STOPS = "One bitrate setting stands in for the {fam} family, and other encoder libraries or versions may overshoot differently."
FORMAT_STOPS = {
    "float16": "One value is converted once; real float16 use moves whole tensors through many operations, where error accumulates.",
    "bfloat16": "Rounding here is round-to-nearest-even done by hand; hardware and libraries may round or flush subnormals differently.",
    "float32": "One conversion of one value; real pipelines repeat conversions and do arithmetic between them.",
    "JSON float64": "Python's JSON encoder and parser round-trip float64 exactly; other languages' encoders or parsers may not.",
    "Text %.6g": "One fixed format string; real systems print with whatever precision their logging or export code happens to use.",
    "int8 over [-1,1]": "The range [-1, 1] is declared in advance; real quantisers calibrate a scale per tensor, so values outside it behave differently.",
}


def audio_label(r):
    fam = r["codec"].split()[0]
    return {
        "is": f"The measured change in true peak when one synthetic master ({r['signal']}, {r['sample_peak_dbfs']:+.1f} dBFS sample peak) "
              f"goes through {r['codec']} on {FF}, graded by the BS.1770 true-peak meter in ffmpeg's EBU R128 scanner.",
        "isnt": "A test of real music, of any other encoder build or setting, of loudness compliance for a platform, or of how it sounds.",
        "stops": SIGNAL_STOPS[r["signal"]] + " " + CODEC_STOPS.format(fam=fam),
        "harm": "Harm is overshoot in dB times 1.5, with a 0.3 floor. That scale is the game's choice, not a measured cost.",
    }


def numeric_label(r):
    return {
        "is": f"The exact relative error after one round trip of {r['value']} through {r['format']}, "
              f"checked against a tolerance of {r['tolerance']:g} with exact rational arithmetic.",
        "isnt": "A test of arithmetic done after decoding, of error building up over many steps, or of any value other than this one.",
        "stops": FORMAT_STOPS[r["format"]] + " The tolerance is a chosen example, not a requirement from any real system.",
        "harm": "Harm is one plus the log of error over tolerance, capped at 6, and 6 for overflow. That scale is the game's choice.",
    }

for r in audio["records"]:
    pre, lim = r["pre_true_peak_dbtp"], r["limit_dbtp"]
    shift = round(r["post_lufs"] - r["pre_lufs"], 1)
    cards.append({
        "id": r["id"], "track": "Audio master",
        "claim": f"{r['signal']} master through {r['codec']}: true peak stays at or below −1.0 dBTP",
        "read": f"{pre:+.1f}", "unit": "dBTP before encode",
        "gauge": clamp(50 + (lim - pre) * 20),
        "rule": pre <= lim, "holds": r["holds"],
        "harm": round(max(0.2, r["overshoot_db"]) * 1.5, 2),
        "result": f"{r['post_true_peak_dbtp']:+.1f} dBTP after encode",
        "undeclared": f"Integrated loudness moved {shift:+.1f} LU" if abs(shift) >= 0.5 else None,
        "label": audio_label(r),
    })

for r in numeric["records"]:
    eps, tol = r["nominal_precision"], r["tolerance"]
    err = r["relative_error"]
    harm = 6.0 if err == "inf" else (0.2 if r["holds"] else min(6.0, math.log10(err / tol) + 1))
    cards.append({
        "id": r["id"], "track": "Numeric transport",
        "claim": f"{r['value']} through {r['format']}: relative error within {tol:g}",
        "read": f"{eps / tol:.2g}×", "unit": "format precision ÷ tolerance",
        "gauge": clamp(50 + 12 * math.log10(tol / eps)),
        "rule": r["contract_says_safe"], "holds": r["holds"], "harm": round(harm, 2),
        "result": "overflowed to infinity" if err == "inf" else f"relative error {err:.2g}",
        "undeclared": None,
        "label": numeric_label(r),
    })

deck = {
    "measured": "2026-10-21",
    "audio_oracle": audio["meta"]["oracle"], "ffmpeg": audio["meta"]["ffmpeg"],
    "numeric_oracle": numeric["meta"]["oracle"],
    "sources_sha256": {p: hashlib.sha256(Path(p).read_bytes()).hexdigest()
                       for p in ["audio_crossings.json", "numeric_crossings.json"]},
    "cards": cards,
}
Path("deck.json").write_text(json.dumps(deck, separators=(",", ":"), ensure_ascii=False))
print(len(cards), "cards,", Path("deck.json").stat().st_size, "bytes")
