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

Recomputes the pooled summary and verdict from the 8 raw cells, checks every cross-process arm's
logical invariants, opens the shipped SQLite nonce ledger to check the shared replay store, and
verifies the chains, manifest and Ed25519 signature. Refuses if engine source is present.
"""
from __future__ import annotations

import hashlib
import json
import statistics
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
CELLS = 8
EX = {"E344P_MANIFEST.json", "E344P_SIGNED_BODY.json", "E344P_VERIFICATION_RESULTS.json",
      "E344P_TAMPER_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
      "E344P_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 ledger(path):
    d = json.loads(path.read_text())
    rows = d["rows"]
    return len(rows), len(rows) - len({r["nonce"] for r in rows})


def summarize(rows, consumed_total, duplicates):
    n = len(rows)
    s = {"cells": n}
    xp = [r["arms"]["XPARITY"] for r in rows]
    s["xparity"] = {"matched": sum(1 for a in xp if a["parity"]), "cells": n,
                    "executed_total": sum(a["executed"] for a in xp),
                    "duplicate_permits": sum(a["permits"] - a["unique_permits"] for a in xp),
                    "nonce_delta_ok": sum(1 for a in xp if a["nonce_delta"] == a["executed"])}
    xr = [r["arms"]["XREPLAY"] for r in rows]
    s["xreplay"] = {"refused": sum(1 for a in xr if not a["ok"]), "cells": n,
                    "accepted": sum(1 for a in xr if a["ok"]),
                    "typed": sum(1 for a in xr if "ALREADY_CONSUMED" in str(a.get("why"))),
                    "nonce_delta_total": sum(a["nonce_delta"] for a in xr)}
    xk = [r["arms"]["XKILL"] for r in rows]
    s["xkill"] = {"killed": sum(1 for a in xk if a["killed"]), "cells": n,
                  "post_fence_total": sum(a["post_fence_executed"] or 0 for a in xk),
                  "claims": sum(1 for a in xk if a["decision"] == "ACCEPT"),
                  "still_authorized": sum(1 for a in xk if a.get("still_authorized") is True),
                  "nonce_delta_ok": sum(1 for a in xk
                                        if a["nonce_delta"] == a["executed"])}
    xb = [r["arms"]["XBUDGET"] for r in rows]
    s["xbudget"] = {"over_cap": sum(1 for a in xb if a["total_executed"] > a["cap"]),
                    "claims": sum(1 for a in xb if a["claims"]),
                    "both_fail_closed": sum(1 for a in xb
                                            if all(w["decision"] == "REFUSE"
                                                   for w in a["workers"])),
                    "typed_both": sum(1 for a in xb if a["typed"] == 2),
                    "executed_total": sum(a["total_executed"] for a in xb),
                    "cap_total": sum(a["cap"] for a in xb),
                    "nonce_delta_ok": sum(1 for a in xb
                                          if a["nonce_delta"] == a["total_executed"]),
                    "cells": n}
    s["ledger"] = {"duplicates": duplicates,
                   "all_deltas_ok": (s["xparity"]["nonce_delta_ok"] == n
                                     and s["xkill"]["nonce_delta_ok"] == n
                                     and s["xbudget"]["nonce_delta_ok"] == n
                                     and s["xreplay"]["nonce_delta_total"] == 0),
                   "consumed_total": consumed_total}
    return s


def decide(s):
    h1 = s["xparity"]["matched"] == s["xparity"]["cells"] == CELLS
    h2 = (s["xreplay"]["refused"] == CELLS and s["xreplay"]["accepted"] == 0
          and s["xreplay"]["typed"] == CELLS and s["xreplay"]["nonce_delta_total"] == 0)
    h3 = (s["xkill"]["killed"] == CELLS and s["xkill"]["post_fence_total"] == 0
          and s["xkill"]["claims"] == 0 and s["xkill"]["still_authorized"] == 0)
    h4 = (s["xbudget"]["cells"] == CELLS and s["xbudget"]["over_cap"] == 0
          and s["xbudget"]["claims"] == 0 and s["xbudget"]["executed_total"] > 0)
    h5 = (s["ledger"]["duplicates"] == 0 and s["ledger"]["all_deltas_ok"])
    vals = {"H1_cross_process_parity": h1, "H2_cross_process_replay_refused": h2,
            "H3_cross_process_kill_zero_post_fence": h3,
            "H4_shared_budget_fails_closed": h4, "H5_shared_ledger_integrity": h5}
    verdict = ("CROSS_PROCESS_GOVERNANCE_EXACT" 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 / "E344P_RUN_REPORT.json").read_text())
    pre = json.loads((d / "E344P_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E344P_PREREGISTRATION_FREEZE.json").read_text())
    salts = json.loads((d / "E344P_SALT_REVEALED.json").read_text())
    ext = json.loads((d / "E344P_EXTERNAL_REVIEW_STATUS.json").read_text())
    dev = json.loads((d / "E344P_DEVIATIONS.json").read_text())
    man = json.loads((d / "E344P_MANIFEST.json").read_text())
    checks = []

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

    ck("schema", rep["schema"] == "cain42.e344p.run_report.v1")
    ck("evolution", rep["evolution"] == "E344-P")
    ck("status line", rep["status"] == S)
    ck("prereg hash", sha((d / "E344P_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_xp = ok_xr = ok_xk = ok_xb = True
    for r in allr:
        a = r["arms"]
        if set(a) != {"XPARITY", "XREPLAY", "XKILL", "XBUDGET"}:
            ok_xp = False
            continue
        xp = a["XPARITY"]
        ok_xp &= (xp["parity"] is True and xp["nonce_delta"] == xp["executed"]
                  and xp["executed"] == xp["permits"] == xp["unique_permits"])
        xr = a["XREPLAY"]
        ok_xr &= (xr["ok"] is False and "ALREADY_CONSUMED" in str(xr.get("why"))
                  and xr["nonce_delta"] == 0)
        xk = a["XKILL"]
        ok_xk &= (xk["killed"] is True and xk["decision"] == "REFUSE"
                  and (xk["post_fence_executed"] or 0) == max(0, xk["executed"] - xk["kill_at"])
                  and xk["still_authorized"] is False
                  and xk["nonce_delta"] == xk["executed"])
        xb = a["XBUDGET"]
        ok_xb &= (xb["total_executed"] <= xb["cap"] and xb["claims"] == 0
                  and all(w["decision"] == "REFUSE" for w in xb["workers"])
                  and xb["nonce_delta"] == xb["total_executed"])
    ck("xparity per cell", ok_xp)
    ck("xreplay per cell", ok_xr)
    ck("xkill per cell", ok_xk)
    ck("xbudget per cell", ok_xb)

    sqlite_path = d / "E344P_JIT_NONCES.json"
    n, dup = ledger(sqlite_path)
    sum_deltas = sum(r["arms"]["XPARITY"]["nonce_delta"] + r["arms"]["XKILL"]["nonce_delta"]
                     + r["arms"]["XBUDGET"]["nonce_delta"] for r in allr)
    ck("shipped nonce ledger", n == sum_deltas and dup == 0)

    pooled = summarize(allr, n, dup)
    prim = summarize(rep["sets"]["primary"]["rows"], n, dup)
    rep_s = summarize(rep["sets"]["replication"]["rows"], n, dup)
    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["xparity"]["matched"] == 4
       and rep_s["xreplay"]["refused"] == 4 and rep_s["xkill"]["killed"] == 4
       and rep_s["xbudget"]["claims"] == 0 and rep_s["xbudget"]["over_cap"] == 0)
    ck("external review blocked", rep["hypotheses"]["H6_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_NONCE_DB" in (d / "E344P_PREREGISTRATION.json").read_text())

    for salt, fname in (("primary", "E344P_CHAIN_PRIMARY.json"),
                        ("replication", "E344P_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 = ("xparity", "xreplay", "xkill", "xbudget", "ledger")
    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 / "E344P_PUBKEY.pem").read_bytes()) \
            if (d / "E344P_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", "shared.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 / "E344P_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())
