#!/usr/bin/env python3
"""E233 forensic-audit verifier. No CAIN imports; audit bundle only."""
import hashlib, json, sys
from pathlib import Path
STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENGINE = {"engine.py", "run.py", "prereg.py"}


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


def merkle(paths):
    leaves = sorted(sha(p.read_bytes()) for p in paths)
    if not leaves: return sha(b"")
    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)]
    return leaves[0]


def main():
    B = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    checks = []
    def ck(n, ok, d=""): checks.append({"check": n, "ok": bool(ok), "detail": str(d)[:300]})
    man = json.loads((B / "E233_MANIFEST.json").read_text())
    ck("status", man.get("status") == STATUS)
    ck("label", man.get("label") == "FORENSIC_AUDIT")
    body = {k: v for k, v in man.items() if k != "signature"}
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]), canon(body))
        ck("signature", True)
    except Exception as ex:
        ck("signature", False, ex)
    files = man.get("files", {})
    ck("files exist", all((B / k).exists() for k in files))
    bad = [k for k, h in files.items() if (B / k).exists() and sha((B / k).read_bytes()) != h]
    ck("hashes", not bad, bad[:3])
    ck("merkle", merkle(sorted(B / k for k in files if (B / k).exists())) == man.get("merkle_root"))
    present = {str(x.relative_to(B)) for x in B.rglob("*") if x.is_file() and "__pycache__" not in x.parts}
    extra = {"E233_MANIFEST.json", "E233_SIGNED_BODY.json", "E233_VERIFICATION_RESULTS.json", "PUBLICATION.json", "E233_OMEGA_SEAL.json", "E233_TAMPER_RESULTS.json"}
    unlisted = sorted(present - set(files) - extra)
    ck("no unlisted", not unlisted, unlisted[:5])
    ck("no engine source", not any((B / n).exists() for n in ENGINE))
    ck("no secrets", not any(x.endswith((".pem", ".key", ".env", ".db")) for x in present))

    cm = json.loads((B / "E233_CAPABILITY_MATRIX.json").read_text())
    ck("matrix count", len(cm["capabilities"]) >= 15)
    ck("matrix honest", cm["summary"]["absent"] >= 1 and cm["summary"]["blocked"] >= 1 and cm["summary"]["partial"] >= 1)
    integrated = next(x for x in cm["capabilities"] if x["id"] == "INTEGRATED_12_SYSTEM_ORGANISM")
    ck("integrated organism absent", integrated["status"] == "ABSENT")
    ck("audit not a capability", cm["audit_is_not_a_new_capability"] is True)
    ck("non-claims", "no AGI" in cm["non_claims"] and "no established RSI" in cm["non_claims"])
    lin = json.loads((B / "E233_LINEAGE.json").read_text())
    ck("lineage latest E232", lin["lineage"][-2]["evolution"] == "E232")
    ck("lineage E233 audit", lin["lineage"][-1]["evolution"] == "E233" and "no new capability" in lin["lineage"][-1]["result"])
    ck("preserved", "E232" in lin["preserved"] and lin["no_overwrite"] is True)
    bl = json.loads((B / "E233_RESEARCH_BACKLOG.json").read_text())
    ck("backlog size", len(bl["items"]) >= 10)
    ck("backlog priorities", any(x["priority"] == "P0" for x in bl["items"]) and any(x["priority"] == "P1" for x in bl["items"]))
    ck("blocked items", any(x["status"] == "BLOCKED" for x in bl["items"]))
    docs = " ".join((B / n).read_text(errors="replace") for n in files if n.endswith(".md"))
    ck("status in docs", STATUS in docs)
    ck("audit is not a result", "not a new capability result" in docs.lower() or "no new capability" in docs.lower())
    ck("no AGI claim", "AGI: NOT ESTABLISHED" in docs and "AGI: ACHIEVED" not in docs)
    ck("governance partial", "PARTIAL" in (B / "E233_ULTIMATE_CAIN42_GOVERNANCE_INTEGRATION_AUDIT.md").read_text())
    ok = all(x["ok"] for x in checks)
    print(json.dumps({"checks": len(checks), "passed": sum(x["ok"] for x in checks), "ok": ok, "verification": "E233 forensic audit; no new capability claim"}))
    for x in checks:
        if not x["ok"]: print("FAIL", x["check"], x["detail"])
    return 0 if ok else 1


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