#!/usr/bin/env python3
"""SMF standalone auditor — imports no CAIN code.

Recomputes, from the exported raw rows: every memory entry's hash and Ed25519 signature, every
admission decision, every arm's sealed result (by executing the returned program on the six probe
values), all counts, the frontier curve, the churn contrast, the poison and the verdict.
"""
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]
TENANT = "cain42-smf"
S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"


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


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


def apply_ops(ops, vec):
    out = list(vec)
    for i in ops:
        out = [PRIMS[i](x) for x in out]
    return tuple(out)


def beh(ops):
    return apply_ops(ops, XS)


def build_index(lib):
    steps = [("m", k, e["ops"], tuple(e["beh"])) for k, e in lib.items()]
    steps += [("p", i, [i], apply_ops([i], XS)) for i in range(len(PRIMS))]
    idx = {}
    for _, ref, _, b in steps:
        idx.setdefault(b, [ref])
    for _, r1, _, b1 in steps:
        for _, r2, ops2, _ in steps:
            idx.setdefault(apply_ops(ops2, b1), [r1, r2])
    return idx


def apply_program(prog, lib):
    b = list(XS)
    for step in prog:
        ops = [step] if isinstance(step, int) else list(lib[step]["ops"])
        for i in ops:
            b = [PRIMS[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 / "SMF_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.smf.run.v1")
    ck("status", rep.get("status") == S)
    ck("salts", rep["salts_commitment"] == {k: sha(v.encode()) for k, v in salts.items()})
    pre = d / "SMF_PREREGISTRATION.json"
    frz = d / "SMF_PREREGISTRATION_FREEZE.json"
    ck("prereg present", pre.exists() and frz.exists())
    if pre.exists() and frz.exists():
        f = json.loads(frz.read_text())
        ck("prereg hash", sha(pre.read_bytes()) == f["preregistration_sha256"])
        ck("salts frozen", f["salt_commitments"] == rep["salts_commitment"])
        ck("amendments preserved", (d / "SMF_PREREGISTRATION.v1.json").exists()
           and (d / "SMF_PREREGISTRATION_FREEZE.v1.json").exists()
           and (d / "SMF_PREREGISTRATION.v2.json").exists())
        dev = json.loads((d / "SMF_DEVIATIONS.json").read_text())
        ck("deviations recorded", len(dev["deviations"]) >= 2)

    # ---- memory chain and signatures
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
    names = ["atlas", "borealis", "cetus", "draco", "eris", "mallory", "steward"]
    pubs = {n: Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"smf|{n}".encode()).digest())
            .public_key().public_bytes_raw().hex() for n in names}
    entries = rep["raw"]["entries"]
    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["tenant"] == TENANT and 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)
    ck("sequences contiguous", [e["seq"] for e in entries] == list(range(1, len(entries) + 1)))

    # ---- admissions must equal a recomputation
    claims = {e["key"]: e for e in entries if e["kind"] in ("macro_claim", "compound_claim")}
    admissions = {e["key"]: e["value"] for e in entries if e["kind"] == "admission"}
    adm_ok = True
    for k, c in claims.items():
        a = admissions.get(k)
        if not a:
            adm_ok = False
            break
        truth = list(beh(c["value"]["ops"])) == list(a["claimed_beh"])
        if a["admitted"] != truth or a["recomputed_beh"] != list(beh(c["value"]["ops"])):
            adm_ok = False
            break
    ck("admissions recompute", adm_ok and len(claims) == len(admissions))

    # ---- libraries and sealed results, recomputed exactly
    arms = rep["raw"]["arms"]
    libs = {k: {e["key"]: e for e in v["lib"]} for k, v in arms.items()}
    ck("FULL library = admitted claims", set(libs["FULL"]) ==
       {k for k, c in claims.items() if admissions[k]["admitted"]})
    bands = rep["raw"]["bands"]
    evaluated = rep["raw"]["evaluated"]
    counts = {}
    idx_cache = {k: build_index(v) for k, v in libs.items()}
    ok_all = True
    for salt in ("salt1", "salt2"):
        counts[salt] = {}
        for arm, lib in libs.items():
            c = {}
            for band, tasks in bands[salt]["bands"].items():
                n = 0
                rows = {r["id"]: r for r in evaluated[salt][arm][band]}
                for t in tasks:
                    prog = idx_cache[arm].get(tuple(t["target"]))
                    good = bool(prog is not None and apply_program(prog, lib) == tuple(t["target"]))
                    r = rows.get(t["id"])
                    if r is None or r["ok"] != good:
                        ok_all = False
                    n += int(good)
                c[band] = n
            c["TOTAL"] = sum(c[b] for b in bands[salt]["bands"])
            c["DEEP"] = c["L4"] + c["L5"]
            counts[salt][arm] = c
    ck("sealed programs recompute", ok_all)
    ck("counts match", all(counts[s][a] == rep["measurements"]["counts"][s][a]
                           for s in counts for a in counts[s]))

    # ---- frontier curve from raw levels and development rows
    lens = {g: len(levels[0]["ops"]) for g, levels in rep["raw"]["levels"].items() if levels}
    dev = {int(g): sum(1 for r in rows if r["solved"]) for g, rows in rep["raw"]["dev"].items()}
    ck("composition length", lens == rep["measurements"]["composition_length"] and lens["5"] == 64)
    fr = {int(k): v for k, v in rep["measurements"]["frontier"].items()}
    ck("development solved", dev == fr and all(v == 16 for v in dev.values()))

    # ---- churn
    churn_ok = True
    churn = {}
    for salt in ("salt1", "salt2"):
        rows = []
        for band in ("L4", "L5", "XGEN"):
            for t in bands[salt]["bands"][band]:
                if "cetus" not in t["owners"]:
                    continue
                rows.append({"full": next(r["ok"] for r in evaluated[salt]["FULL"][band] if r["id"] == t["id"]),
                             "ml": next(r["ok"] for r in evaluated[salt]["MEMORY_LOSS_CHURN"][band] if r["id"] == t["id"])})
        churn[salt] = {"tasks": len(rows), "full": sum(1 for x in rows if x["full"]),
                       "memory_loss": sum(1 for x in rows if x["ml"])}
        if churn[salt] != {k: rep["measurements"]["churn"][salt][k] for k in ("tasks", "full", "memory_loss")}:
            churn_ok = False
    ck("churn recompute", churn_ok)
    rev = [e for e in entries if e["kind"] == "revocation" and e["value"]["agent"] == "cetus"]
    ck("revocation recorded", len(rev) == 1 and not [e for e in entries
                                                     if e["agent"] == "cetus" and e["seq"] > rev[0]["seq"]])
    ck("successor wrote", any(e["agent"] == "eris" and e["kind"] == "compound_claim" for e in entries))

    # ---- poison
    p = rep["measurements"]["poison"]
    ck("poison refused", len(p["claims"]) == 3 and all(not a["admitted"] for a in p["admissions"]))
    ck("poison absent", p["library_unchanged"] and not any(k.startswith("poison") for k in libs["FULL"]))
    ck("poison ops mismatch", all(c["actual"] != c["claimed"] for c in p["claims"]))

    # ---- transport drill: no probe row, a recovery row, reported identity
    kinds = [e["kind"] for e in entries]
    ck("transport", "partition_probe" not in kinds and "recovery" in kinds
       and rep["measurements"]["transport"]["refused_write"]
       and rep["measurements"]["transport"]["refused_read"]
       and rep["measurements"]["transport"]["logs_identical"])
    rp = rep["measurements"]["remote_probe"]
    ck("remote compute", rp.get("ok") and rp.get("match") and rp.get("remote_not_local"))
    ck("no memory authority", all(x["authority"] == "REFUSED_MEMORY_HAS_NO_AUTHORITY"
                                 for x in p["promotions"]))

    # ---- hypotheses
    H = rep["hypotheses"]
    tot = lambda s, a: counts[s][a]["TOTAL"]
    rules = {
        "H1_frontier_law": all(counts["salt1"]["FULL"][b] >= 11 for b in
                               ("L1", "L2", "L3", "L4", "L5", "XGEN")) and all(v == 16 for v in dev.values()),
        "H2_shared_memory_dominance": tot("salt1", "FULL") >= 66 and tot("salt1", "ISOLATED") <= 30,
        "H3_deep_frontier": (counts["salt1"]["FULL"]["DEEP"] >= 22
                             and counts["salt1"]["ISOLATED"]["DEEP"] <= 6
                             and counts["salt1"]["DEPTH_LIMITED"]["DEEP"] == 0),
        "H4_agent_substitutability": (all(r["solved"] for g in (4, 5) for r in rep["raw"]["dev"][str(g)])
                                      and rep["measurements"]["eris_compounds"] >= 8
                                      and churn["salt1"]["tasks"] >= 3
                                      and churn["salt1"]["full"] == churn["salt1"]["tasks"]
                                      and churn["salt1"]["memory_loss"] <=
                                      churn["salt1"]["tasks"] - max(1, churn["salt1"]["tasks"] // 4)),
        "H5_admission_load_bearing": (all(not a["admitted"] for a in p["admissions"])
                                      and p["library_unchanged"]
                                      and tot("salt1", "NO_ADMISSION") <= tot("salt1", "FULL") - 6),
        "H6_generalist_reference": abs(tot("salt1", "FULL") - tot("salt1", "GENERALIST")) <= 4,
        "H7_integrity": not bad,
        "H8_transport": (rep["measurements"]["transport"]["refused_write"]
                         and rep["measurements"]["transport"]["refused_read"]
                         and rep["measurements"]["transport"]["local_rows_unchanged"]
                         and rep["measurements"]["transport"]["logs_identical"]),
        "H9_replication": (tot("salt2", "FULL") >= 66 and tot("salt2", "ISOLATED") <= 30
                           and counts["salt2"]["FULL"]["DEEP"] >= 22
                           and churn["salt2"]["full"] == churn["salt2"]["tasks"]),
    }
    for k, v in rules.items():
        want = ("PARITY" if k == "H6_generalist_reference" and v else
                "NOT_PARITY" if k == "H6_generalist_reference" else
                "SUPPORTED" if v else "NOT_SUPPORTED")
        if H[k]["verdict"] != want:
            ck("hypothesis " + k, False)
    ck("hypotheses recompute", all(H[k]["verdict"] ==
                                  ("PARITY" if k == "H6_generalist_reference" and v else
                                   "NOT_PARITY" if k == "H6_generalist_reference" else
                                   "SUPPORTED" if v else "NOT_SUPPORTED") for k, v in rules.items()))
    ck("H10 blocked", H["H10_external_review"]["verdict"] == "BLOCKED")
    verdict = "GOVERNED_MEMORY_FRONTIER_AND_AGENT_SUBSTITUTABILITY_SUPPORTED" if all(rules.values()) else "NOT_SUPPORTED"
    ck("verdict", rep["verdict"] == verdict)

    # ---- manifest
    manp = d / "SMF_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", "SMF_OMEGA_SEAL.json", "MANIFEST.json", "MERKLE_ROOT.txt",
                 "SMF_PUBKEY.pem", "SMF_SIGNED_BODY.json", "SMF_VERIFICATION_RESULTS.json",
                 "SMF_TAMPER_RESULTS.json", "SMF_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


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