#!/usr/bin/env python3
"""E110 standalone verifier. Standard library only; imports no CAIN code.

Checks the manifest, re-derives the integration summary and gate decisions, checks the transfer,
governance, long-horizon and negative-result records, and confirms this file has no CAIN imports.
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

C = []


def check(n, ok, d=""):
    C.append((n, bool(ok), str(d)))


def main():
    root = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    import ast
    tree = ast.parse(Path(__file__).read_text())
    banned = []
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            banned += [a.name for a in node.names if a.name.split(".")[0] == "cain"]
        elif isinstance(node, ast.ImportFrom) and (node.module or "").split(".")[0] == "cain":
            banned.append(node.module)
    check("verifier imports no CAIN code", not banned, banned)

    man = json.loads((root / "MANIFEST.json").read_text())
    ok = True
    for rel, h in man["files"].items():
        p = root / rel
        if not p.exists() or hashlib.sha256(p.read_bytes()).hexdigest() != h:
            ok = False
            check(f"hash {rel}", False)
    check(f"manifest hashes ({len(man['files'])})", ok)

    res = json.loads((root / "RESEARCH_LEDGER.json").read_text())
    rows = res.get("rows", [])
    s = {}
    for arm in ("A_base", "B_no_memory", "C_no_planning", "D_no_transfer", "E_full", "F_full_governance"):
        R = [r for r in rows if r["arm"] == arm]
        s[arm] = {"n": len(R), "solved": sum(1 for r in R if r["solved"]),
                  "attempts": sum(r["attempts"] for r in R) / len(R) if R else 0,
                  "false_accepts": sum(1 for r in R if r["false_accept"])}
        check(f"{arm}: rows", s[arm]["n"] == 7, s[arm]["n"])
    e, a, b, c, d = (s[k] for k in ("E_full", "A_base", "B_no_memory", "C_no_planning", "D_no_transfer"))
    check("E solves at least 5/7", e["solved"] >= 5, e["solved"])
    check("E beats every baseline", e["solved"] > max(a["solved"], b["solved"], c["solved"], d["solved"]),
          {k: v["solved"] for k, v in (("A", a), ("B", b), ("C", c), ("D", d))})
    check("memory lowers attempts", e["attempts"] < b["attempts"], (e["attempts"], b["attempts"]))
    check("no false accepts", e["false_accepts"] == 0, e["false_accepts"])

    ab = next((r for r in rows if r["mission"] == "M7_abstain" and r["arm"] == "E_full"), {})
    check("insufficient evidence -> abstain", ab.get("choice") == "ABSTAIN" and ab.get("solved"), ab.get("choice"))
    adv = [r for r in rows if r["mission"] == "M2_security" and r["arm"] == "E_full"]
    check("adversarial worker claim rejected", all(r.get("adversary_rejected") for r in adv), adv)

    tr = json.loads((root / "TRANSFER_RESULTS.json").read_text())
    v = tr.get("verdicts", {})
    per = v.get("G6_primary_per_pathway", {})
    positives = sum(1 for x in per.values() if x) if per else sum(1 for x in v.values() if x is True)
    check("transfer: 4 of 5 supported", positives >= 4, {"positive": positives, "verdicts": v})

    gov = json.loads((root / "GOVERNANCE_RESULTS.json").read_text())
    check("governance: baseline cases pass",
          gov.get("counts", {}).get("baseline", {}).get("passed", 0) >= 1, gov.get("counts"))
    check("kill fence", "R4" in json.dumps(gov.get("kill_fence", "")))

    lh = json.loads((root / "LONG_HORIZON_RESULTS.json").read_text())
    check("six-hour gate not claimed", lh.get("status") == "BLOCKED" and not lh.get("six_hours"), lh.get("actual_seconds"))

    gates = json.loads((root / "GATE_MATRIX.json").read_text())["gates"]
    check("G1 PASS", gates["G1"]["status"] == "PASS")
    check("G2 consistent", (gates["G2"]["status"] == "PASS") == (e["solved"] > max(a["solved"], b["solved"], c["solved"], d["solved"])))
    check("G8 BLOCKED", gates["G8"]["status"] == "BLOCKED")
    check("G17 BLOCKED", gates["G17"]["status"] == "BLOCKED")
    check("G18 FAIL", gates["G18"]["status"] == "FAIL")
    neg = (root / "NEGATIVE_RESULTS.md").read_text()
    for k, g in gates.items():
        if g["status"] != "PASS":
            check(f"negative ledger lists {k}", k in neg)

    passed = sum(1 for _, ok, _ in C if ok)
    for n, ok, d in C:
        print(("PASS " if ok else "FAIL ") + n + ("" if ok else f" :: {d}"))
    print(f"\n{passed}/{len(C)} checks passed")
    return 0 if passed == len(C) else 1


if __name__ == "__main__":
    raise SystemExit(main())
