#!/usr/bin/env python3
"""E421-D standalone auditor (no CAIN imports).

Re-derives the study keys, re-verifies the signed memory chain, re-applies every returned program,
recomputes the 2-of-3 quorum, the fault drill, the isolated coverage, the baseline, the development
curve and the verdict, then checks the signed manifest.
"""
import hashlib
import json
import sys
from pathlib import Path

MOD = 1009
XS = [0, 1, 2, 3, 4, 5]
PRIMS = [lambda x: (x + 1) % MOD, lambda x: (x + 7) % MOD, lambda x: (x * 2) % MOD,
         lambda x: (x * x) % MOD, lambda x: (x * x * x + 1) % MOD, lambda x: (-x) % MOD]
AGENTS = ["atlas", "borealis", "cetus", "draco", "eris", "faun", "mallory"]
TENANT = "cain42-e421d"


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


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


def beh(ops):
    b = list(XS)
    for i in ops:
        b = [PRIMS[i](x) for x in b]
    return tuple(b)


def apply_program(prog, lib):
    b = list(XS)
    for s in prog or []:
        ops = [s] if isinstance(s, int) else lib[s]["ops"]
        for i in ops:
            b = [PRIMS[i](x) for x in b]
    return tuple(b)


def baseline(target):
    def rec(p):
        if p and beh(p) == target:
            return p
        if len(p) == 3:
            return None
        for i in range(6):
            r = rec(p + [i])
            if r is not None:
                return r
        return None
    return rec([])


