"""Append the Millennium Lab round 7 receipts to the existing lab ledger.

Opens data/lab.db WITHOUT deleting it and appends 3 computation receipts
(NS round 7, YM round 7, field renders for rounds 5-7, rcpt_0063-0065),
reopens and verifies, appends the VERIFICATION receipt (rcpt_0066),
reopens, verifies final, regenerates data/receipts.json. Same
SovereignStore format as compute/receipts_append_r6.py.

NEVER run compute/receipts.py on this ledger: it deletes the ledger
and rebuilds runs 1-2 only.
"""
import hashlib
import json
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
LAB = HERE.parent
DATA = LAB / "data"
POSTER = LAB / "poster"
sys.path.insert(0, str(Path.home() / "workspace" / "sovereign-runtime"))

from sovereign_runtime.store import SovereignStore  # noqa: E402


def load(name):
    return json.loads((DATA / name).read_text())


def load_poster(name):
    return json.loads((POSTER / name).read_text())


def sha256_file(p):
    return hashlib.sha256(Path(p).read_bytes()).hexdigest()


def main():
    store = SovereignStore(str(DATA / "lab.db"))
    already = store.receipt_count()
    # Resume-safe: a partial run may have appended the NS and YM receipts
    # before failing on the renders receipt. Append only what is missing.
    do_ns_ym = already == 62

    if do_ns_ym:
        ns7 = load("navier_stokes_hunt_r7.json")
        r = store.append_receipt(
            node_id="millennium-lab/navier-stokes",
            kind="COMPUTATION",
            detail="Round 7: full 96^3 Navier-Stokes at nu 0.000125, dt 0.01, t = 10, on the round 4 real-FFT solver; snapshot loop validated bit-identical to the round 4 solver at 32^3 (all result fields identical); Kida-Pelz 96^3 enstrophy growth 145.79 (peak 164.02 at t = 8.2, initial 1.125, final 132.99), max vorticity growth 28.10 (peak 84.30), energy 0.375 to 0.206, wall 1357.8 s; Taylor-Green 96^3 enstrophy growth 138.27 (peak 51.85 at t = 9.8, final 51.48), max vorticity growth 24.81 (peak 49.63), energy 0.125 to 0.088, wall 1351.7 s; growth rises with resolution at fixed viscosity: Kida-Pelz 88.24 at 64^3 to 145.79 at 96^3 (ratio 1.65), Taylor-Green 87.56 to 138.27 (ratio 1.58), no saturation; Taylor-Green 64^3 to T = 20 enstrophy growth 88.56 (peak 33.21 at t = 11.0, final 14.94), max vorticity growth 19.14, wall 617.3 s, so Taylor-Green is transient too, it just peaks later than Kida-Pelz; 96^3 cost probe 1.734 s/step, peak RSS 390.4 MB, full 1000-step run about 0.38 h, matching the measured walls; dual run of the strongest case (Kida-Pelz 96^3) identical hashes; all cases stayed smooth, no blowup",
            payload=ns7,
        )
        print(f"{r.receipt_id} {r.receipt_hash[:16]}... navier-stokes round 7")

        ym7 = load("yang_mills_r7.json")
        r = store.append_receipt(
            node_id="millennium-lab/yang-mills",
            kind="COMPUTATION",
            detail="Round 7: third seed (base 20261122) at beta 2.5 and 2.6, 8^4 SU(2), same setup as rounds 5-6, runtime 631.0 s; seed 3 torelon lands between seeds 1 and 2 at both betas (2.5: 1.080 plus/minus 0.068 vs seed 1 1.280 plus/minus 0.082 and seed 2 0.890 plus/minus 0.044, no pair agrees within combined errors; 2.6: 1.268 plus/minus 0.052 vs 1.608 plus/minus 0.161 and 1.193 plus/minus 0.106, only seed 2 vs seed 3 agree); GEVP 0++ seed 3 is 1.356 plus/minus 0.103 at 2.5 (seed 2 1.626, no seed 1) and 1.659 plus/minus 0.160 at 2.6 (seed 1 1.332 plus/minus 0.099, seed 2 1.603 plus/minus 0.134); estimator test at both betas: within a single chain the torelon effective mass moves more across tau (2.395 at 2.5, 2.100 at 2.6) than it moves across chains at fixed tau (0.390, 0.415), so the correlator has no stable plateau and the plateau choice moves the mass far more than the chain does, while the chains still disagree at fixed tau beyond combined errors; the three-seed inverse-variance mean series fit gives intercept 2.120 plus/minus 0.526, chi2/dof 55.35/3; OVERTURNED STANDS: the five-point linear extrapolation still cannot support any continuum claim",
            payload=ym7,
        )
        print(f"{r.receipt_id} {r.receipt_hash[:16]}... yang-mills round 7")
    else:
        print(f"NS and YM receipts already present (count {already}), skipping")

    meta5 = load_poster("render_meta_r5.json")
    meta6 = load_poster("render_meta_r6.json")
    meta7 = load_poster("render_meta_r7.json")
    png5 = POSTER / "millennium-field-render-r5.png"
    png6 = POSTER / "millennium-field-render-r6.png"
    png7 = POSTER / "millennium-field-render-r7.png"
    render_payload = {
        "round5": {"meta": meta5, "png": png5.name, "png_bytes": png5.stat().st_size,
                   "png_sha256": sha256_file(png5)},
        "round6": {"meta": meta6, "png": png6.name, "png_bytes": png6.stat().st_size,
                   "png_sha256": sha256_file(png6)},
        "round7": {"meta": meta7, "png": png7.name, "png_bytes": png7.stat().st_size,
                   "png_sha256": sha256_file(png7)},
    }
    r = store.append_receipt(
        node_id="millennium-lab/poster",
        kind="COMPUTATION",
        detail=(
            "Field renders for rounds 5, 6 and 7, 1080x1350, computed from the lab's own solvers, "
            "same pattern as rounds 1-4. Round 5: Kida-Pelz 64^3 nu 0.00025 enstrophy growth "
            f"{meta5['kida_pelz']['enstrophy_growth']:.2f} (peak t = {meta5['kida_pelz']['peak_time']:.1f}), "
            f"Yang-Mills weave beta 2.6 plaquette {meta5['yang_mills']['plain_mean']:.6f}, "
            f"PNG {png5.name} {png5.stat().st_size} bytes sha256 {sha256_file(png5)[:16]}.... "
            "Round 6: Kida-Pelz 64^3 nu 0.000125 enstrophy growth "
            f"{meta6['kida_pelz']['enstrophy_growth']:.2f} (peak t = {meta6['kida_pelz']['peak_time']:.1f}), "
            f"Yang-Mills weave beta 2.5 plaquette {meta6['yang_mills']['plain_mean']:.6f}, "
            f"PNG {png6.name} {png6.stat().st_size} bytes sha256 {sha256_file(png6)[:16]}.... "
            "Round 7: Kida-Pelz 96^3 nu 0.000125 enstrophy growth "
            f"{meta7['kida_pelz']['enstrophy_growth']:.2f} (peak t = {meta7['kida_pelz']['peak_time']:.1f}), "
            f"Yang-Mills weave beta 2.6 plaquette {meta7['yang_mills']['plain_mean']:.6f}, "
            f"PNG {png7.name} {png7.stat().st_size} bytes sha256 {sha256_file(png7)[:16]}...."
        ),
        payload=render_payload,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... field renders rounds 5-7")
    store.close()

    store2 = SovereignStore(str(DATA / "lab.db"))
    verdict = store2.verify_chain()
    print("reopen verify:", verdict)
    assert verdict["valid"], "chain broken after reopen"
    head_before = store2.last_receipt_hash()
    rv = store2.append_receipt(
        node_id="millennium-lab",
        kind="VERIFICATION",
        detail="Receipt chain verified after store reopen (restart proof), round 7",
        payload={
            "checked": verdict["checked"],
            "chain_valid": verdict["valid"],
            "head_hash_before_this_receipt": head_before,
        },
    )
    store2.close()

    store3 = SovereignStore(str(DATA / "lab.db"))
    final = store3.verify_chain()
    head = store3.last_receipt_hash()
    count = store3.receipt_count()
    receipts = [
        {"receipt_id": r.receipt_id, "timestamp": r.timestamp, "node_id": r.node_id,
         "kind": r.kind, "detail": r.detail, "prev_hash": r.prev_hash,
         "receipt_hash": r.receipt_hash}
        for r in store3.list_receipts(limit=500)
    ]
    store3.close()
    summary = {
        "ledger": str(DATA / "lab.db"),
        "receipt_format": "sovereign-runtime SovereignStore, canonical JSON, SHA-256, GENESIS head",
        "receipt_count": count,
        "chain_valid": final["valid"],
        "head_hash": head,
        "verification_receipt": rv.receipt_id,
        "receipts": receipts,
    }
    (DATA / "receipts.json").write_text(json.dumps(summary, indent=2))
    print(f"receipts: {count}, chain valid: {final['valid']}, head: {head}")
    print("summary:", DATA / "receipts.json")


if __name__ == "__main__":
    main()
