"""Append the four new Millennium Lab moves' receipts to the existing lab ledger.

Opens data/lab.db WITHOUT deleting it and appends 6 receipts (rcpt_0031-0036),
reopens and verifies, appends the VERIFICATION receipt (rcpt_0037), reopens,
verifies final, regenerates data/receipts.json. Same SovereignStore format as
compute/receipts.py; the lab ledger is a separate store from the runtime's own.
"""
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

NS_AUDIT_PAYLOAD = {
    "paper_title": "On the Navier-Stokes Millennium Prize Problem",
    "paper_url": "https://openai.com/index/navier-stokes-solution/",
    "date_read": "2026-11-20",
    "proves": [
        "As claimed in the OpenAI announcement (not independently verified here): finite-time blowup for forced 3D incompressible Navier-Stokes, Clay statements (C) on R^3 and (D) on T^3, from rest with a smooth compactly supported force and bounded energy, plus a Lean formalization",
        "As claimed in the same announcement: finite-time blowup for the unforced Euler equations, a separate result and not a Millennium Prize problem",
    ],
    "does_not_prove": [
        "Unforced Navier-Stokes blowup or regularity, Clay statements (A) and (B), which remain open",
        "That the Clay two-year clock has started or that any prize is due, since no refereed publication or completed independent review was confirmed in the sources read",
        "Priority over Buckmaster and Alpoege on forced Euler, which OpenAI itself recognizes as theirs; the wider priority dispute is unresolved in the sources read",
    ],
    "clay_clock": "no, because Clay's rules require a refereed publication, a two-year interval, and general acceptance, and as of the sources read on 2026-11-20 there is no confirmed refereed publication, no completed independent review, and no prize awarded; Clay's 11 September 2026 statement said only that the problem has apparently been settled and that evaluation is deliberately unhurried",
}

YM_AUDIT_PAYLOAD = {
    "sources_read": [
        {"url": "https://openai.com/index/building-scientific-understanding-with-academic-communities/", "date": "2026-11-20", "note": "OpenAI announcement, October 26, 2026"},
        {"url": "https://github.com/yang-mills-group/OpenAI-YM-20261028", "date": "2026-11-20", "note": "Lean formalization submitted October 28, 2026; repository listing and README read, Lean code not read line by line"},
        {"url": "https://raw.githubusercontent.com/yang-mills-group/YM/main/docs/assessment-1.pdf", "date": "2026-11-20", "note": "Independent assessment, November 10, 2026, Douglas, Jaffe, Nissim, Rajasekaran, approved by the Yang-Mills group"},
        {"url": "https://philarchive.org/archive/NIETOA-3", "date": "2026-11-20", "note": "Nielsen critique, November 2026, The OpenAI Yang-Mills Formalization Does Not Establish Existence"},
        {"url": "https://en.wikipedia.org/w/index.php?title=Millennium_Prize_Problems&oldid=1375752114", "date": "2026-11-20", "note": "Clay rules summary: peer-reviewed publication required, at least two years from publication before consideration"},
    ],
    "criteria_met": [
        "Wightman QFT constructed as scaling limit of Wilson lattice gauge theory for any simple compact gauge group (assessment judgment)",
        "Osterwalder-Schrader axioms for component theories with clustering",
        "Conserved stress tensor, short-distance laws, operator product expansion with bounds",
        "Lean clean rebuild with zero errors, no placeholder axiom in solution, Comparator passed October 30 and November 3",
    ],
    "criteria_disputed": [
        "Existence on R4 in the Clay sense: convergence is subsequential only, infinite-volume limit uniqueness unproven",
        "Non-triviality: trace test excludes only finite Wick profiles, not generalized free fields",
        "Contact-term uniqueness: correlations established only for separated points",
        "Identification of the constructed object as Yang-Mills theory: evidence, not proof; no human verification of the full construction",
    ],
    "gaps_remaining": [
        "Mass gap Delta greater than 0: explicitly not claimed, no evidence for or against",
        "Uniqueness of the infinite-volume limit and of the vacuum",
        "Wilson loop area law",
        "Continuum probability measure",
        "Single-particle states and energy-momentum spectrum",
        "Human-readable exposition with general acceptance in the mathematics community",
        "Peer-reviewed publication, the Clay clock prerequisite",
    ],
    "clay_clock": "no, because there is no peer-reviewed publication and the mass gap half has no proof; Clay rules require a peer-reviewed publication plus two years before consideration, and the problem requires both halves",
}


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


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

    ns = load("navier_stokes.json")
    r = store.append_receipt(
        node_id="millennium-lab/navier-stokes",
        kind="COMPUTATION",
        detail="32^3 pseudo-spectral Taylor-Green run to t=10, nu=0.01, peak enstrophy growth 1.73, stayed smooth; hunt to t=10 at nu=0.001, strongest Kida-Pelz 48^3 enstrophy growth 18.29, max vorticity growth 7.97, stayed smooth, no blowup observed",
        payload=ns,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... navier-stokes run")

    r = store.append_receipt(
        node_id="millennium-lab/navier-stokes",
        kind="AUDIT",
        detail="Background reading note on the OpenAI Navier-Stokes paper, read 2026-11-20, no verdict per founder correction; Clay clock not started, unforced case open, priority dispute unresolved",
        payload=NS_AUDIT_PAYLOAD,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... navier-stokes background")

    pnp = load("p_vs_np.json")
    r = store.append_receipt(
        node_id="millennium-lab/p-vs-np",
        kind="AUDIT",
        detail="P vs NP recipe-search complexity object: registry search in P by measurement (558 recipes, 0.0718 s sweep), composition search 2^317 candidates with linear verification, defeater non-monotonicity confirmed by run, phase transition measured; barriers: relativization no, natural proofs yes, algebrization no; no separation or collapse claimed",
        payload=pnp,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... p-vs-np")

    ym = load("yang_mills.json")
    r = store.append_receipt(
        node_id="millennium-lab/yang-mills",
        kind="COMPUTATION",
        detail="8^4 SU(2) Wilson lattice, beta 2.2 and 2.4, avg plaquette 0.568932 and 0.631483, string tension sigma a^2 0.4054 and 0.2444, torelon gap 2.67 and 1.74",
        payload=ym,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... yang-mills run")

    r = store.append_receipt(
        node_id="millennium-lab/yang-mills",
        kind="AUDIT",
        detail="Gap audit: Wightman construction judged proved by Nov 10 assessment, existence in Clay sense disputed by Nielsen critique, mass gap unclaimed and open, Clay clock cannot start",
        payload=YM_AUDIT_PAYLOAD,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... yang-mills gap audit")

    hodge = load("hodge.json")
    r = store.append_receipt(
        node_id="millennium-lab/hodge",
        kind="FORMALIZATION",
        detail="Lean 4.13.0 + mathlib v4.13.0: compiled; Lefschetz (1,1) proved conditionally and kernel-checked with no sorry, general Hodge conjecture stated; unconditional case blocked by the missing exponential sequence and Hodge decomposition in mathlib",
        payload=hodge,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... hodge")
    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)",
        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()
