"""Write Millennium Lab computation receipts into the sovereign runtime's
hash-chained receipt format.

Direct reuse of the production runtime's receipt chain: this imports
SovereignStore from ~/workspace/sovereign-runtime/sovereign_runtime and
writes into a lab ledger (data/lab.db) using the identical receipt
format (canonical JSON, SHA-256, prev_hash chaining, GENESIS head).
The runtime's own ledger is untouched; the lab ledger is a separate
store in the same format, verifiable with the same verify_chain call.

Receipts written:
  rcpt_0001  COMPUTATION  riemann zero verification (batch, with results SHA-256)
  rcpt_0002+ COMPUTATION  one per BSD curve (rank, L-value, method, source)
  rcpt_last  VERIFICATION chain verification after a reopen (restart proof)
"""
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 sha256_file(p: Path) -> str:
    return hashlib.sha256(p.read_bytes()).hexdigest()


def main() -> None:
    db = DATA / "lab.db"
    if db.exists():
        db.unlink()
    store = SovereignStore(str(db))

    riemann_path = DATA / "riemann_zeros.json"
    riemann = json.loads(riemann_path.read_text())
    r1 = store.append_receipt(
        node_id="millennium-lab/riemann",
        kind="COMPUTATION",
        detail="Riemann zero verification: first 1000 non-trivial zeros on the critical line",
        payload={
            "method": riemann["method"],
            "date": riemann["date"],
            "zeros_checked": riemann["zeros_checked"],
            "t_first": riemann["t_first"],
            "t_last": riemann["t_last"],
            "max_re_deviation": riemann["max_re_deviation"],
            "worst_zero_n": riemann["worst_zero_n"],
            "max_abs_zeta_at_line": riemann["max_abs_zeta_at_line"],
            "von_mangoldt_expected_at_T": riemann["von_mangoldt_expected_at_T"],
            "S_of_T": riemann["S_of_T"],
            "scan_seconds": riemann["scan_seconds"],
            "total_seconds": riemann["total_seconds"],
            "results_sha256": sha256_file(riemann_path),
        },
    )
    print(f"{r1.receipt_id} {r1.receipt_hash[:16]}... riemann batch")

    bsd_path = DATA / "bsd_curves.json"
    bsd = json.loads(bsd_path.read_text())
    for c in bsd["curves"]:
        r = store.append_receipt(
            node_id="millennium-lab/bsd",
            kind="COMPUTATION",
            detail=f"BSD curve {c['label']}: rank and L-value",
            payload={
                "label": c["label"],
                "equation": c["equation"],
                "conductor": c["conductor"],
                "rank": c["rank"],
                "rank_method": c["rank_method"],
                "L_value": c["L_value"],
                "L_value_at": c["L_value_at"],
                "L_method": c["L_method"],
                "source": c["source"],
            },
        )
        print(f"{r.receipt_id} {r.receipt_hash[:16]}... curve {c['label']} rank {c['rank']}")
    store.close()

    # Restart proof: reopen the store from disk and verify the chain.
    store2 = SovereignStore(str(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(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(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()
