#!/usr/bin/env python3
"""E459-C standalone auditor (imports no CAIN code)."""
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-e459c"
SEED = "e459c"
WORLDS = 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 / "E459C_RUN_REPORT.json").read_text())
    salts = json.loads((d / "SALTS.json").read_text())
    frz = json.loads((d / "E459C_PREREGISTRATION_FREEZE.json").read_text())
    checks = []

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

    ck("prereg hash", sha((d / "E459C_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)
    ok_rows = True
    for r in rows:
        if r["contrast_size"] != len(r["contrast"]) or not r["contrast"]:
            ok_rows = False
        if any(not (0 <= i < 48) for i in r["contrast"]):
            ok_rows = False
        if r["sufficient"] is not True or r["minimal"] is not True:
            ok_rows = False
        if not (0.0 <= r["random_reproduction"] <= 1.0):
            ok_rows = False
        if r["verified_winner"] != r["winner"]:
            ok_rows = False
    ck("row consistency", ok_rows)

    for sn in ("salt1", "salt2"):
        sub = [r for r in rows if r["salt"] == sn]
        S = rep["salts"][sn]
        ck(f"{sn} worlds", len(sub) == WORLDS)
        ck(f"{sn} contrast mean", abs(S["mean_contrast"] - sum(r["contrast_size"] for r in sub) / WORLDS) < 1e-9)
        ck(f"{sn} cause mean", abs(S["mean_cause"] - sum(r["cause_size"] for r in sub) / WORLDS) < 1e-9)
        ck(f"{sn} random mean", abs(S["mean_random_reproduction"] - sum(r["random_reproduction"] for r in sub) / WORLDS) < 1e-9)
        ck(f"{sn} spans", S["spans_two_plus"] == sum(1 for r in sub if r["span"] >= 2))
        ck(f"{sn} sufficient", S["sufficient"] == sum(1 for r in sub if r["sufficient"]))
        ck(f"{sn} minimal", S["minimal"] == sum(1 for r in sub if r["minimal"]))
        ck(f"{sn} gt cause", S["contrast_gt_cause"] == sum(1 for r in sub if r["contrast_size"] > r["cause_size"]))
        ck(f"{sn} poison wins", S["poison_wins"] == sum(1 for r in sub if r["poison_winner"] == r["poison_candidate"]))
        ck(f"{sn} poison contrast", S["poison_in_contrast"] == sum(1 for r in sub if r["poison_in_contrast"]))
        ck(f"{sn} poison rejected", S["poison_rejected"] == sum(1 for r in sub if r["poison_rejected"]))
        ck(f"{sn} verified", S["verified_ok"] == sum(1 for r in sub if r["verified_winner"] == r["winner"] and r["poison_rejected"]))

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

    def H1():
        return all(x[k] == WORLDS for x in (s1, s2) for k in ("sufficient", "minimal"))

    def H2():
        return s1["mean_contrast"] <= 0.40 * 48 and s2["mean_contrast"] <= 0.40 * 48

    def H3():
        return s1["mean_random_reproduction"] <= 0.50 and s2["mean_random_reproduction"] <= 0.50

    def H4():
        return s1["spans_two_plus"] >= 0.8 * WORLDS and s2["spans_two_plus"] >= 0.8 * WORLDS

    def H5():
        return s1["contrast_gt_cause"] >= 0.8 * WORLDS and s2["contrast_gt_cause"] >= 0.8 * WORLDS

    def H6():
        return (all(x["poison_wins"] >= 0.9 * WORLDS and x["poison_in_contrast"] >= WORLDS
                    and x["poison_rejected"] == WORLDS and x["verified_ok"] == WORLDS for x in (s1, s2)))

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

    exp = {"H1_sufficient_minimal": H1(), "H2_compression": H2(), "H3_selection": H3(),
           "H4_cross_agent": H4(), "H5_pairwise_costs_more": H5(), "H6_poison": H6(), "H7_governance": H7()}
    for k, v in exp.items():
        ck(k, rep["hypotheses"][k]["verdict"] == ("SUPPORTED" if v else "NOT_SUPPORTED"))
    ck("H8 blocked", rep["hypotheses"]["H8_external_review"]["verdict"] == "BLOCKED")
    expected = "CONTRAST_SET_EXPLANATION_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))
    ck("no model calls", rep["measurements"].get("model_calls") == 0)

    manp = d / "E459C_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", "E459C_OMEGA_SEAL.json", "MANIFEST.json", "MERKLE_ROOT.txt",
                 "E459C_PUBKEY.pem", "E459C_SIGNED_BODY.json", "E459C_VERIFICATION_RESULTS.json",
                 "E459C_TAMPER_RESULTS.json", "E459C_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())
