#!/usr/bin/env python3
"""Standalone auditor for the real-workload scan. Re-reads the real files and recomputes everything."""
from __future__ import annotations
import hashlib, json, re, sys
from pathlib import Path
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

ROOT = Path("/usr/local/lib/python3.14/dist-packages/sklearn")
TENANT = "cain42-real"
R1 = re.compile(r"\bsk-(?:ant-)?[A-Za-z0-9_-]{18,}")
R2 = re.compile(r"\bsk-(?:proj-|ant-api\d{2}-)?[A-Za-z0-9]{32,}")


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 scan(text):
    hits = []
    for i, line in enumerate(text.splitlines(), 1):
        for name, rx in (("openai_like", R1), ("openai_like_strict", R2)):
            for m in rx.finditer(line):
                hits.append({"line": i, "rule": name, "match_sha": sha(m.group(0).encode()),
                             "match_len": len(m.group(0)), "snippet_sha": sha(line.strip().encode())})
    return hits


def nonce(a, k, key, v): return sha(canon({"agent": a, "kind": k, "key": key, "value": v}))[:16]


def pub_of(a):
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
    k = Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"real|{a}".encode()).digest())
    return k.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw).hex()


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():
    root = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
    ck, fail = [], []
    def check(n, ok, d=""):
        ck.append({"check": n, "ok": bool(ok), "detail": d})
        if not ok: fail.append(n)
    run = json.loads((root / "REAL_RUN.json").read_text())
    rows = json.loads((root / "REAL_ROWS.json").read_text())
    mem = json.loads((root / "REAL_MEMORY.json").read_text())
    man = json.loads((root / "MANIFEST.json").read_text())

    bad_hash = bad_scan = missing = 0
    for r in rows:
        p = ROOT / r["path"]
        if not p.exists():
            missing += 1; continue
        data = p.read_bytes()
        if sha(data) != r["sha256"] or len(data) != r["bytes"]:
            bad_hash += 1; continue
        if scan(data.decode("utf-8", "replace")) != r["hits"]:
            bad_scan += 1
    check("every file still exists", missing == 0, f"{missing} missing")
    check("every file hash and size matches the real bytes", bad_hash == 0, f"{bad_hash} mismatches")
    check("every detector result recomputes from the real source", bad_scan == 0, f"{bad_scan} mismatches")
    check("file count is 240", len(rows) == 240, str(len(rows)))
    check("byte count matches the report", sum(r["bytes"] for r in rows) == run["corpus"]["bytes_scanned"])

    v1 = [x for r in rows for x in r["hits"] if x["rule"] == "openai_like"]
    v2 = [x for r in rows for x in r["hits"] if x["rule"] == "openai_like_strict"]
    check("naive rule hits are reported (9)", len(v1) == run["findings"]["v1_hits"] == 9, str(len(v1)))
    check("structural rule hits are reported (0)", len(v2) == run["findings"]["v2_hits"] == 0, str(len(v2)))

    pubs = {a: pub_of(a) for a in ("reader", "auditor")}
    check("published memory keys derive from the seed", pubs == mem["keys"])
    bad = vmem(mem["entries"], pubs)
    check("every governed read entry verifies (signature and chain)", not bad, str(bad[:5]))
    check("one signed entry per file", len(mem["entries"]) == len(rows))
    check("every signed entry binds the file hash",
          all(e["value"]["sha256"] == r["sha256"] for e, r in zip(mem["entries"], rows)))

    probes = {p["probe"]: p for p in run["boundary"]["probes"]}
    check("a path outside the corpus is refused before any read",
          probes["path_escape"]["interceptor_allowed"] is False)
    check("a tool not on the allowlist is refused (default-deny)",
          probes["denied_tool"]["allowed"] is False and "not on the allowlist" in probes["denied_tool"]["reason"])
    check("a JIT capability is single-use",
          probes["replay"]["first"] is True and probes["replay"]["second"] is False
          and "ALREADY_CONSUMED" in probes["replay"]["reason"])
    check("zero model calls", run.get("model_calls") == 0)
    check("status line", run.get("status") == "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL")

    fs = sorted(p for p in root.rglob("*") if p.is_file() and "__pycache__" not in p.parts
                and p.name not in ("MANIFEST.json", "REAL_MANIFEST.json", "MERKLE_ROOT.txt",
                                   "REAL_SIGNED_BODY.json", "REAL_VERIFICATION_RESULTS.json",
                                   "REAL_TAMPER_RESULTS.json", "REAL_PUBLIC_CHECK.json",
                                   "PUBLICATION.json", "REAL_OMEGA_SEAL.json", "REAL_PUBKEY.pem"))
    body = {k: man[k] for k in ("schema", "evolution", "status", "name", "created_at", "verifier",
                                "pubkey_ed25519", "files", "merkle_root", "engine_withheld", "external_review")}
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]), canon(body))
        check("manifest signature", True)
    except Exception:
        check("manifest signature", False)
    check("file hashes match the manifest", all(man["files"].get(str(p.relative_to(root))) == sha(p.read_bytes()) for p in fs))
    check("manifest lists exactly the bundle files", sorted(man["files"]) == sorted(str(p.relative_to(root)) for p in fs))
    check("merkle root recomputes", man["merkle_root"] == merkle(fs))
    check("engine source withheld", man.get("engine_withheld") is True and not any(p.suffix == ".py" and "verify" not in p.name for p in fs))
    check("external review not claimed", man.get("external_review") == "NOT_OBTAINED")

    print(json.dumps({"checks": len(ck), "passed": sum(1 for c in ck if c["ok"]),
                      "failed": fail, "files": len(rows), "bytes": sum(r["bytes"] for r in rows),
                      "v1_hits": len(v1), "v2_hits": len(v2)}, indent=1))
    return 0 if not fail else 1


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