#!/usr/bin/env python3
"""E420-X standalone auditor. Imports no CAIN code.

Recomputes: the memory chain and signatures for every arm, every macro's behaviour, every sealed
target from its primitive ops, every reported program on the sealed inputs, the counts and
hypotheses, the attestation firewall accounting, the poison outcomes, the no-authority read flags,
and the bundle manifest/Merkle root.
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

MOD = 1009
XS = [0, 1, 2, 3, 4, 5]
PRIMS = [
    ("add1", lambda x: (x + 1) % MOD),
    ("add7", lambda x: (x + 7) % MOD),
    ("mul2", lambda x: (x * 2) % MOD),
    ("square", lambda x: (x * x) % MOD),
    ("cube1", lambda x: (x * x * x + 1) % MOD),
    ("neg", lambda x: (-x) % MOD),
]
F = [f for _, f in PRIMS]
AGENTS = ("alpha", "beta", "gamma")
ATTESTORS = ("delta", "epsilon")
TENANT = "cain42-e420x"
ARMS = ("ISOLATED", "SHARED", "FIREWALLED", "FIREWALLED_POISON")
S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"


def sha(b):
    return hashlib.sha256(b.encode() if isinstance(b, str) else b).hexdigest()


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


def beh(ops, xs=None):
    b = list(XS if xs is None else xs)
    for i in ops:
        b = [F[int(i)](x) for x in b]
    return tuple(b)


def apply_program(program, xs):
    b = list(xs)
    for kind, val in program:
        ops = [int(val)] if kind == "p" else list(val)
        for i in ops:
            b = [F[int(i)](x) for x in b]
    return tuple(b)


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

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

    ck("schema", rep.get("schema") == "cain42.e420x.run.v1")
    ck("evolution", rep.get("evolution") == "E420-X")
    ck("status line", rep.get("status") == S)
    ck("salt commitments", all(rep["salts_commitment"][k] == sha(v.encode()) for k, v in salts.items()))
    ck("keyseed commitment shape", len(rep["salts_commitment"].get("keyseed", "")) == 64)

    prep = d / "E420X_PREREGISTRATION.json"
    frzp = d / "E420X_PREREGISTRATION_FREEZE.json"
    if prep.exists() and frzp.exists():
        frz = json.loads(frzp.read_text())
        ck("preregistration hash", sha(prep.read_bytes()) == frz["preregistration_sha256"])
        ck("salt commitments frozen", frz["salt_commitments"] == rep["salts_commitment"])
        ck("engine hashes frozen", "cain/cain2027/e420x/run.py" in frz["engine_sha256"])

    # ---- memory chains per arm --------------------------------------------------------------
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    from cryptography.exceptions import InvalidSignature

    def chain(entries, pubs):
        prev = ""
        bad = []
        for e in entries:
            body = canon({"schema": "cain42.e420x.memory.entry.v1", "tenant": e["tenant"], "seq": e["seq"],
                          "agent": e["agent"], "kind": e["kind"], "key": e["key"], "payload": e["payload"],
                          "uncertainty": e["uncertainty"], "verification": e["verification"],
                          "nonce": e["nonce"], "prev_hash": e["prev_hash"], "created_at": e["created_at"]})
            ok = e["prev_hash"] == prev and sha(e["prev_hash"].encode() + body + bytes.fromhex(e["sig"])) == e["entry_hash"]
            if ok:
                try:
                    Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubs[e["agent"]])).verify(
                        bytes.fromhex(e["sig"]), body)
                except (InvalidSignature, ValueError, KeyError):
                    ok = False
            if not ok:
                bad.append(e["seq"])
            prev = e["entry_hash"]
        return bad

    pubs = rep["raw"]["pubs"]
    all_ok = True
    for arm in ARMS:
        entries = rep["raw"]["entries_all"][arm]
        if arm == "ISOLATED":
            groups = {}
            for e in entries:
                groups.setdefault(e["agent"], []).append(e)
            bad = []
            for a, g in groups.items():
                bad += chain(g, {a: pubs[a]})
        else:
            bad = chain(entries, pubs)
        all_ok &= not bad
    ck("memory chains and signatures (all arms)", all_ok)
    ck("entry counts", {a: len(rep["raw"]["entries_all"][a]) for a in ARMS} == rep["raw"]["entries_by_arm"])

    # ---- read flags and authority ----------------------------------------------------------
    rs = rep["raw"]["read_sample"]
    ck("read sample non-authorizing", bool(rs) and all(
        (not h["grants_authority"]) and h["authority_effect"] == "none" and (not h["executable"]) for h in rs))
    probes = rep["measurements"]["probes"]
    ck("authority refused every attempt", probes["authority_refused"] == probes["authority_attempts"] > 0)
    ck("cross-tenant refusals", probes["cross_tenant_write_refused"] and probes["cross_tenant_read_refused"])
    ck("tamper detected", probes["tamper_detected"] is True)

    # ---- libraries -------------------------------------------------------------------------
    lib_ok = True
    for arm in ARMS:
        for a, L in rep["raw"]["libraries"][arm].items():
            for e in L:
                lib_ok &= tuple(e["beh"]) == beh(e["ops"])
                lib_ok &= not e["key"].startswith("poison")
    ck("library behaviours recompute", lib_ok)

    # ---- sealed evaluations ----------------------------------------------------------------
    counts = {}
    sealed_ok = True
    for arm in ARMS:
        counts[arm] = {}
        for salt in ("salt1", "salt2"):
            g2 = g3 = 0
            for kind in ("gen2", "gen3"):
                for rec in rep["raw"]["sealed"][arm][salt][kind]:
                    xs = [p[0] for p in rec["target"]]
                    ys = [p[1] for p in rec["target"]]
                    true_b = beh(rec["ops"], xs)
                    sealed_ok &= tuple(ys) == true_b
                    got = apply_program(rec["program"], xs) if rec["program"] else None
                    solved = got == true_b
                    sealed_ok &= solved == rec["solved"]
                    if solved:
                        if kind == "gen2":
                            g2 += 1
                        else:
                            g3 += 1
            counts[arm][salt] = {"gen2": g2, "gen3": g3, "total": g2 + g3,
                                 "gen2_total": len(rep["raw"]["sealed"][arm][salt]["gen2"]),
                                 "gen3_total": len(rep["raw"]["sealed"][arm][salt]["gen3"])}
    ck("sealed targets and programs", sealed_ok)
    ck("sealed counts", counts == rep["measurements"]["counts"])

    # ---- firewall --------------------------------------------------------------------------
    fw_entries = rep["raw"]["entries_all"]["FIREWALLED"]
    genuine = {}
    for a, L in rep["raw"]["libraries"]["FIREWALLED"].items():
        for e in L:
            genuine[e["key"]] = e
    genuine_gate = True
    for k, e in genuine.items():
        att = {x["agent"] for x in fw_entries
               if x["kind"] == "attestation" and x["payload"].get("macro_key") == k and x["agent"] != e["owner"]}
        use = {x["agent"] for x in fw_entries if x["kind"] == "mission_use" and x["payload"].get("macro_key") == k}
        genuine_gate &= len(att) >= 2 and len(use) >= 2
    ck("genuine macros pass the gate", genuine_gate)
    poison = rep["raw"]["poison"]
    fw_records = poison.get("firewall", [])
    fw_ok = True
    for rec in fw_records:
        k = rec["key"]
        att = {x["agent"] for x in fw_entries
               if x["kind"] == "attestation" and x["payload"].get("macro_key") == k and x["agent"] != "mallory"}
        use = {x["agent"] for x in fw_entries if x["kind"] == "mission_use" and x["payload"].get("macro_key") == k}
        usable = len(att) >= 2 and len(use) >= 2
        fw_ok &= (usable == rec["usable"]) and (not usable)
    ck("fabricated credentials refused", fw_ok and len(fw_records) >= 2)
    rec_rows = poison.get("recompute", [])
    ck("wrong behaviour refused", any(r["key"] == "poison-wrong" and not r["admitted"] and r["claimed"] != r["actual"] for r in rec_rows))
    ck("poison out of the library", poison.get("library_tainted") == []
       and all(not k.startswith("poison") for k in genuine))
    ck("promotion refused", all(p["authority"].startswith("REFUSED") for p in poison.get("promotions", [])))
    ck("no false refusals", rep["measurements"]["firewall"]["false_refusals"] == [])

    # ---- hypotheses and verdict ------------------------------------------------------------
    H = rep["hypotheses"]
    rules = {
        "H1_cross_mission_gap": counts["SHARED"]["salt1"]["total"] >= 30 and counts["ISOLATED"]["salt1"]["total"] <= 6,
        "H2_firewall_no_loss": counts["FIREWALLED"]["salt1"]["total"] >= 30
                               and counts["FIREWALLED"]["salt1"]["total"] >= counts["SHARED"]["salt1"]["total"] - 2,
        "H3_firewall_refuses_fabrication": fw_ok and len(fw_records) >= 2
                                           and any(r["key"] == "poison-wrong" and not r["admitted"] for r in rec_rows)
                                           and all(p["authority"].startswith("REFUSED") for p in poison.get("promotions", []))
                                           and poison.get("library_tainted") == []
                                           and rep["measurements"]["firewall"]["false_refusals"] == [],
        "H4_integrity_and_no_authority": all_ok and bool(rs) and all(
            (not h["grants_authority"]) and h["authority_effect"] == "none" and (not h["executable"]) for h in rs)
            and probes["cross_tenant_write_refused"] and probes["cross_tenant_read_refused"]
            and probes["tamper_detected"] and probes["authority_refused"] == probes["authority_attempts"] > 0,
        "H5_replication": counts["SHARED"]["salt2"]["total"] >= 30 and counts["ISOLATED"]["salt2"]["total"] <= 6
                          and counts["FIREWALLED"]["salt2"]["total"] >= 30,
        "H6_external_review": H["H6_external_review"]["verdict"] == "BLOCKED",
    }
    ck("hypotheses", all(H[k]["verdict"] == ("SUPPORTED" if v else "NOT_SUPPORTED") for k, v in rules.items() if k != "H6_external_review")
       and H["H6_external_review"]["verdict"] == "BLOCKED")
    verdict = "CROSS_MISSION_ATTESTATION_FIREWALL_SUPPORTED" if all(rules.values()) else "NOT_SUPPORTED"
    ck("verdict", rep["verdict"] == verdict)

    # ---- bundle manifest -------------------------------------------------------------------
    manp = d / "E420X_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 root", leaves[0] == man["merkle_root"])
        ck("engine withheld", not (d / "run.py").exists())
        extra = {"PUBLICATION.json", "E420X_OMEGA_SEAL.json", "MANIFEST.json", "MERKLE_ROOT.txt",
                 "E420X_PUBKEY.pem", "E420X_SIGNED_BODY.json", "E420X_VERIFICATION_RESULTS.json",
                 "E420X_TAMPER_RESULTS.json", "E420X_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())
