"""Append the two Millennium Lab round 6 moves' receipts to the existing
lab ledger.

Opens data/lab.db WITHOUT deleting it and appends 2 receipts
(rcpt_0060-0061), reopens and verifies, appends the VERIFICATION
receipt (rcpt_0062), reopens, verifies final, regenerates
data/receipts.json. Same SovereignStore format as
compute/receipts_append_r5.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"
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"))

    ns6 = load("navier_stokes_hunt_r6.json")
    r = store.append_receipt(
        node_id="millennium-lab/navier-stokes",
        kind="COMPUTATION",
        detail="Round 6: deep dive at nu 0.000125, 64^3, dt 0.01, stability probe passed (35.73 s, per-step 0.357 s, no cost explosion); Kida-Pelz enstrophy growth 88.24 (ladder 18.86, 40.33, 64.46, 88.24), Taylor-Green 87.56, perturbed Taylor-Green 78.67 at 64^3 and 58.29 at 48^3 (resolution ratio 1.35); anti-parallel tubes inert again (1.02, and tight variant 1.24), the configuration does not stretch at any tested viscosity; Kida-Pelz T=20 peaks at t=9.4 and decays to 37.7x by t=20, growth is transient not runaway; 96^3 cost probe with the current solver 1.716 s/step, full run about 0.48 h and 379 MB peak RSS, the Round 3 8.8 h rejection was the old solver; dual run of the strongest case identical hashes; all cases stayed smooth, no blowup",
        payload=ns6,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... navier-stokes round 6")

    ym6 = load("yang_mills_r6.json")
    r = store.append_receipt(
        node_id="millennium-lab/yang-mills",
        kind="COMPUTATION",
        detail="Round 6: second seed (base 20261121) at beta 2.5 and 2.6, 8^4 SU(2), same setup as round 5; seed 2 torelon is far below seed 1 at both betas (2.5: 0.890 plus/minus 0.044 vs 1.280 plus/minus 0.082; 2.6: 1.193 plus/minus 0.106 vs 1.608 plus/minus 0.161), and the difference runs through every tau, so it is a correlator-level chain difference, not plateau picking; GEVP 0++ seed 2 is higher at 2.6 (1.603 plus/minus 0.134 vs 1.332 plus/minus 0.099); torelon extrapolation OVERTURNED: seed 1 fit intercept 2.423 plus/minus 0.739 chi2/dof 7.60/3, seed 2 fit intercept -0.208 plus/minus 0.643 chi2/dof 29.71/3, seed-mean fit 0.702 plus/minus 0.611 chi2/dof 35.04/3; the five-point linear extrapolation cannot support any continuum claim, and the jackknife errors underestimate the true chain-to-chain uncertainty",
        payload=ym6,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... yang-mills round 6")
    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 6",
        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()
