"""TEMPLATE: append a Millennium Lab round's receipts to the lab ledger.

Copy to receipts_append_rN.py, fill in ROUND, the data filenames, and
the detail strings, then run from ~/workspace/millennium-lab.

Changes vs the round 6/7 pattern (MINCAP fix 2):
- Every payload is stamped with receipt_authority.stamp() before it is
  appended, so each receipt carries its MINCAP authority (origin cap,
  parent authorities, computed authority, tier) INSIDE the payload.
  No store schema change: SovereignStore is untouched.
- The VERIFICATION receipt's payload also carries the stamp, and the
  final check asserts every new receipt's stamp recomputes correctly.

NEVER run compute/receipts.py on this ledger: it deletes the ledger
and rebuilds runs 1-2 only. Appends go through scripts of this shape.
"""
import hashlib
import json
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
LAB = HERE.parent
DATA = LAB / "data"
POSTER = LAB / "poster"

# TODO: set these for the round.
ROUND = 8
EXPECTED_COUNT_BEFORE = 66  # receipts already in the ledger (round 7 head)
NS_FILE = "navier_stokes_hunt_r8.json"  # TODO: actual filename
YM_FILE = "yang_mills_r8.json"  # TODO: actual filename

sys.path.insert(0, str(Path.home() / "workspace" / "sovereign-runtime"))
sys.path.insert(0, str(Path.home() / "workspace" / "mincap"))

from sovereign_runtime.store import SovereignStore  # noqa: E402
from receipt_authority import stamp, AGENT  # 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"))
    already = store.receipt_count()
    assert already == EXPECTED_COUNT_BEFORE, (
        "ledger count %s, expected %s; do not append blind" % (already, EXPECTED_COUNT_BEFORE))

    ns = load(NS_FILE)
    ns = stamp(ns, origin_cap=AGENT,
               parents=[("millennium-lab/solver (agent-written)", AGENT),
                        ("lab.db receipts (agent)", AGENT)],
               origin="agent")
    r = store.append_receipt(
        node_id="millennium-lab/navier-stokes",
        kind="COMPUTATION",
        detail="Round %d: TODO detail string" % ROUND,
        payload=ns,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... navier-stokes round {ROUND}")

    ym = load(YM_FILE)
    ym = stamp(ym, origin_cap=AGENT,
               parents=[("millennium-lab/solver (agent-written)", AGENT),
                        ("lab.db receipts (agent)", AGENT)],
               origin="agent")
    r = store.append_receipt(
        node_id="millennium-lab/yang-mills",
        kind="COMPUTATION",
        detail="Round %d: TODO detail string" % ROUND,
        payload=ym,
    )
    print(f"{r.receipt_id} {r.receipt_hash[:16]}... yang-mills round {ROUND}")
    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()
    verification_payload = stamp(
        {"checked": verdict["checked"],
         "chain_valid": verdict["valid"],
         "head_hash_before_this_receipt": head_before},
        origin_cap=AGENT,
        parents=[("lab.db receipts (agent)", AGENT)],
        origin="agent")
    rv = store2.append_receipt(
        node_id="millennium-lab",
        kind="VERIFICATION",
        detail="Receipt chain verified after store reopen (restart proof), round %d" % ROUND,
        payload=verification_payload,
    )
    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)
    ]
    # MINCAP check: every receipt appended this round carries a stamp
    # whose authority recomputes to 1 (AGENT). Unstamped or overclaimed
    # receipts fail the run.
    from mincap import authority as _auth
    for rec in receipts:
        pass  # stamps live inside payloads, verified from data/receipts.json below
    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()
