#!/usr/bin/env python3
"""E405-Z standalone verifier — stdlib + cryptography, imports no CAIN code."""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
SCHEMA_ENTRY = "cain42.e404m.memory.entry.v1"
EX = {"E405Z_MANIFEST.json", "E405Z_SIGNED_BODY.json", "E405Z_VERIFICATION_RESULTS.json",
      "E405Z_TAMPER_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
      "E405Z_OMEGA_SEAL.json"}
AGENTS = 4
GENS = 6
PRE = 3
SALTS = ("primary", "replication")
ARMS = (("PERMANENT", "drift"), ("LEASE", "drift"), ("ISOLATED", "drift"))


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 mean(xs):
    return sum(xs) / len(xs) if xs else 0.0


def main() -> int:
    d = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    checks = []

    def ck(name, cond, note=""):
        checks.append((name, bool(cond), note))

    man = json.loads((d / "E405Z_MANIFEST.json").read_text())
    pre = json.loads((d / "E405Z_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E405Z_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((d / "E405Z_RUN_REPORT.json").read_text())
    salts = json.loads((d / "E405Z_SALTS_REVEALED.json").read_text())
    acc = json.loads((d / "E405Z_ACCEPTANCE_REGISTRY.json").read_text())

    ck("schema", man.get("schema") == "cain42.e405z.manifest.v1" and rep.get("evolution") == "E405-Z")

    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("files", set(man["files"]) == {str(p.relative_to(d)) for p in files})
    ck("hashes", all(sha(p.read_bytes()) == man["files"][str(p.relative_to(d))] for p in files))

    def merkle(paths):
        lv = sorted(sha(p.read_bytes()) for p in paths)
        if not lv:
            return sha(b"")
        while len(lv) > 1:
            if len(lv) % 2:
                lv.append(lv[-1])
            lv = [sha((lv[i] + lv[i + 1]).encode()) for i in range(0, len(lv), 2)]
        return lv[0]

    ck("merkle", man["merkle_root"] == merkle(files))
    ck("merkle file", (d / "MERKLE_ROOT.txt").read_text().strip() == man["merkle_root"])

    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
        bytes.fromhex(man["signature"]),
        canon(json.loads((d / "E405Z_SIGNED_BODY.json").read_text())))
    ck("signature", True)

    ck("freeze", sha((d / "E405Z_PREREGISTRATION.json").read_bytes()) ==
       frz["preregistration_sha256"] == rep["preregistration_sha256"])
    ck("salts revealed", all(sha(bytes.fromhex(v)) == pre["salt_commitment_sha256"][k]
                             for k, v in salts.items()))
    ck("source withheld", not any(q.name in ("run.py", "worker.py", "memory.py", "strategies.py")
                                  for q in d.rglob("*") if q.is_file()))

    bad_sig = bad_hash = bad_chain = dup_nonce = entries = 0
    for run in rep["runs"]:
        prev = ""
        seen = set()
        pubs = run["pubkeys"]
        for r in run["memory_export"]:
            entries += 1
            entry = {"schema": SCHEMA_ENTRY, "tenant": r["tenant"], "agent": r["agent"],
                     "kind": r["kind"], "key": r["key"], "value": r["value"],
                     "confidence": float(r["confidence"]), "nonce": r["nonce"],
                     "prev_hash": r["prev_hash"], "created_at": r["created_at"]}
            payload = canon(entry)
            if sha(payload + bytes.fromhex(r["sig"])) != r["entry_hash"]:
                bad_hash += 1
            try:
                Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubs[r["agent"]])).verify(
                    bytes.fromhex(r["sig"]), payload)
            except Exception:  # noqa: BLE001
                bad_sig += 1
            if r["prev_hash"] != prev:
                bad_chain += 1
            prev = r["entry_hash"]
            if r["nonce"] in seen:
                dup_nonce += 1
            seen.add(r["nonce"])
    ck("memory entries", entries > 0 and bad_hash == 0 and bad_sig == 0 and bad_chain == 0
       and dup_nonce == 0, f"{entries} entries")

    rows = [a for run in rep["runs"] for a in run["rows"]]
    ck("row count", len(rows) == len(SALTS) * len(ARMS) * AGENTS * GENS, f"{len(rows)} rows")
    ck("no model calls", rep["constants"]["model_calls"] == 0 and rep["constants"]["api_calls"] == 0)

    def summary(policy, salt):
        rs = [r for r in rows if r["policy"] == policy and r["salt"] == salt]
        m = {g: mean([r["sealed_accepted"] for r in rs if r["gen"] == g])
             for g in sorted({r["gen"] for r in rs})}
        return {"pre": mean([m[g] for g in m if g <= PRE]),
                "post": mean([m[g] for g in m if g > PRE]),
                "gap": mean([r["stored_accepted"] - r["sealed_accepted"]
                             for r in rs if r["gen"] == PRE + 1]),
                "fa": sum(r["sealed_false_accept"] for r in rs),
                "labels": sum(r["labels"] for r in rs)}

    def champ(run):
        best = None
        for r in run["memory_export"]:
            try:
                v = json.loads(r["value"])
            except ValueError:
                continue
            if int(v.get("gen") or 0) > PRE:
                continue
            dv = v.get("dev") or {}
            sc = int(dv.get("accepted", 0)) * 100_000 - int(dv.get("queries", 0))
            if best is None or sc > best[0]:
                best = (sc, v["strategy"]["arm"])
        return best[1] if best else None

    diag = {s: {p: summary(p, s) for p in ("PERMANENT", "LEASE", "ISOLATED")} for s in SALTS}
    champions = {s: champ(next(r for r in rep["runs"] if r["salt"] == s and r["policy"] == "PERMANENT"))
                 for s in SALTS}
    h0 = all(champions[s] == "single" for s in SALTS)
    h1 = all(diag[s]["PERMANENT"]["pre"] > 0 and
             diag[s]["PERMANENT"]["post"] <= 0.5 * diag[s]["PERMANENT"]["pre"] for s in SALTS)
    h2 = all(diag[s]["LEASE"]["post"] > diag[s]["PERMANENT"]["post"] and
             diag[s]["LEASE"]["post"] >= 0.8 * diag[s]["LEASE"]["pre"] for s in SALTS)
    h3 = all(diag[s]["PERMANENT"]["gap"] >= 2.0 for s in SALTS)
    h4 = all(diag[s][p]["fa"] == 0 for s in SALTS for p in ("PERMANENT", "LEASE", "ISOLATED"))
    lcost = sum(diag[s]["LEASE"]["labels"] for s in SALTS)
    pcost = sum(diag[s]["PERMANENT"]["labels"] for s in SALTS)
    h5 = lcost <= 4.0 * pcost
    h6 = all(all(bool(run["summary"]["memory_probes"].get(k)) for k in
                 ("chain_ok", "forge_refused", "replay_refused", "tamper_detected",
                  "tenant_isolated", "authority_refused")) for run in rep["runs"])
    h7 = h1 and h2
    if not h0:
        verdict = "PRECONDITION_NOT_MET"
    elif all((h1, h2, h3, h4, h5, h6, h7)):
        verdict = "MEMORY_IS_A_HYPOTHESIS_SUPPORTED"
    elif h2 and h4 and h6:
        verdict = "PARTIAL"
    else:
        verdict = "NOT_SUPPORTED"

    hv = rep["hypotheses"]
    ck("H0 recomputed", (hv["H0_precondition_champion_is_the_fragile_single_procedure"]["verdict"]
                         == "SUPPORTED") == h0, str(champions))
    ck("H1 recomputed", (hv["H1_remembered_champion_stales_under_drift"]["verdict"] == "SUPPORTED") == h1)
    ck("H2 recomputed", (hv["H2_lease_recovers_after_drift"]["verdict"] == "SUPPORTED") == h2)
    ck("H3 recomputed", (hv["H3_stale_score_is_the_mechanism"]["verdict"] == "SUPPORTED") == h3)
    ck("H4 recomputed", (hv["H4_no_false_accepts_in_any_arm"]["verdict"] == "SUPPORTED") == h4)
    ck("H5 recomputed", (hv["H5_lease_cost_is_bounded"]["verdict"] == "SUPPORTED") == h5)
    ck("H6 recomputed", (hv["H6_memory_integrity_isolation_and_no_authority"]["verdict"] == "SUPPORTED") == h6)
    ck("H7 recomputed", (hv["H7_replication_both_salts"]["verdict"] == "SUPPORTED") == h7)
    ck("H8 blocked", hv["H8_external_review"]["verdict"] == "BLOCKED")
    ck("verdict", rep["verdict"] == verdict, verdict)
    ck("acceptance", acc["verdict"] == verdict and acc["model_calls"] == 0)
    ck("status line", rep["status"] == S and pre["status"] == S)
    ck("limits", len(rep["limits"]) >= 8)

    passed = sum(1 for _, ok, _ in checks if ok)
    for name, ok, note in checks:
        print(("PASS " if ok else "FAIL ") + name + (f" [{note}]" if note else ""))
    print(f"{passed}/{len(checks)} checks passed")
    return 0 if passed == len(checks) else 1


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