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

Recomputes the two-decoy statistics, the anchor-completeness hypotheses, the verdict and the
SHA-256 claim chain from raw rows. Verifies the preregistration, salt commitments, manifest
signature, every file digest and the Merkle root.
"""
import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENG = ("world.py", "oracles.py", "enumerate.py", "covers.py", "identify.py", "run.py")
GRAMMARS = ("A", "B")
PANELS = ("honest4", "two_decoy4")
ARMS = ("TRUTH", "P2_ONE", "P2_SHARED", "NONE")
EX = {"E326_MANIFEST.json", "E326_SIGNED_BODY.json", "E326_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E326_OMEGA_SEAL.json",
      "E326_TAMPER_RESULTS.json", "E326_ACCEPTANCE_REGISTRY.json"}


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)
    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] if leaves else sha(b"")


def summary(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"] and r["correct"]),
        "false_accept": sum(1 for r in rows if r["false_accept"]),
        "failed": sum(1 for r in rows if r["failed"]),
        "mean_labels": sum(r["labels"] for r in rows) / n,
        "mean_anchor_queries": sum(r["anchor_queries"] for r in rows) / n,
        "mean_split_rows": sum(r["split_rows"] for r in rows) / n,
        "mean_wrong_anchors": sum(r["wrong_anchors"] for r in rows) / n,
        "truth_in": sum(1 for r in rows if r["truth_in"]),
    }


def chain(rows):
    prev = "0" * 64
    out = []
    for r in rows:
        h = sha((prev + sha(canon(r))).encode())
        out.append({"i": len(out), "prev": prev, "hash": h})
        prev = h
    return out


def stats(rows, panel, arm):
    rs = [r for r in rows if r["panel"] == panel and r["arm"] == arm]
    return {"n": len(rs),
            "acc": sum(1 for r in rs if r["accepted"] and r["correct"]),
            "fa": sum(1 for r in rs if r["false_accept"]),
            "failed": sum(1 for r in rs if r["failed"]),
            "anchors": sum(r["anchor_queries"] for r in rs) / max(1, len(rs)),
            "wrong_anchors": sum(r["wrong_anchors"] for r in rs) / max(1, len(rs))}


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

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

    man = json.loads((B / "E326_MANIFEST.json").read_text())
    ck("schema", man.get("schema") == "cain42.e326.manifest.v1")
    ck("status", man.get("status") == S)
    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:
        ck("signature", False, ex)
    files = man.get("files", {})
    ck("files present", all((B / k).exists() for k in files))
    ck("file 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}
    ck("no unlisted file", not (present - set(files) - EX))
    ck("source withheld", not any((B / n).exists() for n in ENG))

    pre = json.loads((B / "E326_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E326_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E326_RUN_REPORT.json").read_text())
    rev = json.loads((B / "E326_SALT_REVEALED.json").read_text())
    ck("prereg hash", sha((B / "E326_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 / "E326_EXTERNAL_REVIEW_STATUS.json").read_text()).get("status") == "NOT_OBTAINED")

    allr = []
    for salt in ("primary", "replication"):
        st = rep["sets"][salt]
        rows = st["rows"]
        allr += rows
        ck(f"{salt} rows", len(rows) == 128, len(rows))
        ck(f"{salt} unique", len({(r["grammar"], r["panel"], r["arm"], r["world"]) for r in rows}) == 128)
        for g in GRAMMARS:
            for p in PANELS:
                for a in ARMS:
                    k = f"{g}|{p}|{a}"
                    ck(f"{salt} {k}", summary([r for r in rows if r["grammar"] == g and
                                               r["panel"] == p and r["arm"] == a]) == st["summary"][k])
    ck("total claims", len(allr) == 256, len(allr))

    rp = rep["sets"]["primary"]["rows"]
    rr = rep["sets"]["replication"]["rows"]
    tp = {a: stats(rp, "two_decoy4", a) for a in ARMS}
    tr = {a: stats(rr, "two_decoy4", a) for a in ARMS}
    honest = [r for r in allr if r["panel"] == "honest4"]
    h1 = all(tp[a]["fa"] == 0 and tp[a]["acc"] >= 0.95 * tp[a]["n"] and
             tr[a]["fa"] == 0 and tr[a]["acc"] >= 0.95 * tr[a]["n"] for a in ("TRUTH", "P2_ONE"))
    h2 = tp["P2_SHARED"]["fa"] >= 1
    h3 = tp["NONE"]["fa"] >= 1
    h4 = all((r["accepted"] and r["correct"] and r["anchor_queries"] == 0) for r in honest)
    h5 = h1 and tr["P2_SHARED"]["fa"] >= 1 and tr["NONE"]["fa"] >= 1
    exp = {"H1_fallible_verifier_exact": h1, "H2_shared_verifier_fails": h2,
           "H3_no_verifier_fails": h3, "H4_honest_needs_no_verifier": h4,
           "H5_replication": h5}
    H = rep["hypotheses"]
    for k, ok in exp.items():
        ck(f"{k} verdict", H[k]["verdict"] == ("SUPPORTED" if ok else "NOT_SUPPORTED"))
    ck("H1 stats", H["H1_fallible_verifier_exact"]["primary"] == {a: tp[a] for a in ("TRUTH", "P2_ONE")} and
       H["H1_fallible_verifier_exact"]["replication"] == {a: tr[a] for a in ("TRUTH", "P2_ONE")})
    ck("H2 count", H["H2_shared_verifier_fails"]["shared_false_primary"] == tp["P2_SHARED"]["fa"])
    ck("H3 count", H["H3_no_verifier_fails"]["none_false_primary"] == tp["NONE"]["fa"])
    ck("two-decoy report", rep["two_decoy"]["primary"] == tp and rep["two_decoy"]["replication"] == tr)
    verdict = ("FALLIBLE_VERIFIER_COMPLETENESS_SUPPORTED" if all(exp.values()) else "NOT_SUPPORTED")
    ck("verdict", verdict == rep["verdict"] == man.get("label"))
    ck("manifest headline", man.get("headline", {}).get("verdict") == rep["verdict"] and
       man.get("headline", {}).get("claims") == 256)
    ck("resources counts", rep["resources"]["claims"] == 256 and
       rep["resources"]["decisions"] == 256)
    for a in ARMS:
        rs = [r for r in allr if r["arm"] == a]
        rate = sum(r["anchor_queries"] for r in rs) / max(1, sum(r["labels"] for r in rs))
        ck(f"anchor rate {a}", abs(rep["anchor_rate"][a] - rate) < 1e-4)

    ch = chain(allr)
    cp = json.loads((B / "checkpoints/claim_chain.json").read_text())
    ck("chain count", cp["count"] == 256)
    ck("chain head", cp["head"] == ch[-1]["hash"])
    ck("chain mid", cp["mid"] == ch[len(ch) // 2]["hash"])
    ck("chain recompute", sha((ch[-2]["hash"] + sha(canon(allr[-1]))).encode()) == ch[-1]["hash"])
    ck("status line", S in (B / "E326_FINAL_REPORT.md").read_text())
    ck("limits present", len(rep.get("limits", [])) >= 5)
    ck("zero model calls", rep["resources"]["model_calls"] == 0)

    passed = sum(1 for x in c if x["ok"])
    print(json.dumps({"schema": "cain42.e326.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())
