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

Recomputes the family structure and the denial price from the stored certificate row sets:
coverage masks, the min-rows table over the 2^k masks, the max one-row coverage, the hitting
number tau, the exact denial(b) curve, mean Jaccard and the per-certificate forgery. Checks
the SHA-256 claim chain, the preregistration hash, the salt commitments, the pinned E306
dependency hashes, the manifest signature, every file digest and the Merkle root. The engine
source is withheld, so the verifier is record-level.
"""
import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENG = ("family.py", "run.py")
DEPS = 5
GRAMMARS = ("A", "B")
P1 = ("honest3", "two_decoy3")
KS = (2, 4)
BMAX = 4
EX = {"E317_MANIFEST.json", "E317_SIGNED_BODY.json", "E317_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E317_OMEGA_SEAL.json",
      "E317_TAMPER_RESULTS.json", "E317_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)
    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 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 coverage(rowsets):
    cov = {}
    for i, rows in enumerate(rowsets):
        for r in rows:
            cov[r] = cov.get(r, 0) | (1 << i)
    return cov


def min_rows_table(cov, k):
    INF = 10 ** 6
    mr = [INF] * (1 << k)
    mr[0] = 0
    for m in cov.values():
        new = mr[:]
        for mask in range(1 << k):
            if mr[mask] + 1 < new[mask | m]:
                new[mask | m] = mr[mask] + 1
        mr = new
    return mr


def jac(a, b):
    sa, sb = set(a), set(b)
    return len(sa & sb) / len(sa | sb) if sa and sb else 0.0


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 / "E317_MANIFEST.json").read_text())
    ck("schema", man.get("schema") == "cain42.e317.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), sorted(present - set(files) - EX)[:5])
    ck("source withheld", not any((B / n).exists() for n in ENG))

    pre = json.loads((B / "E317_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E317_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E317_RUN_REPORT.json").read_text())
    rev = json.loads((B / "E317_SALT_REVEALED.json").read_text())
    ck("prereg hash", sha((B / "E317_PREREGISTRATION.json").read_bytes()) ==
       frz["preregistration_sha256"])
    ck("freeze before run", frz["frozen_at"] <= rep["generated_at"])
    ck("two salts", set(rev["salts"]) == {"primary", "replication"})
    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 / "E317_EXTERNAL_REVIEW_STATUS.json").read_text()).get("status") == "NOT_OBTAINED")
    ck("pinned dependency", len(pre.get("dependency_sha256", {})) == DEPS)
    ck("engine hashes", len(pre.get("engine_sha256", {})) == len(ENG))

    allr = []
    for salt in ("primary", "replication"):
        rows = rep["sets"][salt]["rows"]
        allr += rows
        ck(f"{salt} rows", len(rows) == 24, len(rows))
        ck(f"{salt} unique", len({(r["grammar"], r["p1"], r["world"]) for r in rows}) == 24)
    ck("total runs", len(allr) == 48, len(allr))

    bad = []
    for r in allr:
        if r["available"] != len(r["certs"]):
            bad.append(("available", r["grammar"], r["p1"], r["world"]))
        for k in KS:
            cell = r["k"].get(str(k))
            if cell is None:
                continue
            rowsets = [c["rows"] for c in r["certs"][:k]]
            cov = coverage(rowsets)
            mr = min_rows_table(cov, k)
            mc = max(m.bit_count() for m in cov.values()) if cov else 0
            tau = min(mr[m] for m in range(1 << k) if m.bit_count() == k)
            if cell["max_cover"] != mc:
                bad.append(("max_cover", k, r["grammar"], r["p1"], r["world"]))
            if cell["tau"] != tau:
                bad.append(("tau", k, r["grammar"], r["p1"], r["world"]))
            if cell["min_rows"] != mr:
                bad.append(("min_rows", k, r["grammar"], r["p1"], r["world"]))
            for b in range(0, k + 2):
                best = max((m.bit_count() for m in range(1 << k) if mr[m] <= b), default=0)
                if cell["denial"][str(b)]["covered"] != best:
                    bad.append(("denial_covered", k, b))
                if abs(cell["denial"][str(b)]["rate"] - best / k) > 1e-9:
                    bad.append(("denial_rate", k, b))
            mean_j = sum(jac(rowsets[a], rowsets[b]) for a in range(k) for b in range(a + 1, k)) / \
                max(1, k * (k - 1) // 2)
            if abs(cell["mean_jaccard"] - round(mean_j, 4)) > 1e-9:
                bad.append(("jaccard", k, r["grammar"], r["p1"], r["world"]))
    ck("family recomputation", not bad, bad[:5])

    cap = [r for r in allr if r["available"] >= 2 and not all(c["correct"] for c in r["certs"])]
    hon = [r for r in allr if r["available"] >= 2 and all(c["correct"] for c in r["certs"])]

    def cells(rows, k):
        return [r["k"][str(k)] for r in rows if str(k) in r["k"]]

    c4 = cells(cap, 4)
    c2 = cells(cap, 2)
    mc4 = sum(c["max_cover"] for c in c4) / max(1, len(c4))
    tau4 = sum(c["tau"] for c in c4) / max(1, len(c4))
    d1_4 = sum(c["denial"]["1"]["rate"] for c in c4) / max(1, len(c4))
    jac4 = sum(c["mean_jaccard"] for c in c4) / max(1, len(c4))
    ov = sum(1 for c in c4 if c["max_cover"] >= 2) / max(1, len(c4))
    tl = sum(1 for c in c4 if c["tau"] < 4) / max(1, len(c4))
    law = all(c["denial"]["1"]["covered"] == c["max_cover"] for c in c4 + c2)
    f = []
    for cell in c4:
        m = min(cell["ms"])
        if str(m) in cell["forgery"]:
            f.append(cell["forgery"][str(m)]["rate"])
    f4 = sum(f) / max(1, len(f))
    h1 = ov >= 0.5 and jac4 > 0
    h2 = d1_4 > 0.30
    h3 = tl >= 0.5
    h4 = law
    h5 = abs(f4 - 0.25) < 0.08
    rcap = [r for r in rep["sets"]["replication"]["rows"]
            if r["available"] >= 4 and not all(c["correct"] for c in r["certs"])]
    rc4 = cells(rcap, 4)
    h6 = (sum(1 for c in rc4 if c["max_cover"] >= 2) / max(1, len(rc4)) >= 0.5 and
          sum(c["denial"]["1"]["rate"] for c in rc4) / max(1, len(rc4)) > 0.30)
    exp = {"H1": h1, "H2": h2, "H3": h3, "H4": h4, "H5": h5, "H6": h6}
    H = rep["hypotheses"]
    ck("H1", H["H1_overlap_exists"]["verdict"] == ("SUPPORTED" if h1 else "NOT_SUPPORTED"),
       round(ov, 3))
    ck("H2", H["H2_one_lie_beats_one_over_k"]["verdict"] == ("SUPPORTED" if h2 else "NOT_SUPPORTED"),
       round(d1_4, 4))
    ck("H3", H["H3_hitting_number_below_k"]["verdict"] == ("SUPPORTED" if h3 else "NOT_SUPPORTED"),
       round(tau4, 3))
    ck("H4", H["H4_denial_equals_max_cover_over_k"]["verdict"] == ("SUPPORTED" if h4 else "NOT_SUPPORTED"))
    ck("H5", H["H5_forgery_price_unchanged"]["verdict"] == ("SUPPORTED" if h5 else "NOT_SUPPORTED"),
       round(f4, 4))
    ck("H6", H["H6_replication"]["verdict"] == ("SUPPORTED" if h6 else "NOT_SUPPORTED"))
    ck("H1 counts", abs(H["H1_overlap_exists"]["mean_jaccard_k4"] - jac4) < 0.0002 and
       abs(H["H1_overlap_exists"]["overlap_fraction_max_cover_ge_2"] - ov) < 0.0002)
    ck("H2 counts", abs(H["H2_one_lie_beats_one_over_k"]["mean_denial_b1_k4"] - d1_4) < 0.0002 and
       abs(H["H2_one_lie_beats_one_over_k"]["mean_max_cover_k4"] - mc4) < 0.002)
    ck("H3 counts", abs(H["H3_hitting_number_below_k"]["mean_tau_k4"] - tau4) < 0.002 and
       abs(H["H3_hitting_number_below_k"]["fraction_tau_lt_4"] - tl) < 0.0002)
    ck("H5 counts", abs(H["H5_forgery_price_unchanged"]["mean_forgery_at_min_m_k4"] - f4) < 0.0002)
    verdict = ("OVERLAP_GOVERNED_DENIAL_SUPPORTED" if all(exp.values()) else "NOT_SUPPORTED")
    ck("verdict", verdict == rep["verdict"] == man.get("label"))
    fnd = rep["finding"]
    ck("finding consistent", abs(fnd["mean_max_cover_k4"] - mc4) < 0.002 and
       abs(fnd["mean_tau_k4"] - tau4) < 0.002 and abs(fnd["mean_denial_b1_k4"] - d1_4) < 0.0002 and
       abs(fnd["mean_jaccard_k4"] - jac4) < 0.0002)
    ck("manifest headline", man.get("headline", {}).get("verdict") == verdict and
       man.get("headline", {}).get("runs") == 48 and
       abs(man.get("headline", {}).get("denial_b1_k4", -1) - d1_4) < 0.0002)

    ch = chain(allr)
    cp = json.loads((B / "checkpoints/claim_chain.json").read_text())
    ck("chain count", cp["count"] == 48)
    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 / "E317_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.e317.verify.v1", "checks": len(c),
                      "passed": passed, "failed": [x for x in c if not x["ok"]],
                      "verdict": verdict, "max_cover": round(mc4, 3), "tau": round(tau4, 3),
                      "denial_b1": round(d1_4, 4), "jaccard": round(jac4, 4)},
                     ensure_ascii=False))
    return 0 if passed == len(c) else 1


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