#!/usr/bin/env python3
"""E112 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 canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), default=str).encode()


def sha(o):
    return hashlib.sha256(o if isinstance(o, bytes) else canon(o)).hexdigest()


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 = [rel for rel, h in man["files"].items()
           if not (root / rel).exists() or hashlib.sha256((root / rel).read_bytes()).hexdigest() != h]
    check(f"manifest hashes ({len(man['files'])})", not bad, bad[:5])

    d = json.loads((root / "E112_LAB_RESULTS.json").read_text())
    pop = d["population"]
    check("2,000 agent identities created", pop["created"] == 2000 and pop["requested"] == 2000, pop["created"])
    check("identities are unique (id and public key)", pop["unique_ids"] == 2000 and pop["unique_public_keys"] == 2000)
    check("identity grants no authority", pop["grants_authority"] is False)
    check("six verticals represented", len(pop["verticals"]) == 6, pop["verticals"])
    check("2,000 tasks", d["tasks"]["count"] == 2000)

    waves = [w for w in d["scaling"] if w.get("status") != "BLOCKED"]
    workers = [w["workers"] for w in waves]
    check("scaling includes 1, 10, 100, 256 and 1,000 processes", all(x in workers for x in (1, 10, 100, 256, 1000)), workers)
    check("every scaling wave solved all 2,000 tasks", all(w["executed"] == 2000 for w in waves))
    check("quality is constant across worker counts", len({w["accuracy"] for w in waves}) == 1,
          [w["accuracy"] for w in waves])
    w1000 = next(w for w in waves if w["workers"] == 1000)
    check("1,000-process PSS is finite and below 8 GB", 0 < w1000["peak_pss_bytes"] < 8 * 1024 ** 3,
          w1000["peak_pss_bytes"])
    check("fan-out is overhead-dominated (1,000 slower than 1)", w1000["wall_s"] > waves[0]["wall_s"],
          (waves[0]["wall_s"], w1000["wall_s"]))
    check("12,000 governed agent executions", d["executions"]["scaling_waves"] + d["executions"]["additional_quality_wave"] >= 12000,
          d["executions"])

    V = ["software", "security", "mathematics", "science", "data", "business"]
    rows = d["last_wave_results"]
    per = {}
    for r in rows:
        if not r.get("executed"):
            continue
        v = V[int(r["task_id"][1:]) % 6]
        per.setdefault(v, [0, 0]); per[v][0] += 1; per[v][1] += int(r["correct"])
    recomputed = {k: round(c / n, 4) for k, (n, c) in per.items()}
    check("per-vertical accuracy recomputed from raw rows",
          all(abs(recomputed[k] - d["quality"]["by_vertical"][k]["accuracy"]) < 1e-9 for k in recomputed), recomputed)
    check("every execution carried a valid agent signature",
          all(r.get("executed") for r in rows) and all(r.get("sig") for r in rows))

    col = d["collective"]
    team = sum(1 for r in col["rows"] if r["majority_correct"]) / len(col["rows"])
    check("collective accuracy recomputed", round(team, 4) == col["team_accuracy"], round(team, 4))
    check("redundant voting is not claimed as a quality gain", col["gain_over_single_exact"] <= 0, col["gain_over_single_exact"])
    sp = d["specialization"]
    sp_rows = sp["rows"]
    for arm in ("A", "B", "C", "D"):
        got = sum(1 for r in sp_rows if r[arm]) / len(sp_rows)
        key = {"A": "A_best_single_agent", "B": "B_random_agent", "C": "C_specialist_team_routed", "D": "D_team_no_router"}[arm]
        check(f"specialization {arm} recomputed", round(got, 4) == sp["arms"][key]["accuracy"], got)
    check("routed specialist team beats the best single specialist", sp["arms"]["C_specialist_team_routed"]["accuracy"] > sp["arms"]["A_best_single_agent"]["accuracy"], sp["gain_C_vs_A"])

    ab = d["governance"]["ablations"]
    check("valid permit accepted", ab["valid_permit"]["ok"] is True, ab["valid_permit"])
    for k in ("missing_permit", "forged_signature", "task_substitution", "scope_mismatch"):
        check(f"{k} refused", ab[k]["ok"] is False, ab[k])

    ev = d["governance"]["receipt_events"]
    prev = "0" * 64; ok = True
    for e in ev:
        if e.get("prev") != prev or e.get("hash") != sha({k: e[k] for k in ("seq", "at", "prev", "event")}):
            ok = False; break
        prev = e["hash"]
    check("receipt chain verifies", ok and prev == d["governance"]["receipt_head"], len(ev))
    check("kill fence: zero effects after the order", d["kill"]["effects_after_kill"] == 0, d["kill"])
    check("kill fence: effects existed before the order", d["kill"]["effects_before_kill"] > 0)

    check("claim does not assert AGI", "No AGI" in d["claim"] or "no AGI" in d["claim"], d["claim"])
    gates = json.loads((root / "E112_GATE_MATRIX.json").read_text())
    valid = {"PASS", "PARTIAL", "FAIL", "BLOCKED", "NOT TESTED"}
    check("gate statuses valid", all(v["status"] in valid for v in gates["gates"].values()))
    check("no gate claims AGI achieved", gates["gates"].get("G10_agi", {}).get("status") != "PASS")

    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())
