#!/usr/bin/env python3
"""Standalone record-level verifier for E403-MR. Stdlib + cryptography; imports no CAIN code.

It checks:
  * the Ed25519 signature on the evidence statement;
  * the report and preregistration hashes;
  * the committed salts;
  * every signed, hash-chained memory entry in the report;
  * the reported hypotheses and verdict against the measurements.

It does NOT re-execute the microcosm. That limit is printed with the result.
"""
from __future__ import annotations

import base64
import hashlib
import json
import sys
from pathlib import Path

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

HERE = Path(__file__).resolve().parent
TENANT = "cain42-e403mr"
STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"


def sha(b) -> str:
    return hashlib.sha256(b if isinstance(b, bytes) else b.encode()).hexdigest()


def canon(o) -> bytes:
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


def main() -> int:
    ev = json.loads((HERE / "E403MR_EVIDENCE.json").read_text())
    rep = json.loads((HERE / "E403MR_RUN_REPORT.json").read_text())
    pre = json.loads((HERE / "E403MR_PREREGISTRATION.json").read_text())
    salts = json.loads((HERE / "SALTS.json").read_text())
    checks = []

    def check(name, ok, detail=""):
        checks.append(bool(ok))
        print(f"{'PASS' if ok else 'FAIL'}  {name}" + (f"  {detail}" if detail else ""))

    body = {k: v for k, v in ev.items() if k not in ("signature_b64", "public_key_b64", "key_fingerprint")}
    pub = base64.b64decode(ev["public_key_b64"])
    try:
        Ed25519PublicKey.from_public_bytes(pub).verify(bytes.fromhex(ev["signature_b64"]), canon(body))
        check("evidence Ed25519 signature", True)
    except Exception as exc:  # noqa: BLE001
        check("evidence Ed25519 signature", False, type(exc).__name__)
    check("evidence key fingerprint", ev["key_fingerprint"] == sha(pub)[:16])
    check("report hash", ev["report_sha256"] == sha((HERE / "E403MR_RUN_REPORT.json").read_bytes()))
    check("preregistration hash", ev["preregistration_sha256"] == sha((HERE / "E403MR_PREREGISTRATION.json").read_bytes()))
    check("salt commitments", all(sha(salts[k].encode()) == pre["salt_commitments_sha256"][k]
                                  for k in ("shared", "salt1", "salt2")))

    pubs = rep["raw"]["pubs"]
    prev, bad = "", []
    for e in rep["raw"]["entries"]:
        payload = {"seq": e["seq"], "tenant": TENANT, "agent": e["agent"], "kind": e["kind"],
                   "key": e["key"], "value": e["value"], "prev": e["prev"], "created_at": e["created_at"]}
        b = canon(payload)
        ok = e["prev"] == prev and sha(prev.encode() + b + bytes.fromhex(e["sig"])) == e["hash"]
        if ok:
            try:
                Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubs[e["agent"]])).verify(
                    bytes.fromhex(e["sig"]), b)
            except Exception:  # noqa: BLE001
                ok = False
        if not ok:
            bad.append(e["seq"])
        prev = e["hash"]
    check("memory hash chain and signatures", not bad, f"{len(rep['raw']['entries'])} entries, bad={bad}")

    m = rep["measurements"]
    H = rep["hypotheses"]
    iso = m["libraries"]["isolated"]
    h1 = m["libraries"]["shared"] > max(iso.values())
    sc, ic = m["sealed"]["shared"], m["sealed"]["isolated_best"]
    h2 = (sc["salt1"]["gen2"] + sc["salt1"]["gen3"] >= 22 and ic["salt1"]["total"] <= 6)
    h3 = (m["dev"]["shared"]["gen3"] >= 10 and m["sealed"]["baseline_no_library"]["salt1"] == 0
          and sc["salt1"]["gen3"] >= 10)
    po = m["poison"]
    h4 = (po["library_unchanged"] and not po["poison_keys_in_library"]
          and all(not x["admitted"] for x in po["admissions"])
          and all(x["authority"].startswith("REFUSED") for x in po["promotions"]))
    h5 = not m["integrity"].get("bad_entries")
    h6 = (sc["salt2"]["gen2"] + sc["salt2"]["gen3"] >= 22 and ic["salt2"]["total"] <= 6)
    computed = {"H1_shared_library_larger": h1, "H2_cross_agent_coverage": h2,
                "H3_compounding": h3, "H4_poison_refused": h4, "H5_integrity": h5,
                "H6_replication": h6}
    for k, v in computed.items():
        want = "SUPPORTED" if v else "NOT_SUPPORTED"
        check(k, H[k]["verdict"] == want, f"reported={H[k]['verdict']} computed={want}")
    check("H7 external review blocked", H["H7_external_review"]["verdict"] == "BLOCKED")
    expect_verdict = ("GOVERNED_SHARED_MEMORY_COMPOSITION_SUPPORTED"
                      if all(computed.values()) else "NOT_SUPPORTED")
    check("verdict", rep["verdict"] == expect_verdict == ev["verdict"],
          f"reported={rep['verdict']} computed={expect_verdict}")
    check("status line", ev["status"] == STATUS and rep["status"] == STATUS)

    ok = all(checks)
    print(f"\n{sum(checks)}/{len(checks)} checks passed")
    print("Record-level verification only: the microcosm is not re-executed; no external reviewer.")
    print(STATUS)
    return 0 if ok else 1


if __name__ == "__main__":
    raise SystemExit(main())
