#!/usr/bin/env python3
"""Fill the pilot's figures into the result slots of the inscribed text. Slots stand in table rows (protected),
and every value written is letter-free, so the fill moves no carrier choice; the build checks that detection
is unchanged by it."""
import json, pathlib, re, sys
HERE = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parents[1] / "tools/chx")); import chx
P = "orcid:0009-0000-1599-0703,axn:AXN:02B2,protocol:SPXI-TLP,version:3.0"
R = json.loads((HERE / "pilot.json").read_text())
E = json.loads((HERE / "spxi-tlp-v3.0.evidence.json").read_text())
names = json.loads((HERE / "slots.json").read_text())
insc = (HERE / "spxi-tlp-v3.0.inscribed.md").read_text(encoding="utf-8")

def p(x):
    if x >= 1e-4: return f"{x:.4f}"
    m, e = f"{x:.1e}".split("e"); return f"{m} × 10^{int(e)}"
def f2(x): return f"{x:.2f}".replace("-", "−")
b, a, s = E["detect_before"], E["detect_after"], R["survive"]
order = ["strip_markup", "lowercase", "drop_half_sentences", "shuffle_paragraphs", "first_quarter_only", "trafilatura_extract"]
ft = R["ft_insc"]
def pr(k): q = R[k]; return f"{f2(q['keyed_delta_mean'])}, {f2(q['keyed_delta_t'])}, {q['keyed_contexts']}"
V = {"OCC": a["occurrences"], "KEYED0": b["keyed"], "EXP0": f"{b['expected']:.1f}", "Z0": f2(b["z"]),
     "SUB": E["substituted"], "REF": E["refused"], "KEYED1": a["keyed"], "Z1": f2(a["z"]), "P1": p(a["p_one_sided"]),
     "KL": f"{E['kl_estimate_mean_nll_rise_per_token']:.5f}",
     "SURV": " / ".join(f2(s[k]["z"]) for k in order), "ZWRONG": f2(R["detect_wrong_payload"]["z"]),
     "FT": f"{ft['tokens']}, {ft['epochs']}; {ft['loss_first']:.2f} → {ft['loss_last_epoch_mean']:.2f} / {R['ft_orig']['loss_first']:.2f} → {R['ft_orig']['loss_last_epoch_mean']:.2f}",
     "PT": pr("probe_true"), "PW": pr("probe_wrong"), "PH": pr("probe_held"),
     "CD": f2(R["canary_vs_base"]["canary_delta_sum"])}
for k, (x, y) in R["opmpt"].items():
    V[k + "0"], V[k + "1"] = x, y
for k, v in V.items(): assert not re.search(r"[A-Za-z]", str(v)), (k, v)
out = insc
for i, n in enumerate(names, 1):
    out = out.replace(f"⟦{i}⟧", str(V[n]))
assert "⟦" not in out
z0, z1 = chx.zscore(insc, P), chx.zscore(out, P)
assert (z0["occurrences"], z0["keyed"]) == (z1["occurrences"], z1["keyed"]), (z0, z1)
(HERE / "SPXI-TLP-v3.0.md").write_text(out, encoding="utf-8")
print("written; detection unchanged by the fill:", z1)
