#!/usr/bin/env python3
"""E116 standalone verifier. Standard library only; imports no CAIN code."""
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())
    bad = [r for r, h in man["files"].items()
           if not (root / r).exists() or hashlib.sha256((root / r).read_bytes()).hexdigest() != h]
    check(f"manifest hashes ({len(man['files'])})", not bad, bad[:5])

    d = json.loads((root / "E116_RAW_RESULTS.json").read_text())
    base, gen, wm, trans, col, imp, adapt, gates = (d["baseline"], d["generalization"], d["world_model"],
                                                    d["transfer"], d["collective"], d["self_improvement"],
                                                    d["model_adaptation"], d["gates"])
    check("E115 baseline reproduced", base["tests"]["passed"] >= 18 and base["verifier"]["passed"] == 7, base["tests"])
    check("E115 is labelled interim, not full", "INTERIM" in str(base["e115_status"]).upper(), base["e115_status"])

    # generalization recomputation from raw rows
    for f, arms in gen["raw"].items():
        for a, rows in arms.items():
            got = sum(1 for r in rows if r["correct"]) / len(rows)
            check(f"{f} {a} accuracy recomputed", round(got, 4) == gen["per_family"][f][a]["accuracy"], got)
    promoted = sum(1 for s in gen["skills"] if s["promoted"])
    check("at least 4/5 skills promoted", promoted >= 4, promoted)
    cap = gen["capability"]
    check("capability acquired with sealed p<0.05", cap["acquired"] and cap["sealed"]["mcnemar_p"] < 0.05, cap["sealed"])
    check("capability replicated on second sealed set", cap["second_sealed"]["mcnemar_p"] < 0.05, cap["second_sealed"])
    check("memory improves over per-task", gen["memory_arms"]["M3_memory"] > gen["memory_arms"]["M2_per_task"],
          gen["memory_arms"])
    check("poisoned memory rejected", gen["poison"]["rejected"] is True)
    check("memory survives serialization", gen["restart"]["retained_accuracy"] > 0.9, gen["restart"])

    learned = [r for r in wm["results"] if r["model"] != "symbolic_true_mode"]
    best = max(learned, key=lambda r: r["accuracy"])
    check("best learned world model beats single table", best["accuracy"] > next(r for r in learned if r["model"] == "learned_single_table")["accuracy"], best)
    check("world-model shift detected", wm["shift_detection"] is True)

    check("transfer >=3 supported", trans["counts"]["statistically_supported"] >= 3, trans["counts"])
    check("harmful transfer rejected", trans["counts"]["negative_transfer_rejected"] >= 1, trans["counts"])
    check("routed collective beats best single", col["specialization"]["arms"]["C_specialist_team_routed"]["accuracy"] >
          col["specialization"]["arms"]["A_best_single_agent"]["accuracy"], col["specialization"]["arms"])
    check("redundant voting not claimed as gain", col["voting"]["gain_over_single_exact"] <= 0,
          col["voting"]["gain_over_single_exact"])
    check("self-improvement promotion withheld", imp.get("promotion", {}).get("enabled") is not True, imp.get("status"))
    check("small-model adaptation improves on baseline", adapt["improved"] is True, adapt)
    check("LLM fine-tuning marked BLOCKED", "BLOCKED" in adapt["llm_fine_tuning"], adapt["llm_fine_tuning"])
    check("no AGI claim", "did not" in d["claim"].lower() or "does NOT" in d["claim"], d["claim"])

    valid = {"PASS", "PARTIAL", "FAIL", "BLOCKED", "NOT TESTED"}
    check("gate statuses valid", all(v["status"] in valid for v in gates.values()))
    counts = {}
    for v in gates.values():
        counts[v["status"]] = counts.get(v["status"], 0) + 1
    check("gate counts consistent", counts == json.loads((root / "E116_GATE_MATRIX.json").read_text())["counts"], counts)
    check("no AGI gate claimed PASS", not any(k.lower().startswith("g_agi") and v["status"] == "PASS" for k, v in gates.items()))
    check("overall is PARTIAL", json.loads((root / "E116_GATE_MATRIX.json").read_text())["overall"] == "PARTIAL")

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


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