#!/usr/bin/env python3
"""Standalone auditor for RMA. Re-parses the real files, rebuilds facts, queries and every arm."""
from __future__ import annotations
import ast, hashlib, json, sys
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey

B = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parent
SK = Path("/usr/local/lib/python3.14/dist-packages/sklearn")
TENANT, SEED, N_FILES, NQ, SHARDS = "cain42-rwm", "rwm", 240, 48, 4


def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
def sha(b): return hashlib.sha256(b).hexdigest()
def h(s): return hashlib.sha256(s.encode()).hexdigest()


def facts(text):
    try: tree = ast.parse(text)
    except SyntaxError: return {"defs": [], "uses": []}
    d = []
    for node in tree.body:
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): d.append(node.name)
        elif isinstance(node, ast.Assign): d += [t.id for t in node.targets if isinstance(t, ast.Name)]
    u = sorted({n.id for n in ast.walk(tree) if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Load)})
    return {"defs": sorted(set(d)), "uses": u}


def keypair(a): return Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"{SEED}|{a}".encode()).digest())
def pubhex(a): return keypair(a).public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw).hex()
def nonce(a, k, key, v): return sha(canon({"agent": a, "kind": k, "key": key, "value": v}))[:16]


def vmem(es, pubs):
    prev, bad = "", []
    for e in es:
        e = {**e, "grants_authority": False, "executable": False}
        body = canon({k: e[k] for k in ("seq", "tenant", "agent", "kind", "key", "value", "prev",
                                        "nonce", "created_at", "grants_authority", "executable")})
        ok = (e["prev"] == prev and e["tenant"] == TENANT
              and sha(e["prev"].encode() + body + bytes.fromhex(e["sig"])) == e["hash"]
              and e["nonce"] == nonce(e["agent"], e["kind"], e["key"], e["value"]))
        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"]
    return bad


def merkle(fs):
    l = sorted(sha(p.read_bytes()) for p in fs)
    while len(l) > 1:
        if len(l) % 2: l.append(l[-1])
        l = [sha((l[i] + l[i + 1]).encode()) for i in range(0, len(l), 2)]
    return l[0] if l else sha(b"")


def main():
    ck = []
    def c(n, ok, d=""): ck.append({"check": n, "ok": bool(ok), "detail": str(d)[:300]})

    run = json.loads((B / "RMA_RUN.json").read_text())
    rows = json.loads((B / "RMA_ROWS.json").read_text())
    mem = json.loads((B / "RMA_MEMORY.json").read_text())

    files = sorted((p for p in SK.rglob("*.py")), key=lambda p: h(str(p.relative_to(SK))))[:N_FILES]
    real = {}
    for i, p in enumerate(files):
        text = p.read_text(errors="replace"); fx = facts(text)
        real[i] = {"shard": int(h(str(p.relative_to(SK))), 16) % SHARDS, "sha256": sha(text.encode()), **fx}
    c("files", len(real) == 240, len(real))
    defs = {}
    for i, v in real.items():
        for s in v["defs"]: defs.setdefault(s, []).append((i, v["shard"]))
    uses = {}
    for i, v in real.items():
        for s in v["uses"]: uses.setdefault(s, set()).add((i, v["shard"]))
    uniq = {s: v[0] for s, v in defs.items() if len(v) == 1}
    cand = []
    for s in sorted(uniq):
        fi, fs = uniq[s]
        for ui, us in sorted(uses.get(s, ())):
            if ui != fi and us != fs: cand.append((s, fi, fs, ui, us)); break
    q = cand[:NQ]
    c("queries_available", len(cand) >= NQ, len(cand))
    c("queries_match", [(x[0], x[1], x[3]) for x in rows["queries"]] == [(s, fi, ui) for s, fi, fs, ui, us in q])

    def answer(scope, s, fi, fs, ui, us):
        own = {i for i, v in real.items() if v["shard"] in scope}
        d = next((i for i in own if s in real[i]["defs"]), None)
        u = any(i in own and s in real[i]["uses"] for i in range(len(real)) if real[i]["shard"] == us)
        return d == fi and u

    shared = [answer(set(range(SHARDS)), *t) for t in q]
    allc = [answer({v["shard"] for v in real.values()}, *t) for t in q]
    iso = [answer({us}, s, fi, fs, ui, us) or answer({fs}, s, fi, fs, ui, us) for s, fi, fs, ui, us in q]
    for arm, exp in (("SHARED", shared), ("ALL_CONTENT", allc), ("ISOLATED", iso)):
        got = [r["ok"] for r in rows[arm]]
        c(f"arm_{arm}", got == exp, sum(got))
        c(f"count_{arm}", sum(1 for x in got if x) == run["summary"][arm]["solved"], run["summary"][arm]["solved"])
    c("shared_exact", run["summary"]["SHARED"]["solved"] == NQ)
    c("isolated_zero", run["summary"]["ISOLATED"]["solved"] == 0)
    c("parity", run["summary"]["ALL_CONTENT"]["solved"] == run["summary"]["SHARED"]["solved"])
    probes = {p["probe"]: p for p in run["boundary"]["probes"]}
    c("boundary_path", probes["outside_declared_roots"]["interceptor_allowed"] is False)
    c("boundary_replay", probes["replay"]["first"] is True and probes["replay"]["second"] is False)
    es = mem["entries"] if isinstance(mem["entries"], list) else list(mem["entries"].values())
    c("memory_entries", len(es) == 480, len(es))
    c("memory_chain", vmem(es, mem["keys"]) == [], vmem(es, mem["keys"])[:5])
    c("memory_no_authority", all(e.get("grants_authority") is False and e.get("executable") is False for e in es))
    c("no_model_calls", run["model_calls"] == 0 and run["api_cost_usd"] == 0.0)
    man = json.loads((B / "MANIFEST.json").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)); sig = True
    except Exception: sig = False
    c("manifest_signature", sig)
    fsx = sorted(x for x in B.rglob("*") if x.is_file() and x.name not in
                 {"MANIFEST.json", "MERKLE_ROOT.txt", "RMA_SIGNED_BODY.json", "RMA_MANIFEST.json",
                  "RMA_VERIFICATION_RESULTS.json", "RMA_TAMPER_RESULTS.json", "RMA_PUBLIC_CHECK.json",
                  "RMA_PUBKEY.pem", "PUBLICATION.json"})
    root = merkle(fsx)
    c("merkle", root == man["merkle_root"] == (B / "MERKLE_ROOT.txt").read_text().strip(), root[:16])
    c("status_line", "AGI: NOT ESTABLISHED" in run["status"] and "RSI: EXPERIMENTAL" in run["status"])
    out = {"schema": "cain42.rma.verification.v1", "checks": ck,
           "passed": sum(1 for x in ck if x["ok"]), "failed": [x["check"] for x in ck if not x["ok"]],
           "summary": run["summary"]}
    (B / "RMA_VERIFICATION_RESULTS.json").write_text(json.dumps(out, indent=1))
    print(json.dumps({"passed": out["passed"], "failed": out["failed"], "summary": out["summary"]}, indent=1))
    return 0 if not out["failed"] else 1


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