#!/usr/bin/env python3
"""E457-C standalone auditor (imports no CAIN code).

Recomputes every arm and hypothesis from the per-task rows, re-verifies the signed memory chain
from the study key derivation, checks the card compression and poison accounting, and the
signed manifest.
"""
import hashlib
import json
import sys
from pathlib import Path

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

TENANT = "cain42-e457c"
SEED = "e457c"
ARMS = ["FULL", "CARD", "RANDOM", "PRIMITIVES", "CARD_UNVERIFIED", "CARD_VERIFIED"]
N_TASKS = 24


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


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


def pub(agent):
    k = Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"{SEED}|{agent}".encode()).digest())
    return k.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw).hex()


def verify_entries(entries):
    prev, bad = "", 0
    for e in entries:
        payload = {k: e[k] for k in ("seq", "tenant", "agent", "kind", "key", "value", "prev",
                                     "created_at", "grants_authority", "executable")}
        body = canon(payload)
        ok = (e["prev"] == "" or e["prev"] == prev) and e["tenant"] == TENANT
        ok = ok and sha(e["prev"].encode() + body + bytes.fromhex(e["sig"])) == e["hash"]
        if ok:
            try:
                Ed25519PublicKey.from_public_bytes(bytes.fromhex(pub(e["agent"]))).verify(
                    bytes.fromhex(e["sig"]), body)
            except Exception:
                ok = False
        if not ok:
            bad += 1
        prev = e["hash"]
    return bad


def main():
    d = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    rep = json.loads((d / "E457C_RUN_REPORT.json").read_text())
    salts = json.loads((d / "SALTS.json").read_text())
    frz = json.loads((d / "E457C_PREREGISTRATION_FREEZE.json").read_text())
    checks = []

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

    ck("prereg hash", sha((d / "E457C_PREREGISTRATION.json").read_bytes()) == frz["preregistration_sha256"])
    ck("salt commitment", all(sha(salts[k].encode()) == frz["salt_commitments"][k] for k in ("salt1", "salt2")))
    ck("status", rep["status"] == "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL")

    rows = rep["rows"]
    ck("row count", len(rows) == 2 * N_TASKS * len(ARMS))
    ck("row success bits", all(r["success"] in (0, 1) for r in rows))
    for sn in ("salt1", "salt2"):
        for a in ARMS:
            sub = [r for r in rows if r["salt"] == sn and r["arm"] == a]
            s = sum(r["success"] for r in sub)
            ck(f"{sn} {a}", len(sub) == N_TASKS and rep["salts"][sn]["counts"][a] == s
               and abs(rep["salts"][sn]["rates"][a] - s / N_TASKS) < 1e-6)

    s1, s2 = rep["salts"]["salt1"], rep["salts"]["salt2"]

    def H1():
        return s1["counts"]["CARD"] == 24 and s2["counts"]["CARD"] == 24

    def H2():
        return s1["ratio"] <= 0.60 and s2["ratio"] <= 0.60

    def H3():
        return ((s1["counts"]["CARD"] - s1["counts"]["RANDOM"]) / N_TASKS >= 0.15
                and (s2["counts"]["CARD"] - s2["counts"]["RANDOM"]) / N_TASKS >= 0.15)

    def H4():
        return (s1["counts"]["CARD"] >= 22.8 and s2["counts"]["CARD"] >= 22.8
                and s1["counts"]["PRIMITIVES"] <= 2.4 and s2["counts"]["PRIMITIVES"] <= 2.4)

    def H5():
        return (s1["counts"]["CARD_VERIFIED"] == 24 and s2["counts"]["CARD_VERIFIED"] == 24
                and s1["counts"]["CARD_UNVERIFIED"] < 24 and s2["counts"]["CARD_UNVERIFIED"] < 24)

    def H6():
        return all(all(v for k, v in rep["governance"][sn].items() if isinstance(v, bool))
                   for sn in ("salt1", "salt2"))

    exp = {"H1_card_exact": H1(), "H2_compression": H2(), "H3_selection_matters": H3(),
           "H4_cold_start_transfer": H4(), "H5_poison_rejected": H5(), "H6_governance": H6()}
    for k, v in exp.items():
        ck(k, rep["hypotheses"][k]["verdict"] == ("SUPPORTED" if v else "NOT_SUPPORTED"))
    ck("H7 blocked", rep["hypotheses"]["H7_external_review"]["verdict"] == "BLOCKED")
    expected = "SKILL_CARD_TRANSFER_SUPPORTED" if all(exp.values()) else "NOT_SUPPORTED"
    ck("verdict", rep["verdict"] == expected)

    ck("ratio arithmetic", all(abs(rep["salts"][sn]["ratio"] - rep["salts"][sn]["card"] / rep["salts"][sn]["library"]) < 1e-12
                               for sn in ("salt1", "salt2")))
    ck("poison accounting", all(rep["salts"][sn]["poison"]["rejected"] for sn in ("salt1", "salt2")))
    ck("poison used", all(rep["salts"][sn]["poison"]["behaviour_used_by"] >= 1 for sn in ("salt1", "salt2")))

    entries = rep.get("raw_entries", [])
    ck("memory entries", len(entries) == rep["measurements"]["entries"])
    ck("memory chain", verify_entries(entries) == 0)
    ck("no authority", all(e["grants_authority"] is False and e["executable"] is False for e in entries))
    ck("no model calls", rep["measurements"].get("model_calls") == 0)

    manp = d / "E457C_MANIFEST.json"
    if manp.exists():
        man = json.loads(manp.read_text())
        body = {k: v for k, v in man.items() if k != "signature"}
        try:
            Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
                bytes.fromhex(man["signature"]), canon(body))
            ck("manifest signature", True)
        except Exception:
            ck("manifest signature", False)
        ck("manifest hashes", {k: sha((d / k).read_bytes()) for k in man["files"]} == man["files"])
        leaves = sorted(man["files"].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)]
        ck("merkle", leaves[0] == man["merkle_root"])
        ck("engine withheld", not (d / "run.py").exists() and not (d / "domain.py").exists()
           and not (d / "memory.py").exists())
        extra = {"PUBLICATION.json", "E457C_OMEGA_SEAL.json", "MANIFEST.json", "MERKLE_ROOT.txt",
                 "E457C_PUBKEY.pem", "E457C_SIGNED_BODY.json", "E457C_VERIFICATION_RESULTS.json",
                 "E457C_TAMPER_RESULTS.json", "E457C_MANIFEST.json"}
        actual = {str(p.relative_to(d)) for p in d.rglob("*") if p.is_file() and "__pycache__" not in p.parts}
        ck("no unexpected files", actual <= (set(man["files"]) | extra))

    fails = [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(fails)}/{len(checks)} checks passed")
    return 0 if not fails else 1


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