#!/usr/bin/env python3
"""E412-M standalone offline verifier (stdlib + cryptography; imports no CAIN code).

It re-checks, from the shipped bundle alone:
  * the manifest Ed25519 signature and every declared file SHA-256;
  * the Merkle root recomputed from those hashes;
  * the frozen preregistration hash, the salt commitments and the revealed salts;
  * every memory chain: canonical body, SHA-256 link, prev link and Ed25519 signature,
    with the public key re-derived from the E380-M study key rule;
  * the hypotheses recomputed from the raw curves, probes and verification rows;
  * the verdict rule, the checkpoint hash chain and the no-models/no-spend record.

It does not re-execute the research engine (the engine source is withheld under the IP
rule). A PASS means the record is internally consistent and cryptographically bound,
not that the research claim is true.
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey

STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
POISON = "single|random|10|20"
THRESH = 0.04
ARMS = ("none", "claimed", "verified")
SALTS = ("primary", "replication")


def sha(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


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


def load(p: Path):
    return json.loads(Path(p).read_text())


def derive_pub(agent: str) -> bytes:
    k = Ed25519PrivateKey.from_private_bytes(hashlib.sha256(("e380m|" + agent).encode()).digest())
    return k.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)


class Checker:
    def __init__(self):
        self.rows = []

    def add(self, name: str, ok: bool, detail: str = "") -> None:
        self.rows.append({"check": name, "ok": bool(ok), "detail": detail})

    def finish(self) -> int:
        ok = sum(1 for r in self.rows if r["ok"])
        n = len(self.rows)
        for r in self.rows:
            print(f'{"PASS" if r["ok"] else "FAIL"}  {r["check"]}  {r["detail"]}')
        print(f"\n{ok}/{n} checks passed · {STATUS}")
        return 0 if ok == n else 1


def by_arm(report: dict, salt: str, arm: str) -> dict:
    return report["curves"][f"{salt}|{arm}"]


def block(report: dict, salt: str) -> dict:
    non, cla, ver = (by_arm(report, salt, a) for a in ARMS)
    h1 = ver[2]["sealed_accepted_correct"] - ver[0]["sealed_accepted_correct"]
    h2 = ver[2]["sealed_accepted_correct"] - non[2]["sealed_accepted_correct"]
    h3 = (cla[1]["champion"] == POISON
          and cla[1]["sealed_accepted_correct"] < non[1]["sealed_accepted_correct"])
    return {"H1": h1 >= THRESH, "H2": h2 >= THRESH, "H3": h3,
            "h1_delta": round(h1, 6), "h2_delta": round(h2, 6)}


def memory_rows(bundle: Path, salt: str, arm: str) -> list[dict]:
    p = bundle / "memory" / f"{salt}-{arm}.json"
    if not p.exists():
        return []
    doc = load(p)
    recs = doc.get("records") or []
    if recs and "rows" in recs[0]:             # the isolated arm stores one part per agent
        out = []
        for part in recs:
            out.extend(part.get("rows") or [])
        return out
    return recs


def memory_parts(bundle: Path, salt: str, arm: str) -> list[tuple[str, list[dict]]]:
    docs = memory_rows(bundle, salt, arm)
    doc = load(bundle / "memory" / f"{salt}-{arm}.json")
    recs = doc.get("records") or []
    if recs and "rows" in recs[0]:
        return [(f"{salt}-{arm}-{p.get('agent', '?')}", p.get("rows") or []) for p in recs]
    return [(f"{salt}-{arm}", docs)]


def check_chain(ch: Checker, label: str, rows: list[dict]) -> None:
    prev = "0" * 64
    ok, sig_ok, canon_ok = True, True, True
    for r in rows:
        body = {"tenant": r["tenant"], "seq": r["seq"], "agent": r["agent"], "kind": r["kind"],
                "payload": r["payload"], "uncertainty": r["uncertainty"],
                "verification": r["verification"], "prev": r["prev"]}
        try:
            h = sha(canon(body) + bytes.fromhex(r["sig"]))
        except Exception:
            canon_ok = False
            break
        if h != r["hash"] or r["prev"] != prev:
            ok = False
            break
        try:
            Ed25519PublicKey.from_public_bytes(derive_pub(r["agent"])).verify(
                bytes.fromhex(r["sig"]), canon(body))
        except InvalidSignature:
            sig_ok = False
            break
        prev = r["hash"]
    ch.add(f"chain:{label}", ok and sig_ok and canon_ok,
           f"{len(rows)} rows, link={ok}, signature={sig_ok}")


def main(argv: list[str]) -> int:
    bundle = Path(argv[1] if len(argv) > 1 else ".").resolve()
    ch = Checker()

    man = load(bundle / "MANIFEST.json")
    body = load(bundle / "E412-M_SIGNED_BODY.json")
    sig = man.get("signature", "")
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(sig), canon(body))
        ch.add("manifest_signature", True, man["pubkey_fingerprint"])
    except Exception as exc:  # noqa: BLE001
        ch.add("manifest_signature", False, repr(exc)[:80])

    declared = man.get("files", {})
    bad = [n for n, h in declared.items() if not (bundle / n).exists() or sha((bundle / n).read_bytes()) != h]
    ch.add("file_hashes", not bad, f"{len(declared)} files" + (f", bad={bad[:3]}" if bad else ""))

    leaves = sorted(declared.values())
    while len(leaves) > 1:
        if len(leaves) % 2:
            leaves.append(leaves[-1])
        leaves = [sha((leaves[i] + leaves[i + 1]).encode()) for i in range(0, len(leaves), 2)]
    ch.add("merkle_root", (leaves[0] if leaves else sha(b"")) == man.get("merkle_root"),
           str(man.get("merkle_root"))[:16])

    pre = load(bundle / "E412-M_PREREGISTRATION.json")
    frz = load(bundle / "E412-M_PREREGISTRATION_FREEZE.json")
    ch.add("preregistration_frozen", sha(canon(pre)) == frz["preregistration_sha256"]
           or sha((bundle / "E412-M_PREREGISTRATION.json").read_bytes()) == frz["preregistration_sha256"],
           frz["preregistration_sha256"][:16])
    sal = load(bundle / "E412-M_SALT_REVEALED.json")["salts"]
    ch.add("salt_commitments",
           all(sha(bytes.fromhex(sal[k])) == pre["salt_commitment_sha256"][k] for k in SALTS),
           ", ".join(k for k in SALTS))

    report = load(bundle / "E412-M_RUN_REPORT.json")
    corrp = bundle / "E412-M_ANALYSIS_CORRECTION.json"
    corr = load(corrp) if corrp.exists() else None
    hyp = corr["hypotheses"] if corr else report["hypotheses"]
    vrd = corr["verdict"] if corr else report["verdict"]
    ch.add("status_line", report.get("status") == STATUS, report.get("status", ""))
    ch.add("no_model_no_spend", report["design"]["model_calls"] == 0
           and report["design"]["api_spend_usd"] == 0.0, "0 calls, $0")

    # headline in the signed body must agree with the report
    hl = man.get("headline", {})
    pv = [g["sealed_accepted_correct"] for g in by_arm(report, "primary", "verified")]
    ch.add("headline_matches_report", hl.get("verdict") == vrd
           and hl.get("primary_verified") == pv,
           f'verdict={hl.get("verdict")}, primary_verified={hl.get("primary_verified")}')

    # checkpoint hash chain
    prev, cp_ok = "0" * 64, True
    for c in report.get("checkpoints", []):
        if c["prev"] != prev:
            cp_ok = False
            break
        prev = c["hash"]
    ch.add("checkpoint_chain", cp_ok and len(report.get("checkpoints", [])) == 6,
           f'{len(report.get("checkpoints", []))} checkpoints')

    # hypotheses recomputed on the primary salt
    pb = block(report, "primary")
    rb = block(report, "replication")
    for k in ("H1", "H2", "H3"):
        ch.add(f"recompute:{k}", pb[k] == (hyp[k]["verdict"] == "SUPPORTED"),
               f'recomputed={"PASS" if pb[k] else "FAIL"} vs reported {hyp[k]["verdict"]}')

    def h4_from(salt: str):
        rows = memory_rows(bundle, salt, "verified")
        vs = [r["payload"] for r in rows if r["payload"].get("type") == "verification"]
        pv = [v for v in vs if v["procedure"] == POISON]
        pool = max([float(v["verified_score"]) for v in vs
                    if v.get("accepted") and v["procedure"] == POISON], default=None)
        ok = bool(pv) and all(not v["accepted"] for v in pv) and (pool is None or pool < 0.5)
        return ok, f"{len(pv)} poison verification(s), verified pool={pool}"

    h4p, d4p = h4_from("primary")
    ch.add("recompute:H4", h4p, d4p)

    def probes_of(salt: str, arm: str):
        p = bundle / f"E412-M_PROBES_{salt}_{arm}.json"
        return load(p) if p.exists() else None

    pp = [probes_of("primary", a) for a in ("claimed", "verified")]
    ch.add("probes_shipped", all(x is not None for x in pp), "primary claimed + verified")
    h5p = all(x is not None and x.get("all_pass") for x in pp)
    ch.add("recompute:H5", h5p, "; ".join(
        f'{x["arm"]}={"pass" if x.get("all_pass") else "fail"}' for x in pp if x))

    # contradiction: two different scores for the poison in the claimed memory
    crows = memory_rows(bundle, "primary", "claimed")
    scores = sorted({round(float(r["payload"]["score"]), 6) for r in crows
                     if r["payload"].get("type") == "claim" and r["payload"].get("procedure") == POISON})
    ch.add("contradiction_visible", len(scores) >= 2, f"poison claim scores={scores}")

    # signatures + chains for every exported memory
    for salt in SALTS:
        for arm in ARMS:
            for label, rows_ in memory_parts(bundle, salt, arm):
                check_chain(ch, label, rows_)

    # reported verdict follows the frozen rule
    passed = sum(1 for k in ("H1", "H2", "H3", "H4", "H5") if hyp[k]["verdict"] == "SUPPORTED")
    h4r, _ = h4_from("replication")
    rp = [probes_of("replication", a) for a in ("claimed", "verified")]
    h5r = all(x is not None and x.get("all_pass") for x in rp)
    h6 = all(rb[k] for k in ("H1", "H2", "H3")) and h4r and h5r
    expected = ("VERIFIED_MEMORY_COMPOUNDS" if passed == 5 and h6
                else "PARTIAL" if passed >= 3 else "NOT_SUPPORTED")
    ch.add("verdict_rule", vrd == expected, f'{vrd} (expected {expected})')
    ch.add("replication_block", h6 == (hyp["H6"]["verdict"] == "SUPPORTED"),
           hyp["H6"]["verdict"])
    if corr:
        ch.add("correction_scope", all(c["hypothesis"] == "H5" for c in corr.get("changes", []))
               and corr.get("unchanged_rows") is True,
               f'{len(corr.get("changes", []))} change(s), only H5, unchanged rows')
        ch.add("corrected_H5_matches_probe", (corr["hypotheses"]["H5"]["verdict"] == "SUPPORTED") == h5p,
               f'corrected H5={corr["hypotheses"]["H5"]["verdict"]}, recomputed={h5p}')
        ch.add("correction_as_shipped_consistent",
               report["verdict"] == corr.get("as_shipped_verdict"),
               f'as-shipped {report["verdict"]} vs correction {corr.get("as_shipped_verdict")}')
        changed = {c["hypothesis"] for c in corr.get("changes", [])}
        same = all(corr["hypotheses"][k]["verdict"] == report["hypotheses"][k]["verdict"]
                   for k in corr["hypotheses"] if k not in changed)
        ch.add("correction_changes_only_listed", same, "unchanged hypotheses agree with the as-shipped report")

    return ch.finish()


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))
