#!/usr/bin/env python3
"""E363-A standalone verifier (stdlib + cryptography; imports no CAIN code).

Recomputes every summary and every hypothesis from the raw rows, then checks the signed
manifest, the Merkle root, the preregistration freeze, the salt commitments, the hash chain
and the report consistency. Record-level: it does not re-execute the learner.
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
PANELS = ("honest3", "p3_m1_ad", "p3_m2_ad", "p5_m2_ad", "p5_m3_ad")
ARMS = ("single", "majority", "repair", "repair_shared")
SALTS = ("primary", "replication")
EX = {"E363A_MANIFEST.json", "E363A_SIGNED_BODY.json", "E363A_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E363A_OMEGA_SEAL.json",
      "E363A_TAMPER_RESULTS.json"}


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


def sha(b):
    return hashlib.sha256(b if isinstance(b, bytes) else b.encode()).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 arm_count(rows, salt, pname, arm):
    rs = [r for r in rows if r["salt"] == salt and r["panel"] == pname]
    if arm == "majority":
        return {"n": len(rs), "verified": sum(1 for r in rs if r["majority"]["verified"]),
                "false_accept": sum(1 for r in rs if r["majority"]["false_accept"]),
                "mean_labels": round(sum(r["majority"]["labels"] for r in rs) / len(rs), 2) if rs else None}
    if arm == "single":
        return {"n": len(rs), "verified": sum(1 for r in rs if r[arm]["verified"]),
                "false_accept": sum(1 for r in rs if r[arm]["false_accept"]),
                "mean_labels": round(sum(r[arm]["labels"] for r in rs) / len(rs), 2) if rs else None}
    return {"n": len(rs), "verified": sum(1 for r in rs if r[arm]["verified"]),
            "false_accept": sum(1 for r in rs if r[arm]["false_accept"]),
            "mean_labels": round(sum(r[arm]["labels"] for r in rs) / len(rs), 2) if rs else None,
            "mean_anchor_queries": round(sum(r[arm]["anchor_queries"] for r in rs) / len(rs), 2) if rs else None,
            "attribution_correct": sum(1 for r in rs if r[arm]["attribution_correct"]),
            "attribution_inverted": sum(1 for r in rs if r[arm]["attribution_inverted"])}


def panel_count(rows, pname, arm):
    rs = [r for r in rows if r["panel"] == pname]
    if arm == "majority":
        return {"n": len(rs), "verified": sum(1 for r in rs if r["majority"]["verified"]),
                "false_accept": sum(1 for r in rs if r["majority"]["false_accept"]),
                "mean_labels": round(sum(r["majority"]["labels"] for r in rs) / len(rs), 2) if rs else None}
    if arm == "single":
        return {"n": len(rs), "verified": sum(1 for r in rs if r[arm]["verified"]),
                "false_accept": sum(1 for r in rs if r[arm]["false_accept"]),
                "mean_labels": round(sum(r[arm]["labels"] for r in rs) / len(rs), 2) if rs else None}
    return {"n": len(rs), "verified": sum(1 for r in rs if r[arm]["verified"]),
            "false_accept": sum(1 for r in rs if r[arm]["false_accept"]),
            "mean_labels": round(sum(r[arm]["labels"] for r in rs) / len(rs), 2) if rs else None,
            "mean_anchor_queries": round(sum(r[arm]["anchor_queries"] for r in rs) / len(rs), 2) if rs else None,
            "attribution_correct": sum(1 for r in rs if r[arm]["attribution_correct"]),
            "attribution_inverted": sum(1 for r in rs if r[arm]["attribution_inverted"])}


def decide(rows):
    summ = {sn: {pn: {arm: arm_count(rows, sn, pn, arm) for arm in ARMS} for pn in PANELS} for sn in SALTS}
    p = {pn: {arm: panel_count(rows, pn, arm) for arm in ARMS} for pn in PANELS}
    q = summ["replication"]
    hold = ("p3_m1_ad", "p5_m2_ad")
    lost = ("p3_m2_ad", "p5_m3_ad")

    def v(pn, arm="majority"):
        return p[pn][arm]["verified"]

    def fa(pn, arm="majority"):
        return p[pn][arm]["false_accept"]

    H = {
        "H1_quorum_absorbs_adaptivity": {
            "verdict": "SUPPORTED" if all(v(pn) >= 18 and fa(pn) == 0 for pn in hold) else "NOT_SUPPORTED",
            "detail": "2-of-3 one adaptive liar and 3-of-5 two adaptive colluders each verify >=18/24 with 0 false accepts"},
        "H2_majority_labels_are_exact": {
            "verdict": "SUPPORTED" if all(r["majority"]["label_errors"] == 0 for r in rows
                                          if r["panel"] == "p3_m1_ad") else "NOT_SUPPORTED",
            "detail": "under 2-of-3 with one liar the majority label is the truth on every queried row (0 errors)"},
        "H3_lost_quorum_breaks": {
            "verdict": "SUPPORTED" if all(v(pn) <= 4 for pn in lost) else "NOT_SUPPORTED",
            "detail": "2-of-3 two adaptive colluders and 3-of-5 three adaptive colluders each verify <=4/24"},
        "H4_repair_restores_lost_quorum": {
            "verdict": "SUPPORTED" if all(v(pn, "repair") >= 18 and fa(pn, "repair") == 0 for pn in lost) else "NOT_SUPPORTED",
            "detail": "REPAIR verifies >=18/24 with 0 false accepts in both lost-quorum panels"},
        "H5_repair_is_cheap": {
            "verdict": ("SUPPORTED" if all((p[pn]["repair"]["mean_anchor_queries"] or 0) <= 20
                                           and (p[pn]["repair"]["mean_labels"] or 0)
                                           <= 3 * (p[pn]["majority"]["mean_labels"] or 1)
                                           for pn in lost) else "NOT_SUPPORTED"),
            "detail": "REPAIR uses <=20 anchor queries and <=3x the colony's labels in the lost-quorum panels"},
        "H6_shared_anchor_inverts_attribution": {
            "verdict": ("SUPPORTED" if all(p[pn]["repair_shared"]["attribution_inverted"] >= 18
                                           and v(pn, "repair_shared") <= 4 for pn in lost) else "NOT_SUPPORTED"),
            "detail": "a captured anchor quarantines the honest oracle(s) in >=18/24 lost-quorum episodes and verifies <=4/24 (the limit)"},
        "H7_replication": {
            "verdict": ("SUPPORTED" if (q["p3_m1_ad"]["majority"]["verified"] >= 9
                                        and q["p5_m2_ad"]["majority"]["verified"] >= 9
                                        and q["p3_m2_ad"]["majority"]["verified"] <= 2
                                        and q["p5_m3_ad"]["majority"]["verified"] <= 2
                                        and q["p3_m2_ad"]["repair"]["verified"] >= 9
                                        and q["p5_m3_ad"]["repair"]["verified"] >= 9) else "NOT_SUPPORTED"),
            "detail": "the replication salt repeats H1, H3 and H4 at >=9/12 or <=2/12"},
        "H8_external_review": {"verdict": "BLOCKED", "detail": "external review NOT OBTAINED"},
    }
    verdict = ("SELF_HEALING_COLONY_SUPPORTED"
               if all(H[k]["verdict"] == "SUPPORTED" for k in H if k != "H8_external_review")
               else "NOT_SUPPORTED")
    return summ, p, H, verdict


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

    def ck(n, c):
        checks.append((n, bool(c)))

    man = json.loads((d / "E363A_MANIFEST.json").read_text())
    pre = json.loads((d / "E363A_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E363A_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((d / "E363A_RUN_REPORT.json").read_text())
    salt = json.loads((d / "E363A_SALT_REVEALED.json").read_text())
    acc = json.loads((d / "E363A_ACCEPTANCE_REGISTRY.json").read_text())
    dev = json.loads((d / "E363A_DEVIATIONS.json").read_text())
    raw = json.loads((d / "E363A_RAW_ROWS.json").read_text())
    ck("schema", man.get("schema") == "cain42.e363a.manifest.v1" and rep.get("evolution") == "E363-A")
    files = sorted(p for p in d.rglob("*") if p.is_file() and str(p.relative_to(d)) not in EX
                   and "__pycache__" not in p.parts)
    ck("files", set(man["files"]) == {str(p.relative_to(d)) for p in files})
    ck("hashes", all(sha(p.read_bytes()) == man["files"][str(p.relative_to(d))] for p in files))
    ck("merkle", man["merkle_root"] == merkle(files))
    ck("merkle file", (d / "MERKLE_ROOT.txt").read_text().strip() == man["merkle_root"])
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    body = json.loads((d / "E363A_SIGNED_BODY.json").read_text())
    pub = Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
    pub.verify(bytes.fromhex(man["signature"]), canon(body))
    ck("signature", True)
    ck("freeze", sha((d / "E363A_PREREGISTRATION.json").read_bytes())
       == frz["preregistration_sha256"] == rep["preregistration_sha256"])
    ck("salts", all(sha(bytes.fromhex(v)) == pre["salt_commitment_sha256"][k]
                    for k, v in salt["salts"].items()))
    ck("source withheld", not any(q.name in ("run.py", "verify.py") for q in d.rglob("*") if q.is_file()))
    rows = rep["sets"]["primary"]["rows"] + rep["sets"]["replication"]["rows"]
    ck("episodes", len(rows) == 120 and len(raw) == 120)
    ck("raw rows", raw == rows)
    summ, p, H, verdict = decide(rows)
    ck("summary", summ == rep["summaries"])
    ck("verdict", verdict == rep["verdict"])
    ck("hypotheses", H == rep["hypotheses"])
    ch = [json.loads(l) for l in (d / "checkpoints/claim_chain.jsonl").read_text().splitlines()]
    prev = "0" * 64
    rec = []
    for r in rows:
        hh = sha((prev + sha(json.dumps(r, sort_keys=True, separators=(",", ":")))).encode())
        rec.append(hh)
        prev = hh
    ck("chain", [x["hash"] for x in ch] == rec
       and [x["prev"] for x in ch] == (["0" * 64] + rec[:-1]) and ch[-1]["hash"] == rep["checkpoint"]["head"])
    cp = json.loads((d / "checkpoints/claim_chain.json").read_text())
    ck("chain file", cp["count"] == len(ch) and cp["head"] == rec[-1])
    ck("report verdict", f"**Preregistered verdict: {rep['verdict']}.**" in (d / "E363A_FINAL_REPORT.md").read_text())
    ck("public summary", rep["verdict"] in (d / "E363A_PUBLIC_SUMMARY.md").read_text())
    ck("acceptance", acc["verdict"] == rep["verdict"])
    ck("deviations", isinstance(dev.get("deviations"), list) and len(dev["deviations"]) == 2
       and {x["id"] for x in dev["deviations"]} == {"D1", "D2"})
    ck("resources", rep["resources"]["model_calls"] == 0 and rep["resources"]["api_spend_usd"] == 0.0)
    ck("finding", rep["finding"]["episodes"] == len(rows) and rep["finding"]["worlds"] == 12
       and rep["finding"]["law"] == "adaptive adversaries are absorbed when n > 2m; attribution repairs n <= 2m")
    ck("audit", rep["design"]["audit_rows"] == 80)
    ck("status", rep["status"] == S and man["status"] == S)
    bad = [n for n, ok in checks if not ok]
    for n, ok in checks:
        print(("PASS " if ok else "FAIL ") + n)
    print(f"{len(checks) - len(bad)}/{len(checks)} checks passed")
    return 0 if not bad else 1


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