#!/usr/bin/env python3
"""Standalone auditor for RSP. Re-reads the real files, recomputes detections and metrics, verifies the chain."""
from __future__ import annotations
import hashlib, json, math, re, sys
from collections import Counter
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 = "cain42-rwm", "rwm"
V1 = re.compile(r"\bsk-(?:ant-)?[A-Za-z0-9_-]{18,}")
V2 = re.compile(r"\bsk-(?:proj-|ant-api\d{2}-)?[A-Za-z0-9]{32,}")
PEM = re.compile(r"-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----")
AWS = re.compile(r"\bAKIA[0-9A-Z]{16}\b")
ASG = re.compile(r"(?i)\b(?:api[_-]?key|secret|token|password|passwd)\b\s*[:=]\s*['\"]?([A-Za-z0-9_\-+/=]{24,})['\"]?")


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 entropy(s):
    if not s: return 0.0
    c = Counter(s); n = len(s)
    return -sum(v / n * math.log2(v / n) for v in c.values())


def detect(text):
    out = {"v1": 0, "v2": 0, "v3": 0}
    for line in text.splitlines():
        if V1.search(line): out["v1"] += 1
        if V2.search(line): out["v2"] += 1
        if PEM.search(line) or AWS.search(line): out["v3"] += 1
        else:
            m = ASG.search(line)
            if m and entropy(m.group(1)) >= 3.5: out["v3"] += 1
    return out


def metrics(rows, rule):
    tp = sum(1 for r in rows if r["label"] == 1 and r["detections"][rule] > 0)
    fn = sum(1 for r in rows if r["label"] == 1 and r["detections"][rule] == 0)
    fp = sum(1 for r in rows if r["label"] == 0 and r["detections"][rule] > 0)
    tn = sum(1 for r in rows if r["label"] == 0 and r["detections"][rule] == 0)
    return {"tp": tp, "fn": fn, "fp": fp, "tn": tn,
            "precision": round(tp / (tp + fp), 4) if (tp + fp) else None,
            "recall": round(tp / (tp + fn), 4) if (tp + fn) else None}


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 / "RSP_RUN.json").read_text())
    rows = json.loads((B / "RSP_ROWS.json").read_text())
    mem = json.loads((B / "RSP_MEMORY.json").read_text())
    c("corpus", run["corpus"]["positives"] == 40 and run["corpus"]["negatives"] == 240, run["corpus"])

    neg = sorted((p for p in SK.rglob("*.py")), key=lambda p: h(str(p.relative_to(SK))))[:240]
    pos = sorted(Path("/root/.cain-rsp/corpus").glob("*.pem"))
    real = {}
    for label, role, ps in ((1, "private_key", pos), (0, "source", neg)):
        for p in ps:
            data = p.read_bytes()
            real[sha(data)] = {"role": role, "label": label, "bytes": len(data), "det": detect(data.decode("utf-8", "replace"))}
    uniq = {r["sha256"] for r in rows}
    c("files_match", all(r["sha256"] in real for r in rows) and len(real) == len(uniq), (len(real), len(uniq), len(rows)))
    c("labels_match", all(real[r["sha256"]]["label"] == r["label"] and real[r["sha256"]]["role"] == r["role"] for r in rows))
    c("detections_match", all(real[r["sha256"]]["det"] == r["detections"] for r in rows),
      sum(1 for r in rows if real[r["sha256"]]["det"] != r["detections"]))
    for rule in ("v1", "v2", "v3"):
        m = metrics(rows, rule)
        c(f"metrics_{rule}", m == run["metrics"][rule], m)
    c("v1_zero_precision", run["metrics"]["v1"]["precision"] == 0.0 and run["metrics"]["v1"]["tp"] == 0)
    c("v3_perfect", run["metrics"]["v3"]["precision"] == 1.0 and run["metrics"]["v3"]["recall"] == 1.0)
    probes = {p["probe"]: p for p in run["boundary"]["probes"]}
    c("boundary_path", probes["outside_declared_roots"]["interceptor_allowed"] is False)
    c("boundary_ssh", probes["ssh_private_key"]["interceptor_allowed"] is False, probes["ssh_private_key"].get("reason", ""))
    c("boundary_tool", probes["unlisted_tool"]["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) == len(rows), 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))
        sigok = True
    except Exception:
        sigok = False
    c("manifest_signature", sigok)
    fs = sorted(x for x in B.rglob("*") if x.is_file() and x.name not in
                {"MANIFEST.json", "MERKLE_ROOT.txt", "RSP_SIGNED_BODY.json", "RSP_MANIFEST.json",
                 "RSP_VERIFICATION_RESULTS.json", "RSP_TAMPER_RESULTS.json", "RSP_PUBLIC_CHECK.json",
                 "RSP_PUBKEY.pem", "PUBLICATION.json"})
    root = merkle(fs)
    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.rsp.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"]],
           "positives": 40, "negatives": 240,
           "v1": run["metrics"]["v1"], "v3": run["metrics"]["v3"]}
    (B / "RSP_VERIFICATION_RESULTS.json").write_text(json.dumps(out, indent=1))
    print(json.dumps({k: out[k] for k in ("passed", "failed", "positives", "negatives", "v1", "v3")}, indent=1))
    return 0 if not out["failed"] else 1


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