#!/usr/bin/env python3
"""E237 campaign standalone verifier (imports no CAIN code).

Checks the campaign bundle: signature, hashes, Merkle, required documents,
status lines, forbidden overclaims, the G01–G20 registry, the adversarial lab
counts, the core-result summary, and (when present) the post-seal publication
record.

Usage: python3 -I verify_e237_campaign_offline.py <bundle-dir>
"""
import hashlib, json, re, sys
from pathlib import Path

STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
REQUIRED = ["E237_EXECUTIVE_SUMMARY.md", "E237_BASELINE_FORENSIC_REPORT.md", "E237_RESEARCH_BIBLIOGRAPHY.md",
            "E237_ARCHITECTURE.md", "E237_RESEARCH_ROADMAP.md", "E237_ACCEPTANCE_REGISTRY.json",
            "E237_PREREGISTRATION.md", "E237_EXPERIMENTAL_RESULTS.md", "E237_KNOWLEDGE_REPORT.md",
            "E237_TRANSFER_REPORT.md", "E237_CONTINUAL_LEARNING_REPORT.md", "E237_RSI_REPORT.md",
            "E237_GOVERNANCE_REPORT.md", "E237_FAILURES_AND_LIMITATIONS.md", "E237_REPLICATION_REPORT.md",
            "E237_PUBLICATION_REPORT.md", "E237_ADVERSARIAL_LAB.json", "E237_CAMPAIGN_SUMMARY.json",
            "verify_e237_campaign_offline.py"]
FORBIDDEN = ["agi achieved", "achieved agi", "agi-certified", "rsi established", "rsi is established",
             "unrestricted rsi", "court-admissible", "soc 2 certified", "production-ready",
             "artificial general intelligence achieved"]
EXTRA = {"MANIFEST.json", "MERKLE_ROOT.txt", "E237_CAMPAIGN_MANIFEST.json", "E237_CAMPAIGN_SIGNED_BODY.json",
         "E237_CAMPAIGN_VERIFICATION_RESULTS.json", "PUBLICATION.json", "E237_CAMPAIGN_OMEGA_SEAL.json",
         "E237_CAMPAIGN_TAMPER_RESULTS.json"}
ENGINE = {"engine.py", "durable.py", "permits.py", "campaign.py", "process.py", "run.py", "lab.py", "prereg.py"}


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).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(name, ok, detail=""):
        checks.append({"check": name, "ok": bool(ok), "detail": str(detail)[:300]})

    man = json.loads((B / "E237_CAMPAIGN_MANIFEST.json").read_text())
    ck("status", man.get("status") == STATUS)
    ck("label set", man.get("label") == "PARTIAL")
    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("manifest signature", True)
    except Exception as ex:
        ck("manifest 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("file hashes", not bad, bad[:3])
    ck("merkle root", 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}
    unlisted = sorted(present - set(files) - EXTRA)
    ck("no unlisted files", 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", ".sqlite")) for x in present))
    ck("required documents", all((B / n).exists() for n in REQUIRED), [n for n in REQUIRED if not (B / n).exists()])

    md = [p for p in B.glob("*.md")]
    ck("status line in every markdown", all(STATUS in p.read_text() for p in md),
       [p.name for p in md if STATUS not in p.read_text()])
    text = "\n".join(p.read_text(errors="replace").lower() for p in list(B.glob("*.md")) + list(B.glob("*.json")))
    hits = [f for f in FORBIDDEN if f in text]
    ck("no forbidden overclaims", not hits, hits)

    reg = json.loads((B / "E237_ACCEPTANCE_REGISTRY.json").read_text())
    gates = reg.get("gates", [])
    ck("20 gates", len(gates) == 20)
    ck("gate ids", [g["id"] for g in gates] == [f"G{i:02d}" for i in range(1, 21)])
    ck("gate statuses valid", all(g["status"] in ("PASS", "PARTIAL", "FAIL", "BLOCKED") for g in gates))
    counts = {s: sum(1 for g in gates if g["status"] == s) for s in ("PASS", "PARTIAL", "FAIL", "BLOCKED")}
    ck("gate counts recomputed", counts == reg.get("counts"), counts)
    ck("no unsupported PASS", all((B / g["artifact"]).exists() for g in gates if g["status"] == "PASS"),
       [g["id"] for g in gates if g["status"] == "PASS" and not (B / g["artifact"]).exists()])

    lab = json.loads((B / "E237_ADVERSARIAL_LAB.json").read_text())
    res = lab["results"]
    attacks = [c for c in res if c["status"] not in ("ALLOWED", "NOT_IMPLEMENTED")]
    ck("lab counts recomputed", lab["cases"] == len(res) and lab["attacks"] == len(attacks) and
       lab["attacks_blocked"] == sum(1 for c in attacks if c["blocked"]) and lab["all_attacks_blocked"])
    ck("controls allowed", [c["case"] for c in res if c["status"] == "ALLOWED"] and
       all(c["blocked"] is False for c in res if c["status"] == "ALLOWED"))
    ck("revocation disclosed", any(c["status"] == "NOT_IMPLEMENTED" and "revocation" in c["case"].lower() for c in res))

    cs = json.loads((B / "E237_CAMPAIGN_SUMMARY.json").read_text())
    ck("core verdict", cs["core"]["verdict"] == "PERSISTENT_GOVERNED_ORGANISM_SUPPORTED")
    ck("core hypotheses", all(v == "SUPPORTED" for v in cs["core"]["hypotheses"].values()))
    ck("core numbers", cs["core"]["episodes"] == 15 and cs["core"]["duplicate_effects"] == 0 and
       cs["core"]["lost_commits"] == [] and cs["core"]["recoveries"] >= 1)
    ck("core seal", cs["core"]["core_seal"] == "OMEGA-000000170")
    ck("core merkle format", bool(re.fullmatch(r"[0-9a-f]{64}", cs["core"]["core_merkle_root"] or "")))
    ck("campaign status", cs["campaign_status"] == "PARTIAL" and cs["gates"] == counts)
    ck("lab summary consistent", cs["lab"]["attacks_blocked"] == lab["attacks_blocked"] and cs["lab"]["cases"] == lab["cases"])

    pub = B / "PUBLICATION.json"
    if pub.exists():
        p = json.loads(pub.read_text())
        ck("publication seal", p.get("seal", "").startswith("OMEGA-") and p.get("seal_verdict") == "ALLOWED")
        ck("publication surfaces", all(k in p.get("surfaces", {}) for k in ("cainstudio", "mcpgate", "clawx", "huggingface")))
    else:
        ck("publication record pending (allowed at seal time)", True, "PUBLICATION.json is added post-seal")

    passed = sum(1 for c in checks if c["ok"])
    print(json.dumps({"schema": "cain42.e237.campaign_verify.v1", "checks": len(checks), "passed": passed,
                      "failed": [c for c in checks if not c["ok"]]}, ensure_ascii=False))
    return 0 if passed == len(checks) else 1


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