#!/usr/bin/env python3
"""E432-A standalone offline verifier. Imports no CAIN code.

Checks:
  * the signed evidence manifest and every declared file hash;
  * every exported memory chain: Ed25519 signatures, SHA-256 links, tenant and sequence;
  * every admission's stored behaviour against the arithmetic (false admissions, poison admissions);
  * the reported generation curves and hypotheses against the raw rows;
  * the verdict rule.
Record-level: it does not re-run the research search or the sealed evaluator.
"""
from __future__ import annotations
import hashlib, json, sys
from pathlib import Path

MOD = 1009
XS = [0, 1, 2, 3, 4, 5]
FUNCS = [
    lambda x: (x + 1) % MOD, lambda x: (x * 2) % MOD, lambda x: (x + 7) % MOD,
    lambda x: (x * x) % MOD, lambda x: (x * 3) % MOD, lambda x: (-x) % MOD,
    lambda x: (x + 13) % MOD, lambda x: (x * x * x + 1) % MOD,
]
S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"


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


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


def beh(ops):
    out = list(XS)
    for p in ops:
        out = [FUNCS[int(p)](x) for x in out]
    return out


def merkle(leaves):
    level = [bytes.fromhex(x) for x in leaves]
    if not level:
        return sha(b"")
    while len(level) > 1:
        nxt = []
        for i in range(0, len(level), 2):
            a = level[i]
            b = level[i + 1] if i + 1 < len(level) else a
            nxt.append(hashlib.sha256(a + b).digest())
        level = nxt
    return level[0].hex()