def main():
    d = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
    rep = json.loads((d / "E421D_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.e421d.run.v1")
    ck("evolution", rep.get("evolution") == "E421-D")
    ck("status", rep.get("status") == "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL")
    ck("salts", rep["salts_commitment"] == {k: sha(v.encode()) for k, v in salts.items()})
    prep = d / "E421D_PREREGISTRATION.json"
    frzp = d / "E421D_PREREGISTRATION_FREEZE.json"
    if prep.exists() and frzp.exists():
        frz = json.loads(frzp.read_text())
        ck("prereg hash", sha(prep.read_bytes()) == frz["preregistration_sha256"])
        ck("salts frozen", frz["salt_commitments"] == rep["salts_commitment"])

    entries = rep["raw"]["entries"]
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
    pubs = {a: Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"e421d|{a}".encode()).digest())
            .public_key().public_bytes_raw().hex() for a in AGENTS}
    prev, bad = "", []
    for e in entries:
        payload = {k: e[k] for k in ("seq", "tenant", "agent", "kind", "key", "value", "prev", "created_at")}
        body = canon(payload)
        ok = e["prev"] == prev and sha(e["prev"].encode() + body + bytes.fromhex(e["sig"])) == e["hash"]
        if ok:
            try:
                Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubs[e["agent"]])).verify(
                    bytes.fromhex(e["sig"]), body)
            except Exception:
                ok = False
        if not ok:
            bad.append(e["seq"])
        prev = e["hash"]
    ck("chain and signatures", not bad and [e["seq"] for e in entries] == list(range(1, len(entries) + 1)))
    ck("tenant constant", all(e["tenant"] == TENANT for e in entries))

    full = {x["key"]: x for x in rep["raw"]["libraries"]["full"]}
    hosts = rep["raw"]["libraries"]["hosts"]
    ck("library behaviors", all(beh(x["ops"]) == tuple(x["beh"]) for x in full.values()))
    ck("admitted only", all(e["value"].get("admitted") for e in entries
                            if e["kind"] in ("macro_claim", "compound_claim") and e["key"] in full))
    p = rep["measurements"]["poison"]
    ck("poison absent", not any(k.startswith("poison") for k in full))
    ck("poison false", len(p["claims"]) == 3 and all(c["actual"] != c["claimed"] for c in p["claims"]))
    ck("poison refused", all(not a["admitted"] for a in p["admissions"]))
    ck("promotions refused", all(x["authority"].startswith("REFUSED") for x in p["promotions"]))
    fc = rep["measurements"]["fail_closed"]
    ck("fail closed", fc["refused"] and fc["local_rows_unchanged"])
    integ = rep["measurements"]["integrity"]
    ck("chain valid", integ["chain_valid"] and not integ["bad"] and integ["entries"] == len(entries))
    ck("logs identical", integ["logs_identical"] and integ["local_sha256"] == sha(
        "".join(json.dumps(e, sort_keys=True, ensure_ascii=False) + "\n" for e in entries).encode()))
    ck("log hashes", all(integ["local_sha256"] == h for h in integ["remote_sha256"].values()))
    ck("remote verifications", rep["measurements"]["remote_verifications"] == sum(
        1 for e in entries if e["kind"] in ("macro_claim", "compound_claim") and e["value"].get("verified_remote")))

    metas = [m["machine"] for s in rep["measurements"]["host_meta"].values() for m in s.values()]
    ck("three machine-ids", len(set(metas)) == 3 and "build-host" in metas and len(metas) >= 6)

    # growth + development curve recomputed from the entry order
    gen_ends = rep["raw"]["gen_ends"]
    full_adm = {}
    growth = []
    for end in gen_ends:
        snap = {}
        for e in entries[:end]:
            if e["kind"] in ("macro_claim", "compound_claim") and e["value"].get("admitted"):
                snap[e["key"]] = {"key": e["key"], "ops": e["value"]["ops"], "beh": e["value"]["beh"]}
        growth.append(len(snap))
    ck("library growth", growth == rep["measurements"]["library_growth"])
    deep = rep["raw"]["deep"]
    curve = []
    for end in gen_ends:
        snap = {}
        for e in entries[:end]:
            if e["kind"] in ("macro_claim", "compound_claim") and e["value"].get("admitted"):
                snap[e["key"]] = {"key": e["key"], "ops": e["value"]["ops"], "beh": e["value"]["beh"]}
        curve.append(sum(1 for t in deep if apply_program_ok(t["target"], snap)))
    ck("development curve", curve == rep["measurements"]["dev_curve"])

    # sealed evaluation
    tasks_by = rep["raw"]["tasks"]
    counts = {}
    parity_ok = True
    quorum_ok = True
    shared = {}
    iso = {}
    base = {}
    for s in ("salt1", "salt2"):
        data = tasks_by[s]
        tasks = data["tasks"]
        targets = {t["id"]: tuple(t["target"]) for t in tasks}
        local = data["local_results"]
        hostr = data["host_results"]
        counts[s] = {"hosts": {}, "shared": {"gen2": 0, "gen3": 0}}
        for t in tasks:
            lr = local[t["id"]]
            lok = lr["program"] is not None and apply_program(lr["program"], full) == targets[t["id"]]
            if lok != lr["ok"]:
                parity_ok = False
            for h, res in hostr.items():
                rr = res[t["id"]]
                rok = rr["program"] is not None and apply_program(rr["program"], full) == targets[t["id"]]
                if rok != rr["ok"] or rok != lok:
                    parity_ok = False
            votes = [bool(res[t["id"]]["ok"]) for res in hostr.values()]
            accepted = sum(votes) >= 2
            if accepted != next(q["accepted"] for q in data["quorum"] if q["id"] == t["id"]):
                quorum_ok = False
            if accepted:
                counts[s]["shared"]["gen3" if t["id"].startswith("s3") else "gen2"] += 1
        shared[s] = counts[s]["shared"]
        # isolated views
        counts[s]["hosts"] = {}
        for h, lib_list in hosts.items():
            lib = {x["key"]: x for x in lib_list}
            row = {"gen2": 0, "gen3": 0}
            for t in tasks:
                if apply_program_ok(t["target"], lib):
                    row["gen3" if t["id"].startswith("s3") else "gen2"] += 1
            row["total"] = row["gen2"] + row["gen3"]
            counts[s]["hosts"][h] = row
        iso[s] = counts[s]["hosts"]
        base[s] = sum(1 for t in tasks if baseline(targets[t["id"]]) is not None)
        # fault drill
        faulty = "vultr-b"
        first, forged = tasks[0]["id"], tasks[-1]["id"]
        corrupt = {k: dict(v) for k, v in hostr[faulty].items()}
        corrupt[first] = {"ok": not corrupt[first]["ok"], "program": corrupt[first]["program"]}
        corrupt[forged] = {"ok": True, "program": [0]}
        acc_f = 0
        for t in tasks:
            votes = [bool(hostr[h][t["id"]]["ok"]) for h in hostr if h != faulty]
            votes.append(bool(corrupt[t["id"]]["ok"]))
            acc_f += int(sum(votes) >= 2)
        acc_h = sum(1 for q in data["quorum"] if q["accepted"])
        detected = False
        for t in tasks:
            votes = [bool(hostr[h][t["id"]]["ok"]) for h in hostr if h != faulty]
            votes.append(bool(corrupt[t["id"]]["ok"]))
            if bool(corrupt[t["id"]]["ok"]) != (sum(votes) >= 2):
                detected = True
        forged_rejected = apply_program([0], full) != targets[forged]
        fd = rep["measurements"]["fault_drill"][s]
        ck(f"{s} fault drill", fd["detected"] == detected and fd["accepted_with_fault"] == acc_f
           and fd["accepted_honest"] == acc_h and fd["count_unchanged"] == (acc_f == acc_h)
           and fd["forged_program_rejected"] == forged_rejected)
    ck("distributed parity", parity_ok)
    ck("quorum recompute", quorum_ok)
    ck("shared counts", shared == rep["measurements"]["shared"])
    ck("host counts", iso == rep["measurements"]["isolated_hosts"])
    ck("baseline", base == rep["measurements"]["baseline"])

    H = rep["hypotheses"]
    best = {s: max(iso[s].items(), key=lambda kv: kv[1]["total"]) for s in iso}
    rules = {
        "H1_distributed_parity": parity_ok,
        "H2_quorum_rejects_fault": all(rep["measurements"]["fault_drill"][s]["detected"]
                                       and rep["measurements"]["fault_drill"][s]["count_unchanged"]
                                       and rep["measurements"]["fault_drill"][s]["forged_program_rejected"]
                                       for s in ("salt1", "salt2")),
        "H3_shared_cross_host_coverage": (sum(shared["salt1"].values()) >= 22 and best["salt1"][1]["total"] <= 12),
        "H4_verified_admission": p["library_unchanged"] and all(not a["admitted"] for a in p["admissions"]),
        "H5_compounding": (sum(1 for a, b in zip(growth, growth[1:]) if b > a) >= 3
                           and curve[-1] > curve[0] and all(b >= a for a, b in zip(curve, curve[1:]))),
        "H6_fail_closed": (fc["refused"] and fc["local_rows_unchanged"] and integ["logs_identical"]
                           and integ["chain_valid"]),
        "H7_replication": (sum(shared["salt2"].values()) >= 22 and best["salt2"][1]["total"] <= 12),
    }
    ck("hypotheses", all(H[k]["verdict"] == ("SUPPORTED" if v else "NOT_SUPPORTED") for k, v in rules.items()))
    verdict = "THREE_HOST_DISTRIBUTED_VERIFIED_RSI_SUPPORTED" if all(rules.values()) else "NOT_SUPPORTED"
    ck("verdict", rep["verdict"] == verdict)

    manp = d / "E421D_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())
        extra = {"PUBLICATION.json", "E421D_OMEGA_SEAL.json", "MANIFEST.json", "MERKLE_ROOT.txt",
                 "E421D_PUBKEY.pem", "E421D_SIGNED_BODY.json", "E421D_VERIFICATION_RESULTS.json",
                 "E421D_TAMPER_RESULTS.json", "E421D_MANIFEST.json"}
        actual = {str(x.relative_to(d)) for x in d.rglob("*") if x.is_file() and "__pycache__" not in x.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


def apply_program_ok(target, lib):
    """Solve a target at depth 2 with a library (BFS, same rule as the engine)."""
    ident = tuple(XS)
    seen = {ident}
    cur = [(ident, [])]
    steps = [(k, v["ops"]) for k, v in lib.items()] + [("p%d" % i, None) for i in range(6)]
    for depth in range(3):
        nxt = []
        for b, prog in cur:
            if b == tuple(target):
                return True
            if depth == 2:
                continue
            for key, ops in steps:
                if ops is None:
                    ops = [int(key[1:])]
                nb = b
                for i in ops:
                    nb = tuple(PRIMS[i](x) for x in nb)
                if nb in seen:
                    continue
                seen.add(nb)
                nxt.append((nb, prog + [key]))
        cur = nxt
    return False


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