#!/usr/bin/env python3
"""E305 standalone verifier — stdlib + cryptography, imports no CAIN code.

Recomputes every summary and hypothesis from the raw rows, re-checks the quorum
logic against the per-panel rule hashes, and verifies the manifest, preregistration,
committed salts and checkpoint. Record-level: the engine is not re-executed.
"""
import hashlib
import json
import sys
from collections import Counter
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENG = {"world.py", "covers.py", "oracles.py", "learner.py", "pin.py", "audit.py", "run.py", "prereg.py"}
GR = ("A", "B")
CONDS = ("H_H_H", "D_H_H", "D_D_H", "D1_D2_H", "I_H_H")
ARMS = ("PIN", "RULE2", "RULE3", "ROW2")
WORLDS = 12


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 summ(rows):
    n = len(rows)
    return {"n": n,
            "accepted": sum(1 for r in rows if r["accepted"]),
            "accepted_correct": sum(1 for r in rows if r["accepted_correct"]),
            "false_accept": sum(1 for r in rows if r["false_accept"]),
            "correct": sum(1 for r in rows if r["correct"]),
            "abstain": sum(1 for r in rows if not r["accepted"]),
            "failed": sum(1 for r in rows if r.get("failed")),
            "mean_total_labels": sum(r["total_labels"] for r in rows) / n,
            "truth_in": sum(1 for r in rows if r["truth_in"])}


