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

Recomputes the pooled summary and verdict from the 8 raw cells, checks the per-read revocation
arms, opens the shipped revocation ledger, and verifies the chains, manifest and signature.
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
CELLS = 8
EX = {"E345R_MANIFEST.json", "E345R_SIGNED_BODY.json", "E345R_VERIFICATION_RESULTS.json",
      "E345R_TAMPER_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
      "E345R_OMEGA_SEAL.json"}


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


def sha(b):
    return hashlib.sha256(b).hexdigest()


def chain(rows):
    prev = "0" * 64
    out = []
    for r in rows:
        hh = sha((prev + sha(canon(r))).encode())
        out.append({"i": len(out), "prev": prev, "hash": hh})
        prev = hh
    return out


def chain_ok(ch):
    prev = "0" * 64
    for i, x in enumerate(ch):
        if x["i"] != i or x["prev"] != prev:
            return False
        prev = x["hash"]
    return True


def merkle(paths):
    leaves = sorted(sha(p.read_bytes()) for p in paths)
    if not leaves:
        return sha(b"")
    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)]
    return leaves[0]


def summarize(rows):
    n = len(rows)
    s = {"cells": n}
    ep = [r["arms"]["EPOCH"] for r in rows]
    s["epoch"] = {"revoked": sum(1 for a in ep if a["revoked"]), "cells": n,
                  "post_fence_total": sum(a["post_fence_executed"] or 0 for a in ep),
                  "claims": sum(1 for a in ep if a["decision"] == "ACCEPT"),
                  "executed_equals_fence": sum(1 for a in ep if a["executed"] == a["revoke_at"]),
                  "typed_revocation": sum(1 for a in ep if a.get("typed_revocation", 0) >= 1),
                  "executed_total": sum(a["executed"] for a in ep)}
    px = [r["arms"]["PARITY"] for r in rows]
    s["parity"] = {"matched": sum(1 for a in px if a["parity"]), "cells": n,
                   "executed_total": sum(a["executed"] for a in px),
                   "duplicate_permits": sum(a["permits"] - a["unique_permits"] for a in px)}
    md = [r["arms"]["MINT_DENIED"] for r in rows]
    s["mint_denied"] = {"zero_reads": sum(1 for a in md if a["executed"] == 0), "cells": n,
                        "claims": sum(1 for a in md if a["decision"] == "ACCEPT"),
                        "typed_revocation": sum(1 for a in md if a.get("typed_revocation", 0) >= 1)}
    td = [r["arms"]["TOKEN_DEAD"] for r in rows]
    s["token_dead"] = {"refused": sum(1 for a in td if not a["ok"]), "cells": n,
                       "accepted": sum(1 for a in td if a["ok"]),
                       "typed": sum(1 for a in td if "JIT_PRINCIPAL_REVOKED" in str(a.get("why")))}
    s["contrast"] = {"e344p_cached_post_fence_reads": 135,
                     "e345r_epoch_post_fence_reads": s["epoch"]["post_fence_total"]}
    return s


def decide(s):
    h1 = (s["epoch"]["revoked"] == CELLS and s["epoch"]["post_fence_total"] == 0
          and s["epoch"]["claims"] == 0 and s["epoch"]["executed_equals_fence"] == CELLS
          and s["epoch"]["typed_revocation"] == CELLS)
    h2 = s["parity"]["matched"] == s["parity"]["cells"] == CELLS
    h3 = (s["mint_denied"]["zero_reads"] == CELLS and s["mint_denied"]["claims"] == 0
          and s["mint_denied"]["typed_revocation"] == CELLS)
    h4 = (s["token_dead"]["refused"] == CELLS and s["token_dead"]["accepted"] == 0
          and s["token_dead"]["typed"] == CELLS)
    vals = {"H1_epoch_kill_zero_post_fence": h1, "H2_parity": h2,
            "H3_revoked_principal_cannot_mint": h3, "H4_pre_revocation_token_dead": h4}
    verdict = ("IMMEDIATE_CROSS_PROCESS_REVOCATION" if all(vals.values()) else "NOT_SUPPORTED")
    return vals, verdict


