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

Recomputes every arm aggregate and every hypothesis from the per-world rows, re-verifies the
signed memory chain (Ed25519 + SHA-256) from the study key derivation, checks the parity
replication, the governance probes, the salt commitments 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-e455r"
SEED = "e455r"
AGENTS = ["alpha", "beta", "gamma", "delta", "mallory", "verifier"]
ARMS = ["FIXED", "RACE", "SHARED", "INDEPENDENT", "UNVERIFIED", "VERIFIED"]
WORLDS = 48


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)
        is_start = e["prev"] == ""
        ok = (is_start 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 / "E455R_RUN_REPORT.json").read_text())
    salts = json.loads((d / "SALTS.json").read_text())
    pre = json.loads((d / "E455R_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E455R_PREREGISTRATION_FREEZE.json").read_text())
    checks = []

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

    ck("prereg hash", sha((d / "E455R_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 * WORLDS * len(ARMS))
    ok_rows = True
    for r in rows:
        if r["success"] != int(r["promoted"] == r["best"]):
            ok_rows = False
        if not (0 <= r["best"] < 120 and 0 <= r["promoted"] < 120 and 0 <= r["poison_id"] < 120):
            ok_rows = False
        if abs(r["gap"] - round(r["best_acc"] - r["second_acc"], 6)) > 1e-9:
            ok_rows = False
        if not (1 <= r["experiments"] <= 2000):
            ok_rows = False
    ck("row consistency", ok_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} count", len(sub) == WORLDS and rep["arms"][sn][a]["success"] == s
               and abs(rep["arms"][sn][a]["rate"] - s / WORLDS) < 1e-12)

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

    def H1():
        return (s1["RACE"]["rate"] - s1["FIXED"]["rate"] >= 0.10
                and s2["RACE"]["rate"] - s2["FIXED"]["rate"] >= 0.10)

    def H2():
        return (s1["SHARED"]["rate"] >= s1["INDEPENDENT"]["rate"] - 0.02
                and s2["SHARED"]["rate"] >= s2["INDEPENDENT"]["rate"] - 0.02)

    def H3():
        return s1["UNVERIFIED"]["rate"] <= 0.10 and s2["UNVERIFIED"]["rate"] <= 0.10

    def H4():
        return (s1["VERIFIED"]["rate"] >= max(0.85, s1["SHARED"]["rate"] - 0.001)
                and s2["VERIFIED"]["rate"] >= max(0.85, s2["SHARED"]["rate"] - 0.001))

    pr = rep.get("parity_replication", {})
    praw = pr.get("rows", [])
    pcount_r = sum(r["race"] for r in praw)
    pcount_s = sum(r["shared"] for r in praw)
    ck("parity rows", len(praw) == 192 and pr["race"] == pcount_r and pr["shared"] == pcount_s)
    ck("parity rates", abs(pr["race_rate"] - pcount_r / 192) < 1e-12
       and abs(pr["shared_rate"] - pcount_s / 192) < 1e-12
       and abs(pr["diff"] - (pcount_s - pcount_r) / 192) < 1e-12)

    def H5b():
        return abs(pr.get("diff", 1)) <= 0.08

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

    exp = {"H1_racing_beats_fixed": H1(), "H2_shared_non_inferior": H2(), "H3_unverified_poisoned": H3(),
           "H4_verified_resists": H4(), "H5b_parity_replication": H5b(), "H6_governance": H6()}
    for k, v in exp.items():
        ck(k, rep["hypotheses"][k]["verdict"] == ("SUPPORTED" if v else "NOT_SUPPORTED"))
    ck("H5 descriptive", rep["hypotheses"]["H5_equal_budget_parity"]["verdict"] == "DESCRIPTIVE")
    ck("H7 blocked", rep["hypotheses"]["H7_external_review"]["verdict"] == "BLOCKED")
    expected = "SEQUENTIAL_GOVERNED_RSI_SUPPORTED" if all(exp.values()) else "NOT_SUPPORTED"
    ck("verdict", rep["verdict"] == expected)

    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))

    # no model calls: the domain block names deterministic agents and no provider
    ck("no model calls", "model" not in rep["domain"] and rep["domain"]["agents"] == ["alpha", "beta", "gamma", "delta"])

    manp = d / "E455R_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", "E455R_OMEGA_SEAL.json", "MANIFEST.json", "MERKLE_ROOT.txt",
                 "E455R_PUBKEY.pem", "E455R_SIGNED_BODY.json", "E455R_VERIFICATION_RESULTS.json",
                 "E455R_TAMPER_RESULTS.json", "E455R_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())
