"""Append the nine Millennium Lab rounds 3 and 4 moves' receipts to the existing lab ledger.

Opens data/lab.db WITHOUT deleting it and appends 9 receipts (rcpt_0044-0052),
reopens and verifies, appends the VERIFICATION receipt (rcpt_0053), reopens,
verifies final, regenerates data/receipts.json. Same SovereignStore format as
compute/receipts_append_r2.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"))

    # Round 3
    ym3 = load("yang_mills_r3.json")
    r = store.append_receipt(
        node_id="millennium-lab/yang-mills",
        kind="COMPUTATION",
        detail="Round 3: 8^4 SU(2) Wilson lattice beta 2.5, plaquette 0.653125, sigma a^2 0.20710, torelon gap 1.280 plus/minus 0.082; 12^4 volume control at beta 2.3 shows no finite-volume shift; four-point torelon extrapolation intercept 1.634 plus/minus 0.820, slope flipped vs three-point, supports nothing firm",
        payload=ym3,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... yang-mills round 3")

    ns3 = load("navier_stokes_hunt_r3.json")
    r = store.append_receipt(
        node_id="millennium-lab/navier-stokes",
        kind="COMPUTATION",
        detail="Round 3: 96^3 REJECTED on measured timing (10-step probe 17.323 s/step, peak RSS 660.7 MB, extrapolated 4.81 h, probes underestimate by 1.83x); fallback Kida-Pelz 64^3 to t=20, 2000 steps, 4431.3 s, enstrophy peak 21.2164 then decay to 1.6547, stayed smooth, no blowup signal out to t=20",
        payload=ns3,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... navier-stokes round 3")

    pnp3 = load("p_vs_np_r3.json")
    r = store.append_receipt(
        node_id="millennium-lab/p-vs-np",
        kind="AUDIT",
        detail="Round 3: full fragment with defeaters is POLYNOMIAL, not hard; defeater rule makes the decision easier, a SATISFIED node exists on every timeline, greedy builds a valid witness on 14 of 14 timelines, 47 of 47 brute-force agreement; three 3-SAT reduction attempts all failed with failure modes recorded; no separation or collapse claimed",
        payload=pnp3,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... p-vs-np round 3")

    hodge3 = load("hodge_r3.json")
    r = store.append_receipt(
        node_id="millennium-lab/hodge",
        kind="FORMALIZATION",
        detail="Round 3: Lean 4.13.0 + mathlib v4.13.0, sheaf O_X IS tractable, overturning the round 2 assessment; holomorphicSheaf, holomorphicSheafCommRing, holomorphicSheafUnits, holomorphicExpSheafHom, 13 theorems, 0 sorries, no sorryAx; (1,1) case now conditional on the sheaf long exact sequence, not on O_X existing",
        payload=hodge3,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... hodge round 3")

    # Round 4
    ym4 = load("yang_mills_r4.json")
    r = store.append_receipt(
        node_id="millennium-lab/yang-mills",
        kind="COMPUTATION",
        detail="Round 4: APE-smeared variational (GEVP) glueball operators at beta 2.3 and 2.4 on 8^4; GEVP ground state 0++ 1.653 plus/minus 0.183 at 2.3 and 1.504 plus/minus 0.157 at 2.4, plain m_eff(0) was contaminated high by about 1.2; variational gap over sqrt(sigma) 2.937 vs 3.042, 3.5 percent apart vs 8.8 percent plain; agrees with torelon within errors; no continuum limit taken",
        payload=ym4,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... yang-mills round 4")

    ns4 = load("navier_stokes_hunt_r4.json")
    r = store.append_receipt(
        node_id="millennium-lab/navier-stokes",
        kind="COMPUTATION",
        detail="Round 4: nu 0.0005, 64^3, T=10, both cases stayed smooth; Kida-Pelz enstrophy growth 40.33, max vorticity growth 14.65, 2008.9 s; Taylor-Green first time at 64^3, enstrophy growth 36.42, vorticity growth 12.26, 1421.3 s; halving viscosity more than doubled enstrophy growth vs round 2, transient not runaway",
        payload=ns4,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... navier-stokes round 4")

    pnp4 = load("p_vs_np_r4.json")
    proof_sha = sha256_file(DATA / "p_vs_np_greedy_proof_r4.md")
    pnp4_payload = dict(pnp4)
    pnp4_payload["greedy_proof_file_sha256"] = proof_sha
    r = store.append_receipt(
        node_id="millennium-lab/p-vs-np",
        kind="AUDIT",
        detail="Round 4: the p^r phase transition does NOT survive defeaters; plain tracks p^r, defeater tracks (1-p)^r, 50/50 mixed tracks 0.5^r at every density, max deviation 0.065 across 140 cells; no rare regime exists, a SATISFIED composed recipe exists on 1400 of 1400 trials; greedy correctness proof sketch written, DF-COMP-SEARCH decidable in polynomial time by one pass over at most 2599 nodes",
        payload=pnp4_payload,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... p-vs-np round 4")

    hodge4 = load("hodge_r4.json")
    r = store.append_receipt(
        node_id="millennium-lab/hodge",
        kind="FORMALIZATION",
        detail="Round 4: Lean 4.13.0 + mathlib v4.13.0, degree-zero Dolbeault formalized as far as mathlib allows; dbar derivative, kernel of d-bar equals O_X pointwise on C, (1,0)/(0,1) type decomposition of the differential, 14 new theorems plus 9 ChernClass theorems re-verified, 0 sorries, no sorryAx; full Dolbeault isomorphism still blocked, no differential forms on manifolds in mathlib v4.13.0",
        payload=hodge4,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... hodge round 4")

    bsd = load("bsd_curves_r4.json")
    riemann = load("riemann_zeros_r4.json")
    calib_payload = {
        "round": 4,
        "bsd": {
            "curves_count": bsd["curves_count"],
            "rank_split": {
                "rank_0": sum(1 for c in bsd["curves"] if c["rank"] == 0),
                "rank_1": sum(1 for c in bsd["curves"] if c["rank"] == 1),
            },
            "rank_1_curve": "37a1, L'(E,1) = 0.3059997738340523",
            "all_rank_0_L_nonzero": all(float(c["L_value"]) != 0 for c in bsd["curves"] if c["rank"] == 0),
            "file_sha256": sha256_file(DATA / "bsd_curves_r4.json"),
        },
        "riemann": {
            "zeros_checked": riemann["zeros_checked"],
            "max_re_deviation": riemann["max_re_deviation"],
            "S_of_T": riemann["S_of_T"],
            "first_2000_match_round2": riemann["first_2000_match_round2"],
            "file_sha256": sha256_file(DATA / "riemann_zeros_r4.json"),
        },
        "note": "Full zero and curve tables live in data/riemann_zeros_r4.json and data/bsd_curves_r4.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 4 calibration: BSD conductor to 40, 93 curves, 92 rank 0 and 1 rank 1 (37a1), all 92 rank-0 L(E,1) nonzero; Riemann first 3000 zeros re-verified on the line, max deviation 0.0, first 2000 match round 2 exactly; run twice, identical hashes",
        payload=calib_payload,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... calibration round 4")
    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), rounds 3 and 4",
        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()
