#!/usr/bin/env python3
"""E314 standalone verifier — stdlib + cryptography, imports no CAIN code."""
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"}
CONDS = ("H", "U", "D", "D_D_H", "U_AUD_LIE")
NON_LIMIT = ("H", "U", "D", "D_D_H")
ARMS = ("PIN", "RULE3", "LADDER", "VERIFY", "VERIFY_ESC")
WORLDS = {"A": 12, "B": 4}


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")),
            "escalated": sum(1 for r in rows if r["escalated"]),
            "verified": sum(1 for r in rows if r["verified"]),
            "mean_total_labels": sum(r["total_labels"] for r in rows) / n,
            "mean_audit_checks": sum(r["audit_checks"] for r in rows) / n,
            "mean_identification_labels": sum(r["identification_labels"] for r in rows) / n}


def replay(chs, trace):
    idx = list(range(len(chs)))
    for step in trace:
        bits = step["bits"]
        if len(bits) != len(idx):
            return None
        idx = [i for j, i in enumerate(idx) if bits[j] == step["p4"]]
    return [chs[i] for i in idx]


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 / "E314_MANIFEST.json").read_text())
    ck("status", man.get("status") == S)
    ck("label", man.get("label") in ("UNANIMOUS_PATH_VERIFIED", "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 = {"E314_MANIFEST.json", "E314_SIGNED_BODY.json", "E314_VERIFICATION_RESULTS.json", "MANIFEST.json",
             "MERKLE_ROOT.txt", "PUBLICATION.json", "E314_OMEGA_SEAL.json", "E314_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 / "E314_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E314_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E314_RUN_REPORT.json").read_text())
    rev = json.loads((B / "E314_SALT_REVEALED.json").read_text())
    ck("prereg hash", sha((B / "E314_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 / "E314_EXTERNAL_REVIEW_STATUS.json").read_text()).get("status") == "NOT_OBTAINED")
    d = pre["design"]
    ck("design conditions", tuple(d["conditions"]) == CONDS)
    ck("design counts", d["cells"] == 160 and d["claims"] == 160 and d["decisions"] == 800
       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"]["H6_checkpoint_resume"].get("resume") is True)
    for salt, st in rep["sets"].items():
        rows = st["rows"]
        ck(f"{salt} n", len(rows) == 400, len(rows))
        keys = [(r["grammar"], r["condition"], r["world"], r["arm"]) for r in rows]
        ck(f"{salt} cells", len(set(keys)) == len(rows)
           and all(sum(1 for k in keys if k[0] == g and k[1] == c0 and k[3] == a) == WORLDS[g]
                   for g in WORLDS for c0 in CONDS for a in ARMS))
        qok = True
        for r in rows:
            hs, chs = r["panel_hashes"], r["candidate_hashes"]
            if sorted(chs) != sorted(set(h for h in hs if h)):
                qok = False
            if r["escalated"]:
                if r["verified"] is not True or r["audit_checks"] != 0:
                    qok = False
            if r["arm"] == "PIN":
                if r["accepted"] != r["panel_accepted"][0] or (r["accepted"] and r["rule_hash"] != hs[0]):
                    qok = False
                if r["trace"] or r["total_labels"] != r["p1_labels"] or r["audit_checks"] != 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["trace"] or r["total_labels"] != r["identification_labels"] or r["audit_checks"] != 0:
                    qok = False
            elif r["arm"] == "LADDER":
                if not r["escalated"]:
                    if r["accepted"] != r["panel_accepted"][0] or (r["accepted"] and r["rule_hash"] != hs[0]):
                        qok = False
                    if r["trace"] or r["total_labels"] != r["p1_labels"] or r["audit_checks"] != 0:
                        qok = False
                else:
                    surv = replay(chs, r["trace"])
                    if surv is None or r["accepted"] != (len(surv) == 1):
                        qok = False
                    elif r["accepted"] and r["rule_hash"] != surv[0]:
                        qok = False
                    if r["total_labels"] != r["identification_labels"] + len(r["trace"]):
                        qok = False
            elif r["arm"] == "VERIFY":
                if r["escalated"]:
                    surv = replay(chs, r["trace"])
                    if surv is None or r["accepted"] != (len(surv) == 1):
                        qok = False
                    elif r["accepted"] and r["rule_hash"] != surv[0]:
                        qok = False
                    if r["total_labels"] != r["identification_labels"] + len(r["trace"]):
                        qok = False
                else:
                    want = bool(r["panel_accepted"][0] and r["verified"])
                    if r["accepted"] != want or (want and r["rule_hash"] != hs[0]):
                        qok = False
                    if r["trace"] or r["total_labels"] != r["p1_labels"] + r["audit_checks"]:
                        qok = False
            else:  # VERIFY_ESC
                if r["escalated"] or (not r["escalated"] and not r["verified"]):
                    surv = replay(chs, r["trace"])
                    if surv is None or r["accepted"] != (len(surv) == 1):
                        qok = False
                    elif r["accepted"] and r["rule_hash"] != surv[0]:
                        qok = False
                    if r["total_labels"] != r["identification_labels"] + len(r["trace"]):
                        qok = False
                else:
                    want = bool(r["panel_accepted"][0] and r["verified"])
                    if r["accepted"] != want or (want and r["rule_hash"] != hs[0]):
                        qok = False
                    if r["trace"] or r["total_labels"] != r["p1_labels"] + r["audit_checks"]:
                        qok = False
            if r["accepted"] and r["correct"] != (r["rule_hash"] == r["truth_hash"]):
                qok = False
        ck(f"{salt} verify trace", 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, rr = rep["sets"]["primary"]["rows"], 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"]),
                "escalated": sum(1 for r in xs if r["escalated"]),
                "mean_total_labels": sum(r["total_labels"] for r in xs) / len(xs),
                "mean_audit_checks": sum(r["audit_checks"] for r in xs) / len(xs)}

    def safe(rs, arm):
        return all(sel(rs, c0, arm)["false_accept"] == 0 for c0 in NON_LIMIT)

    h1 = safe(rp, "VERIFY") and safe(rp, "VERIFY_ESC")
    lad_u, ver_u, esc_u = sel(rp, "U", "LADDER"), sel(rp, "U", "VERIFY"), sel(rp, "U", "VERIFY_ESC")
    h2 = (lad_u["false_accept"] >= 0.9 * lad_u["n"] and ver_u["accepted"] <= 0.1 * ver_u["n"]
          and esc_u["accepted_correct"] >= 0.9 * esc_u["n"])
    pin_h = sel(rp, "H", "PIN")["mean_total_labels"]
    rule_h = sel(rp, "H", "RULE3")["mean_total_labels"]
    ver_h = sel(rp, "H", "VERIFY")["mean_total_labels"]
    esc_h = sel(rp, "H", "VERIFY_ESC")["mean_total_labels"]
    h3 = ver_h <= 0.75 * rule_h and esc_h <= 0.75 * rule_h and ver_h >= pin_h and esc_h >= pin_h
    lie_v, lie_e = sel(rp, "U_AUD_LIE", "VERIFY"), sel(rp, "U_AUD_LIE", "VERIFY_ESC")
    h4 = lie_v["false_accept"] >= 1 and lie_e["false_accept"] >= 1
    h5 = (safe(rr, "VERIFY") and safe(rr, "VERIFY_ESC")
          and sel(rr, "U", "LADDER")["false_accept"] >= 0.9 * sel(rr, "U", "LADDER")["n"]
          and sel(rr, "U", "VERIFY")["accepted"] <= 0.1 * sel(rr, "U", "VERIFY")["n"]
          and sel(rr, "U", "VERIFY_ESC")["accepted_correct"] >= 0.9 * sel(rr, "U", "VERIFY_ESC")["n"]
          and sel(rr, "U_AUD_LIE", "VERIFY")["false_accept"] >= 1)
    H = rep["hypotheses"]
    for k, ok in (("H1_verify_safety", h1), ("H2_unanimous_capture", h2), ("H3_honest_cost", h3),
                  ("H5_replication", h5)):
        ck(f"{k} verdict", H[k]["verdict"] == ("SUPPORTED" if ok else "NOT_SUPPORTED"))
    ck("H4_auditor_lie_limit verdict", H["H4_auditor_lie_limit"]["verdict"] == (
        "LIMIT_CONFIRMED" if h4 else "NOT_CONFIRMED"))
    ck("H1 detail", H["H1_verify_safety"]["by_condition"] == {c0: sel(rp, c0, "VERIFY") for c0 in CONDS})
    ck("H2 detail", H["H2_unanimous_capture"]["ladder"] == lad_u
       and H["H2_unanimous_capture"]["verify"] == ver_u
       and H["H2_unanimous_capture"]["verify_esc"] == esc_u)
    ck("H3 detail", H["H3_honest_cost"]["verify"] == round(ver_h, 3)
       and H["H3_honest_cost"]["verify_esc"] == round(esc_h, 3)
       and H["H3_honest_cost"]["rule3"] == round(rule_h, 3))
    ck("H4 detail", H["H4_auditor_lie_limit"]["verify"] == lie_v
       and H["H4_auditor_lie_limit"]["verify_esc"] == lie_e)
    verdict = "UNANIMOUS_PATH_VERIFIED" if all([h1, h2, h3, h4, h5,
                                               H["H6_checkpoint_resume"].get("resume") is True]) else "NOT_SUPPORTED"
    ck("verdict", verdict == rep["verdict"] == man["label"], f"{verdict} vs {rep['verdict']}")
    ck("decisions", len(rp) + len(rr) == 800)
    ck("claims", len([r for r in rp + rr if r["arm"] == "PIN"]) == 160)
    hd = man.get("headline", {})
    ck("headline", hd.get("verify_u_rejected") == ver_u["abstain"]
       and hd.get("esc_u_correct") == esc_u["accepted_correct"]
       and hd.get("ladder_u_false") == lad_u["false_accept"]
       and hd.get("verify_h_labels") == round(ver_h, 2)
       and hd.get("rule3_h_labels") == round(rule_h, 2)
       and hd.get("verify_lie_false") == lie_v["false_accept"]
       and hd.get("claims") == 160 and hd.get("decisions") == 800)
    passed = sum(1 for x in c if x["ok"])
    print(json.dumps({"schema": "cain42.e314.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())
