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

Opens data/lab.db WITHOUT deleting it and appends 5 receipts (rcpt_0038-0042),
reopens and verifies, appends the VERIFICATION receipt (rcpt_0043), reopens,
verifies final, regenerates data/receipts.json. Same SovereignStore format as
compute/receipts.py and compute/receipts_append.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"))

    ns = load("navier_stokes_hunt_r2.json")
    r = store.append_receipt(
        node_id="millennium-lab/navier-stokes",
        kind="COMPUTATION",
        detail="Round 2: Kida-Pelz 64^3 enstrophy growth 18.86, max vorticity growth 11.51, stayed smooth, 1516.7 s; high-amplitude anti-parallel tubes 48^3 growth 1.02, stayed smooth; no blowup observed",
        payload=ns,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... navier-stokes round 2")

    pnp = load("p_vs_np_r2.json")
    r = store.append_receipt(
        node_id="millennium-lab/p-vs-np",
        kind="AUDIT",
        detail="Round 2: defeater-free fragment DF-COMP admits explicit polynomial-time greedy search, at most 2599 candidates, 0.10-0.58 s per run, 44 of 44 brute-force agreement; 3-SAT hardness direction stalls structurally; no separation or collapse claimed",
        payload=pnp,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... p-vs-np round 2")

    ym = load("yang_mills_r2.json")
    r = store.append_receipt(
        node_id="millennium-lab/yang-mills",
        kind="COMPUTATION",
        detail="Round 2: 8^4 SU(2) Wilson lattice beta 2.3, plaquette 0.602788, sigma a^2 0.3166, torelon gap 1.8602; three-point continuum extrapolation intercept 3.473 plus/minus 1.506, slope unconstrained; 10^4 volume check consistent",
        payload=ym,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... yang-mills round 2")

    hodge = load("hodge_r2.json")
    r = store.append_receipt(
        node_id="millennium-lab/hodge",
        kind="FORMALIZATION",
        detail="Round 2: Lean 4.13.0 + mathlib v4.13.0, exponential sequence 0 to Z to C to C* to 1 proved exact at every term, 9 new theorems, 0 sorries, no sorryAx; sheaf-level sequence still blocked, unconditional (1,1) still conditional",
        payload=hodge,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... hodge round 2")

    bsd = load("bsd_curves_r2.json")
    riemann = load("riemann_zeros_r2.json")
    calib_payload = {
        "round": 2,
        "bsd": {
            "curves_count": bsd["curves_count"],
            "rank_split": {"rank_0": sum(1 for c in bsd["curves"] if c["rank"] == 0)},
            "all_L_nonzero": all(float(c["L_value"]) != 0 for c in bsd["curves"]),
            "file_sha256": sha256_file(DATA / "bsd_curves_r2.json"),
        },
        "riemann": {
            "zeros_checked": riemann["zeros_checked"],
            "max_re_deviation": riemann["max_re_deviation"],
            "S_of_T": riemann["S_of_T"],
            "file_sha256": sha256_file(DATA / "riemann_zeros_r2.json"),
        },
        "note": "Full zero and curve tables live in data/riemann_zeros_r2.json and data/bsd_curves_r2.json; this payload carries counts, hashes, and headline numbers only.",
    }
    r = store.append_receipt(
        node_id="millennium-lab/calibration",
        kind="COMPUTATION",
        detail="Round 2 calibration: BSD conductor to 30, 57 curves, all rank 0, all L(E,1) nonzero; Riemann first 2000 zeros re-verified on the line, max deviation 0.0; no pattern breaks",
        payload=calib_payload,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... calibration round 2")
    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 2",
        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()