def main(argv=None):
    argv = argv or sys.argv[1:]
    d = Path(argv[0]).resolve() if argv else Path(__file__).resolve().parent
    checks = []

    def ok(name, cond, detail=""):
        checks.append({"check": name, "ok": bool(cond), "detail": str(detail)[:300]})

    r = json.loads((d / "E432A_RUN_REPORT.json").read_text())
    mem = [json.loads(x) for x in (d / "E432A_MEMORY.jsonl").read_text().splitlines() if x.strip()]
    pubs = json.loads((d / "E432A_PUBKEYS.json").read_text())
    salts = json.loads((d / "E432A_SALTS.json").read_text())
    man = json.loads((d / "E432A_EVIDENCE_MANIFEST.json").read_text())
    tam_p = d / "E432A_TAMPER_RESULTS.json"
    tam = json.loads(tam_p.read_text()) if tam_p.exists() else None

    ok("schema", r.get("schema") == "cain42.e432a.run.v2" and r.get("evolution") == "E432-A")
    ok("status_line", r.get("status") == S)
    ok("no_model_calls", r.get("model_calls") == 0)
    ok("two_salts", set(salts) == {"salt1", "salt2"})
    ok("salt_commitments", all(r["salts_commitment"][k] == sha(v.encode()) for k, v in salts.items()),
       r.get("salts_commitment"))

    # manifest
    files = man.get("files", {})
    missing = [n for n in files if not (d / n).is_file()]
    ok("manifest_files_present", not missing, missing)
    bad = [n for n, h in files.items() if (d / n).is_file() and sha((d / n).read_bytes()) != h]
    allowed_extra = {"MERKLE_ROOT.txt", "E432A_EVIDENCE_MANIFEST.json",
                     "E432A_VERIFICATION_RESULTS.json", "E432A_TAMPER_RESULTS.json"}
    extra = {p.name for p in d.iterdir() if p.is_file()} - set(files) - allowed_extra
    ok("no_extra_files", not extra, extra)
    ok("manifest_hashes", not bad, bad)
    leaves = [files[n] for n in sorted(files)]
    root = merkle(leaves)
    ok("manifest_merkle", root == man.get("merkle_root"), f"{root} vs {man.get('merkle_root')}")
    body = {k: man[k] for k in ("schema", "evolution", "created_at", "files", "merkle_root", "public_key")}
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["public_key"])).verify(
            bytes.fromhex(man["signature"]), canon(body))
        sig_ok = True
    except Exception as exc:  # noqa: BLE001
        sig_ok = False
        ok("manifest_signature_error", False, exc)
    ok("manifest_signature", sig_ok)

    # memory chains
    groups = {}
    for e in mem:
        groups.setdefault((e["salt"], e["arm"], e.get("db", ""), e["tenant"]), []).append(e)
    chains_ok = True
    sig_count = 0
    for key, rows in groups.items():
        rows.sort(key=lambda x: x["seq"])
        prev = "0" * 64
        for e in rows:
            payload = {k: e[k] for k in ("tenant", "seq", "agent", "kind", "key", "value", "prev", "created_at")}
            b = canon(payload)
            if e["prev"] != prev or sha(bytes.fromhex(e["sig"]) + b) != e["hash"]:
                chains_ok = False
                break
            try:
                from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
                Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubs[e["agent"]])).verify(
                    bytes.fromhex(e["sig"]), b)
                sig_count += 1
            except Exception:
                chains_ok = False
                break
            prev = e["hash"]
            if e["value"].get("grants_authority") or e["value"].get("executable"):
                chains_ok = False
    ok("memory_chains_and_signatures", chains_ok, f"{len(mem)} rows, {sig_count} signatures, {len(groups)} chains")

    # admissions and poison
    false_by, poison_by = {}, {}
    for e in mem:
        if e["kind"] != "admission":
            continue
        key = (e["salt"], e["arm"])
        actual = beh(e["value"].get("ops", []))
        claimed = e["value"].get("claimed_beh", [])
        if actual != claimed:
            false_by[key] = false_by.get(key, 0) + 1
        if e["value"].get("claim_agent") == "e420m-mallory":
            poison_by[key] = poison_by.get(key, 0) + 1
    verified_false = sum(v for (s, a), v in false_by.items() if a == "VERIFIED")
    verified_poison = sum(v for (s, a), v in poison_by.items() if a == "VERIFIED")
    trust_false = sum(v for (s, a), v in false_by.items() if a == "TRUST")
    trust_poison = sum(v for (s, a), v in poison_by.items() if a == "TRUST")
    audit_false = sum(v for (s, a), v in false_by.items() if a == "AUDIT")
    quorum_false = sum(v for (s, a), v in false_by.items() if a == "QUORUM")
    ok("verified_zero_false_admissions", verified_false == 0, verified_false)
    ok("verified_zero_poison_admissions", verified_poison == 0, verified_poison)
    ok("trust_admits_adaptive_poison", trust_poison == 6 and trust_false == 6, f"{trust_poison}/{trust_false}")
    ok("audit_false_admissions", audit_false == 0, audit_false)
    ok("quorum_zero_false_admissions", quorum_false == 0, quorum_false)

    # curves and headline
    h = r.get("headline", {})
    arms = r["arms"]
    for salt in ("salt1", "salt2"):
        for arm in ("ISOLATED", "TRUST", "AUDIT", "VERIFIED", "QUORUM"):
            curve = [g["sealed"]["solved"] for g in arms[salt][arm]["generations"]]
            ok(f"curve_{salt}_{arm}", curve == h.get(f"{arm.lower()}_{salt}", curve), curve)
    ok("headline_verified_salt1", h.get("verified_salt1") == [g["sealed"]["solved"] for g in arms["salt1"]["VERIFIED"]["generations"]])
    ok("headline_verified_salt2", h.get("verified_salt2") == [g["sealed"]["solved"] for g in arms["salt2"]["VERIFIED"]["generations"]])
    ok("headline_trusted_poison", h.get("trusted_poison_admitted") == 6 and h.get("trusted_false_admissions") == 6)
    ok("headline_verified_integrity", h.get("verified_poison_admitted") == 0 and h.get("verified_false_admissions") == 0)
    ok("verified_beats_isolated", all(
        h["verified_" + s][-1] >= h["isolated_" + s][-1] for s in ("salt1", "salt2")))

    H = r.get("hypotheses", {})
    ok("H1", H.get("H1_verified_integrity", {}).get("verdict") == "SUPPORTED")
    ok("H2", H.get("H2_trusted_memory_admits_adaptive_poison", {}).get("verdict") == "SUPPORTED")
    ok("H4", H.get("H4_two_attestation_quorum", {}).get("verdict") == "SUPPORTED")
    ok("H5", H.get("H5_bounded_compounding", {}).get("verdict") == "PARTIAL")
    ok("H7", H.get("H7_governance", {}).get("verdict") == "SUPPORTED")
    ok("verdict", r.get("verdict") == "ADAPTIVE_POISON_REJECTED_UNDER_VERIFICATION", r.get("verdict"))
    ok("tamper_post_seal", tam is None or (tam.get("rejected") == tam.get("count") and tam.get("count", 0) >= 8), tam or "not yet run")
    ok("external_review_honest", r.get("external_review") == "NOT_OBTAINED")

    passed = sum(1 for c in checks if c["ok"])
    result = {"schema": "cain42.e432a.verification.v1", "verifier": "verify_e432a_offline.py",
              "checks": checks, "passed": passed, "total": len(checks),
              "all_pass": passed == len(checks), "record_level": True,
              "note": "Record-level: verifies the signed record, chains, admissions and hypotheses; it does not re-run the search or sealed evaluator."}
    (d / "E432A_VERIFICATION_RESULTS.json").write_text(json.dumps(result, indent=1))
    for c in checks:
        print(("PASS " if c["ok"] else "FAIL ") + c["check"] + (f" :: {c['detail']}" if c["detail"] else ""))
    print(f"E432-A VERIFIED: {passed}/{len(checks)}")
    return 0 if result["all_pass"] else 1


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