def main():
    B = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    c = []

    def ck(n, ok, d=""):
        c.append({"check": n, "ok": bool(ok), "detail": str(d)[:300]})

    man = json.loads((B / "E305_MANIFEST.json").read_text())
    ck("status", man.get("status") == S)
    ck("label", man.get("label") in ("RULE_LEVEL_CONSENSUS_SUPPORTED", "NOT_SUPPORTED"))
    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:  # noqa: BLE001
        ck("signature", False, ex)
    files = man.get("files", {})
    ck("files", all((B / k).exists() for k in files))
    ck("hashes", not [k for k, h in files.items() if (B / k).exists() and sha((B / k).read_bytes()) != h])
    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 = {"E305_MANIFEST.json", "E305_SIGNED_BODY.json", "E305_VERIFICATION_RESULTS.json", "MANIFEST.json",
             "MERKLE_ROOT.txt", "PUBLICATION.json", "E305_OMEGA_SEAL.json", "E305_TAMPER_RESULTS.json"}
    ck("no unlisted", not (present - set(files) - extra), sorted(present - set(files) - extra)[:5])
    ck("code withheld", not any((B / n).exists() for n in ENG))
    pre = json.loads((B / "E305_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E305_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E305_RUN_REPORT.json").read_text())
    rev = json.loads((B / "E305_SALT_REVEALED.json").read_text())
    ck("prereg hash", sha((B / "E305_PREREGISTRATION.json").read_bytes()) == frz["preregistration_sha256"])
    ck("freeze before run", frz["frozen_at"] <= rep["generated_at"])
    ck("salt commitments", all(sha(bytes.fromhex(rev["salts"][k])) == pre["salt_commitment_sha256"][k]
                               for k in rev["salts"]))
    ck("external not faked", json.loads((B / "E305_EXTERNAL_REVIEW_STATUS.json").read_text()).get("status") == "NOT_OBTAINED")
    d = pre["design"]
    ck("design conditions", tuple(d["conditions"]) == CONDS)
    ck("design grammars", d["grammars"]["A"] == {"features": 8, "terms": 3, "literals": 3}
       and d["grammars"]["B"] == {"features": 9, "terms": 4, "literals": 3})
    ck("design counts", d["worlds"]["cells"] == 240 and d["worlds"]["claims"] == 240
       and d["worlds"]["decisions"] == 960 and d["worlds"]["per_grammar_per_salt"] == WORLDS)
    ck("pilot disclosed", "pilot" in json.dumps(pre).lower())
    rec = rep["checkpoint"]
    cp = B / "checkpoints" / "gen0"
    ck("checkpoint chain", cp.exists() and sha((cp / "candidates.json").read_bytes()) == rec["candidates_sha256"]
       and sha((cp / "scores.json").read_bytes()) == rec["scores_sha256"])
    ch = json.loads((cp / "chain.json").read_text())
    ck("checkpoint hash", sha(json.dumps({k: v for k, v in ch.items() if k != "hash"}, sort_keys=True).encode()) == ch["hash"])
    ck("resume", rep["hypotheses"]["H10_checkpoint_resume"].get("resume") is True)
    for salt, st in rep["sets"].items():
        rows = st["rows"]
        ck(f"{salt} n", len(rows) == 480, len(rows))
        keys = [(r["grammar"], r["condition"], r["world"], r["arm"]) for r in rows]
        ck(f"{salt} cells", len(set(keys)) == len(rows) == 480
           and all(sum(1 for k in keys if k[0] == g and k[1] == c0 and k[3] == a) == WORLDS
                   for g in GR for c0 in CONDS for a in ARMS))
        ck(f"{salt} arithmetic", all(r["false_accept"] == (r["accepted"] and not r["correct"]) for r in rows)
           and all(r["accepted_correct"] == (r["accepted"] and r["correct"]) for r in rows))
        ck(f"{salt} hashes", all(len(r["panel_hashes"]) == 3 for r in rows))
        # Quorum logic is re-derived from the per-panel rule hashes.
        qok = True
        for r in rows:
            hs = r["panel_hashes"]
            if r["arm"] == "PIN":
                if r["accepted"] and r["rule_hash"] != hs[0]:
                    qok = False
            elif r["arm"] == "RULE2":
                want = bool(hs[0] and hs[1] and hs[0] == hs[1])
                if r["accepted"] != want or (want and r["rule_hash"] != hs[0]):
                    qok = False
            elif r["arm"] == "RULE3":
                cnt = Counter([h for h in hs if h])
                maj = next((h for h, k in cnt.items() if k >= 2), None)
                if r["accepted"] != (maj is not None) or (maj is not None and r["rule_hash"] != maj):
                    qok = False
            if r["accepted"] and r["correct"] != (r["rule_hash"] == r["truth_hash"]):
                qok = False
        ck(f"{salt} quorum", qok)
        for cond in CONDS:
            for arm in ARMS:
                k = f"{cond}|{arm}"
                exp = summ([r for r in rows if r["condition"] == cond and r["arm"] == arm])
                ck(f"{salt} {k}", exp == st["summary"][k], f"{exp} vs {st['summary'][k]}")
    rp = rep["sets"]["primary"]["rows"]
    rr = rep["sets"]["replication"]["rows"]

    def sel(rs, cond, arm):
        xs = [r for r in rs if r["condition"] == cond and r["arm"] == arm]
        return {"n": len(xs), "accepted": sum(1 for r in xs if r["accepted"]),
                "accepted_correct": sum(1 for r in xs if r["accepted_correct"]),
                "false_accept": sum(1 for r in xs if r["false_accept"]),
                "abstain": sum(1 for r in xs if not r["accepted"])}

    def safe(rs):
        return all(sel(rs, c0, "RULE3")["false_accept"] == 0 for c0 in ("H_H_H", "D_H_H", "I_H_H", "D1_D2_H"))

    def live(rs, cond):
        x = sel(rs, cond, "RULE3")
        return x["accepted_correct"] >= 0.9 * x["n"]

    h1 = safe(rp)
    h2 = live(rp, "D_H_H") and live(rp, "I_H_H")
    h3 = live(rp, "H_H_H") and sel(rp, "H_H_H", "RULE3")["accepted_correct"] >= 0.95 * sel(rp, "H_H_H", "RULE3")["n"]
    two = sel(rp, "D_D_H", "RULE3")
    h4 = two["false_accept"] >= 0.9 * two["n"]
    diff = sel(rp, "D1_D2_H", "RULE3")
    h5 = diff["accepted"] <= 0.1 * diff["n"] and diff["false_accept"] == 0
    r2d = sel(rp, "D_H_H", "RULE2")
    h6 = r2d["accepted"] <= 0.1 * r2d["n"] and live(rp, "D_H_H")
    h7 = (sel(rp, "D_H_H", "ROW2")["accepted_correct"] >= 0.9 * sel(rp, "D_H_H", "ROW2")["n"]
          and sel(rp, "I_H_H", "ROW2")["accepted_correct"] >= 0.9 * sel(rp, "I_H_H", "ROW2")["n"])
    pin_h = sum(r["total_labels"] for r in rp if r["condition"] == "H_H_H" and r["arm"] == "PIN")
    n_h = sum(1 for r in rp if r["condition"] == "H_H_H" and r["arm"] == "PIN")
    rule3_h = sum(r["total_labels"] for r in rp if r["condition"] == "H_H_H" and r["arm"] == "RULE3")
    h8 = rule3_h <= 3.2 * pin_h and pin_h / n_h <= 0.5 * 512
    h9 = (safe(rr) and live(rr, "D_H_H") and live(rr, "I_H_H")
          and sel(rr, "D_D_H", "RULE3")["false_accept"] >= 0.9 * sel(rr, "D_D_H", "RULE3")["n"]
          and sel(rr, "D1_D2_H", "RULE3")["accepted"] <= 0.1 * sel(rr, "D1_D2_H", "RULE3")["n"]
          and sel(rr, "D_H_H", "RULE2")["accepted"] <= 0.1 * sel(rr, "D_H_H", "RULE2")["n"])
    H = rep["hypotheses"]
    ck("H1 detail", H["H1_rule3_safety"]["by_condition"] == {c0: sel(rp, c0, "RULE3") for c0 in CONDS})
    ck("H2 detail", H["H2_one_decoy_liveness"]["D_H_H"] == sel(rp, "D_H_H", "RULE3")
       and H["H2_one_decoy_liveness"]["I_H_H"] == sel(rp, "I_H_H", "RULE3"))
    ck("H3 detail", H["H3_honest"]["H_H_H"] == sel(rp, "H_H_H", "RULE3"))
    ck("H4 detail", H["H4_two_decoy_limit"]["false_accept"] == two["false_accept"]
       and H["H4_two_decoy_limit"]["n"] == two["n"])
    ck("H5 detail", H["H5_different_decoys_abstain"]["accepted"] == diff["accepted"])
    ck("H6 detail", H["H6_rule2_liveness_gap"]["rule2_D_H_H"] == r2d)
    ck("H7 detail", H["H7_rowlevel_crosscheck"]["D_H_H"] == sel(rp, "D_H_H", "ROW2"))
    ck("H8 detail", H["H8_efficiency"]["pin_honest"] == round(pin_h / n_h, 2)
       and H["H8_efficiency"]["rule3_honest"] == round(rule3_h / n_h, 2))
    exp = {"H1_rule3_safety": h1, "H2_one_decoy_liveness": h2, "H3_honest": h3,
           "H4_two_decoy_limit": h4, "H5_different_decoys_abstain": h5,
           "H6_rule2_liveness_gap": h6, "H7_rowlevel_crosscheck": h7,
           "H8_efficiency": h8, "H9_replication": h9,
           "H10_checkpoint_resume": H["H10_checkpoint_resume"].get("resume") is True}
    for k, ok in exp.items():
        want = ("LIMIT_CONFIRMED" if ok else "NOT_CONFIRMED") if k == "H4_two_decoy_limit" else (
            "SUPPORTED" if ok else "NOT_SUPPORTED")
        ck(f"{k} verdict", H[k]["verdict"] == want, f"{H[k]['verdict']} vs {want}")
    verdict = "RULE_LEVEL_CONSENSUS_SUPPORTED" if all(exp.values()) else "NOT_SUPPORTED"
    ck("verdict", verdict == rep["verdict"] == man["label"], f"{verdict} vs {rep['verdict']}")
    ck("decisions", len(rp) + len(rr) == 960)
    ck("claims", len([r for r in rp + rr if r["arm"] == "PIN"]) == 240)
    hd = man.get("headline", {})
    ck("headline", hd.get("rule3_d_h_h_correct") == sel(rp, "D_H_H", "RULE3")["accepted_correct"]
       and hd.get("rule3_i_h_h_correct") == sel(rp, "I_H_H", "RULE3")["accepted_correct"]
       and hd.get("rule3_d_d_h_false") == two["false_accept"]
       and hd.get("rule3_diff_accepted") == diff["accepted"]
       and hd.get("rule2_d_h_h_accepted") == r2d["accepted"]
       and hd.get("claims") == 240 and hd.get("decisions") == 960)
    passed = sum(1 for x in c if x["ok"])
    print(json.dumps({"schema": "cain42.e305.verify.v1", "checks": len(c), "passed": passed,
                      "failed": [x for x in c if not x["ok"]], "verdict": verdict}, ensure_ascii=False))
    return 0 if passed == len(c) else 1


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