"""Append the five Millennium Lab round 5 moves' receipts to the existing lab ledger.

Opens data/lab.db WITHOUT deleting it and appends 5 receipts (rcpt_0054-0058),
reopens and verifies, appends the VERIFICATION receipt (rcpt_0059), reopens,
verifies final, regenerates data/receipts.json. Same SovereignStore format as
compute/receipts_append_r3r4.py; the lab ledger is a separate store from the
runtime's own.

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"
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 sha256_file(p):
    return hashlib.sha256(Path(p).read_bytes()).hexdigest()


def main():
    store = SovereignStore(str(DATA / "lab.db"))

    ym5 = load("yang_mills_r5.json")
    r = store.append_receipt(
        node_id="millennium-lab/yang-mills",
        kind="COMPUTATION",
        detail="Round 5: fifth beta point, 8^4 SU(2) Wilson lattice beta 2.6, plaquette 0.670483, sigma a^2 0.1847, torelon 1.608 plus/minus 0.161, GEVP 0++ 1.332 plus/minus 0.099; five-point torelon extrapolation intercept 2.423 plus/minus 0.739, chi2/dof 7.60/3, weaker than the four-point fit, supports nothing firm; variational gap over sqrt(sigma) 3.099, flat across 2.3/2.4/2.6",
        payload=ym5,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... yang-mills round 5")

    ns5 = load("navier_stokes_hunt_r5.json")
    r = store.append_receipt(
        node_id="millennium-lab/navier-stokes",
        kind="COMPUTATION",
        detail="Round 5: lower viscosity nu 0.00025, 64^3, dt 0.01, T=10, stability probe passed (28.77 s, no cost explosion); Kida-Pelz enstrophy growth 64.46, peak 72.52 at t=8.9, max vorticity growth 17.04; Taylor-Green enstrophy growth 62.69, peak 23.51 at t=9.9, max vorticity growth 13.68; both stayed smooth, growth monotone with decreasing viscosity, transient not runaway",
        payload=ns5,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... navier-stokes round 5")

    pnp5 = load("p_vs_np_r5.json")
    r = store.append_receipt(
        node_id="millennium-lab/p-vs-np",
        kind="AUDIT",
        detail="Round 5: wider fragment, arbitrary defeater-free LogicNode trees over all 15 LOGIC_OPS; greedy extends to 5 of 6 non-composer ops by exact reduction (0 non-CF violations), extended brute force 44 of 44 agreement; CONTRADICTION_FREE is the exception, zero-arg node SATISFIED on every timeline, makes existence trivially always YES; no triple validates where singles and pairs fail (0 rescues in 1066 combos); ingredient-deleting defeaters and counting/optimization closed as not a mechanism / ill-posed; no separation or collapse claimed",
        payload=pnp5,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... p-vs-np round 5")

    hodge5 = load("hodge_r5.json")
    r = store.append_receipt(
        node_id="millennium-lab/hodge",
        kind="FORMALIZATION",
        detail="Round 5: Lean 4.13.0 + mathlib v4.13.0, sheaf long exact sequence WITH c1 for the actual exponential sequence, Hodge/LongExactSequence.lean, 18 theorems, 0 sorries, no sorryAx; expSeq_shortExact (0 -> Z -> O_X -> O_X^* -> 0 as sheaves), c1 exact at both joints and surjecting onto the kernel, Lefschetz (1,1) now conditional only on the Dolbeault isomorphism and the Hodge decomposition; full Dolbeault isomorphism still blocked, no differential forms in mathlib v4.13.0",
        payload=hodge5,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... hodge round 5")

    bsd = load("bsd_curves_r5.json")
    riemann = load("riemann_zeros_r5.json")
    calib_payload = {
        "round": 5,
        "bsd": {
            "curves_count": bsd["curves_count"],
            "rank_split": bsd["rank_split"],
            "rank_1_curves": bsd["rank_1_curves"],
            "all_L_nonzero": bsd["all_L_nonzero"],
            "note": "L column for rank-1 curves holds L'(E,1), the leading Taylor coefficient, not L(E,1) which vanishes at rank 1.",
            "file_sha256": sha256_file(DATA / "bsd_curves_r5.json"),
        },
        "riemann": {
            "zeros_checked": riemann["zeros_checked"],
            "max_re_deviation": riemann["max_re_deviation"],
            "S_of_T": riemann["S_of_T"],
            "first_3000_match_round4": riemann["first_3000_match_round4"],
            "file_sha256": sha256_file(DATA / "riemann_zeros_r5.json"),
        },
        "note": "Full zero and curve tables live in data/riemann_zeros_r5.json and data/bsd_curves_r5.json; this payload carries counts, hashes, and headline numbers only. BSD and Riemann scans were each run twice with identical hashes.",
    }
    r = store.append_receipt(
        node_id="millennium-lab/calibration",
        kind="COMPUTATION",
        detail="Round 5 calibration: BSD conductor to 50, 130 curves, 128 rank 0 and 2 rank 1 (37a1 and new 43a1), all rank-0 L(E,1) nonzero; Riemann first 4000 zeros re-verified on the line, max deviation 0.0, first 3000 match round 4 exactly; run twice, identical hashes",
        payload=calib_payload,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... calibration round 5")
    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 5",
        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()