def main() -> int:
    d = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
    rep = json.loads((d / "E345R_RUN_REPORT.json").read_text())
    pre = json.loads((d / "E345R_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E345R_PREREGISTRATION_FREEZE.json").read_text())
    salts = json.loads((d / "E345R_SALT_REVEALED.json").read_text())
    ext = json.loads((d / "E345R_EXTERNAL_REVIEW_STATUS.json").read_text())
    dev = json.loads((d / "E345R_DEVIATIONS.json").read_text())
    man = json.loads((d / "E345R_MANIFEST.json").read_text())
    rev = json.loads((d / "E345R_REVOCATIONS.json").read_text())
    checks = []

    def ck(name, ok):
        checks.append((name, bool(ok)))

    ck("schema", rep["schema"] == "cain42.e345r.run_report.v1")
    ck("evolution", rep["evolution"] == "E345-R")
    ck("status line", rep["status"] == S)
    ck("prereg hash", sha((d / "E345R_PREREGISTRATION.json").read_bytes())
       == frz["preregistration_sha256"])
    ck("salt commitments", all(sha(bytes.fromhex(salts[k])) == v
                               for k, v in pre["salt_commitment_sha256"].items()))
    ck("jit key commitment recorded", salts.get("jit_key_commitment_sha256")
       == pre["jit_key_commitment_sha256"] and "jit_key" not in salts)
    ck("two salts", set(rep["sets"]) == {"primary", "replication"})
    allr = []
    for salt in ("primary", "replication"):
        rows = rep["sets"][salt]["rows"]
        ck(f"{salt} 4 cells", len(rows) == 4)
        allr += rows
    ck("pooled 8 cells", len(allr) == CELLS)

    ok_ep = ok_px = ok_md = ok_td = True
    for r in allr:
        a = r["arms"]
        if set(a) != {"PARITY", "EPOCH", "TOKEN_DEAD", "MINT_DENIED"}:
            ok_ep = False
            continue
        ep = a["EPOCH"]
        ok_ep &= (ep["revoked"] is True and ep["decision"] == "REFUSE"
                  and (ep["post_fence_executed"] or 0) == 0
                  and ep["executed"] == ep["revoke_at"]
                  and ep.get("typed_revocation", 0) >= 1)
        px = a["PARITY"]
        ok_px &= (px["parity"] is True and px["executed"] == px["permits"] == px["unique_permits"])
        md = a["MINT_DENIED"]
        ok_md &= (md["executed"] == 0 and md["decision"] == "REFUSE"
                  and md.get("typed_revocation", 0) >= 1)
        td = a["TOKEN_DEAD"]
        ok_td &= (td["ok"] is False and "JIT_PRINCIPAL_REVOKED" in str(td.get("why")))
    ck("epoch per cell", ok_ep)
    ck("parity per cell", ok_px)
    ck("mint denied per cell", ok_md)
    ck("token dead per cell", ok_td)

    ck("revocation ledger", rev["count"] == 16 and len(rev["rows"]) == 16
       and len({x["principal"] for x in rev["rows"]}) == 16
       and all(float(x["not_before"]) > 0 for x in rev["rows"]))

    pooled = summarize(allr)
    prim = summarize(rep["sets"]["primary"]["rows"])
    rep_s = summarize(rep["sets"]["replication"]["rows"])
    ck("pooled summary recomputed", pooled == rep["summaries"]["all"])
    ck("primary summary recomputed", prim == rep["summaries"]["primary"])
    ck("replication summary recomputed", rep_s == rep["summaries"]["replication"])
    vals, verdict = decide(pooled)
    ck("pooled verdict recomputed", verdict == rep["verdict"])
    ck("pooled hypotheses recomputed", all(rep["hypotheses"][k]["verdict"]
                                           == ("SUPPORTED" if v else "NOT_SUPPORTED")
                                           for k, v in vals.items()))
    ck("replication direction", rep_s["epoch"]["post_fence_total"] == 0
       and rep_s["parity"]["matched"] == 4 and rep_s["mint_denied"]["zero_reads"] == 4
       and rep_s["token_dead"]["refused"] == 4)
    ck("external review blocked", rep["hypotheses"]["H5_external_review"]["verdict"] == "BLOCKED"
       and ext["status"] == "NOT_OBTAINED")
    ck("deviations recorded", isinstance(dev.get("deviations"), list))
    ck("model calls zero", rep["resources"]["model_calls"] == 0
       and rep["resources"]["api_spend_usd"] == 0.0)
    ck("limits present", len(rep["limits"]) >= 6)
    ck("hardening declared", "CAIN_JIT_REVOCATION_ENFORCE" in
       (d / "E345R_PREREGISTRATION.json").read_text())

    for salt, fname in (("primary", "E345R_CHAIN_PRIMARY.json"),
                        ("replication", "E345R_CHAIN_REPLICATION.json")):
        ch = json.loads((d / fname).read_text())["chain"]
        rows = rep["sets"][salt]["rows"]
        ck(f"{salt} chain", chain_ok(ch) and len(ch) == len(rows) and ch == chain(rows))

    HEAD = ("epoch", "parity", "mint_denied", "token_dead", "contrast")
    ck("headline matches report", all(man["headline"][k] == pooled[k] for k in HEAD)
       and man["headline"]["verdict"] == rep["verdict"])
    files = sorted(p for p in d.rglob("*") if p.is_file()
                   and str(p.relative_to(d)) not in EX and "__pycache__" not in p.parts
                   and not p.name.endswith(("-wal", "-shm")))
    ck("manifest files", man["files"] == {str(p.relative_to(d)): sha(p.read_bytes())
                                         for p in files})
    ck("merkle root", man["merkle_root"] == merkle(files))
    try:
        from cryptography.hazmat.primitives import serialization
        pk = serialization.load_pem_public_key((d / "E345R_PUBKEY.pem").read_bytes()) \
            if (d / "E345R_PUBKEY.pem").exists() else None
        if pk is None:
            from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
            pk = Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
        pk.verify(bytes.fromhex(man["signature"]),
                  canon({k: v for k, v in man.items() if k != "signature"}))
        ck("manifest signature", True)
    except Exception as e:  # noqa: BLE001
        ck(f"manifest signature ({type(e).__name__})", False)

    ck("engine source withheld", not any(
        p.name in ("run.py", "worker.py", "learner.py", "certificate.py", "build_seq.py",
                   "mcp_proxy.py", "jit_capability.py")
        or "cain2027" in p.parts for p in d.rglob("*") if p.is_file()))
    ck("status in public summary", S in (d / "E345R_PUBLIC_SUMMARY.md").read_text())

    bad = [n_ for n_, ok in checks if not ok]
    for n_, ok in checks:
        print(("PASS " if ok else "FAIL ") + n_)
    print(f"{len(checks) - len(bad)}/{len(checks)} checks passed")
    return 0 if not bad else 1


if __name__ == "__main__":
    sys.exit(main())
