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

Re-derives every transfer arm from the stored coverage matrices and the stored schedules:
the per-world oracle (primal/dual certificates checked without solving an LP), the mean
transferred policy, the pooled robust schedule (primal feasibility, dual feasibility and
strong duality checked), the mean policy, nearest-source selection, and half-shrinkage.
Then recomputes the hypotheses and the verdict, and checks the chain, preregistration,
salt commitments, pinned dependency hashes, manifest signature and Merkle root.
"""
import hashlib
import json
import math
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENG = ("transfer.py", "run.py")
DEPS = 7
K = 4
EX = {"E331_MANIFEST.json", "E331_SIGNED_BODY.json", "E331_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E331_OMEGA_SEAL.json",
      "E331_TAMPER_RESULTS.json", "E331_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 deny(A, p):
    return max(sum(A[r][i] * p[i] for i in range(len(p))) for r in range(len(A))) if A else 0.0


def signature(A):
    return [sum(row[i] for row in A) / len(A) for i in range(len(A[0]))]


def sigdist(A, B):
    return sum(abs(x - y) for x, y in zip(signature(A), signature(B)))


def mean(xs):
    xs = list(xs)
    return sum(xs) / len(xs) if xs else 0.0


def shrink(p, eps=0.5):
    return [(1.0 - eps) * p[i] + eps / len(p) for i in range(len(p))]


def spearman(x, y):
    n = len(x)
    if n < 3:
        return 0.0

    def ranks(v):
        order = sorted(range(n), key=lambda i: v[i])
        r = [0.0] * n
        i = 0
        while i < n:
            j = i
            while j + 1 < n and v[order[j + 1]] == v[order[i]]:
                j += 1
            avg = (i + j) / 2.0 + 1.0
            for t in range(i, j + 1):
                r[order[t]] = avg
            i = j + 1
        return r

    rx, ry = ranks(x), ranks(y)
    mx, my = sum(rx) / n, sum(ry) / n
    num = sum((rx[i] - mx) * (ry[i] - my) for i in range(n))
    den = math.sqrt(sum((rx[i] - mx) ** 2 for i in range(n)) * sum((ry[i] - my) ** 2 for i in range(n)))
    return num / den if den else 0.0


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 / "E331_MANIFEST.json").read_text())
    ck("schema", man.get("schema") == "cain42.e331.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 / "E331_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E331_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E331_RUN_REPORT.json").read_text())
    rev = json.loads((B / "E331_SALT_REVEALED.json").read_text())
    ck("prereg hash", sha((B / "E331_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 / "E331_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))

    bad = []
    for salt in ("primary", "replication"):
        rows = rep["sets"][salt]["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)
        idx = {(r["grammar"], r["p1"], r["world"]): r for r in rows}
        for r in rows:
            cell = r["k4"]
            if not cell:
                continue
            A, p, t, w, lam = cell["A"], cell["p"], cell["t"], cell["w"], cell["lam"]
            rr = cell["rows"]
            if len(A) != len(rr) or len(w) != len(rr):
                bad.append(("lengths", salt, r["grammar"], r["p1"], r["world"]))
            if abs(sum(p) - 1) > 1e-6 or min(p) < -1e-8:
                bad.append(("primal_simplex", salt))
            if abs(sum(w) - 1) > 1e-6 or min(w) < -1e-8:
                bad.append(("dual_simplex", salt))
            for row in A:
                if sum(row[i] * p[i] for i in range(K)) > t + 1e-7:
                    bad.append(("primal_row", salt))
            for i in range(K):
                if sum(w[q] for q in range(len(rr)) if A[q][i]) < lam - 1e-7:
                    bad.append(("dual_cert", salt))
            if abs(t - lam) > 1e-6:
                bad.append(("duality", salt))
            if t > cell["uniform"] + 1e-6:
                bad.append(("worse_than_uniform", salt))
            if abs(cell["uniform"] - max(sum(row) for row in A) / K) > 1e-9:
                bad.append(("uniform", salt))
            if abs(t * cell["tau_star"] - 1) > 1e-6:
                bad.append(("tau_star", salt))
        # transfer arms
        for r in rows:
            tr = r["transfer"]
            if not tr:
                continue
            A = r["k4"]["A"]
            srcs = [idx.get((r["grammar"], r["p1"], w)) for w in tr["sources"]]
            if any(s is None or s is r or not s["k4"] or s["k4"]["correct"] for s in srcs):
                bad.append(("bad_sources", salt, r["grammar"], r["p1"], r["world"]))
                continue
            if len(srcs) < 2:
                bad.append(("too_few_sources", salt))
            ps = [s["k4"]["p"] for s in srcs]
            ds = [deny(A, p) for p in ps]
            expect = {
                "oracle": r["k4"]["t"],
                "uniform": r["k4"]["uniform"],
                "mean": mean(ds),
                "pool_avg": deny(A, [mean(p[i] for p in ps) for i in range(K)]),
                "shrink50": mean(deny(A, shrink(p)) for p in ps),
            }
            cand = sorted(range(len(srcs)), key=lambda j: (sigdist(A, srcs[j]["k4"]["A"]), srcs[j]["world"]))
            expect["nearest"] = ds[cand[0]]
            for k, v in expect.items():
                if abs(v - tr["arms"][k]) > 1e-9:
                    bad.append(("arm", k, salt, r["grammar"], r["p1"], r["world"], v, tr["arms"][k]))
            # pooled robust schedule: reconstruct the union of source rows
            union = [row for s in srcs for row in s["k4"]["A"]]
            pool = tr["pool"]
            pp, pt, pw, plam = pool["p"], pool["t"], pool["w"], pool["lam"]
            if abs(sum(pp) - 1) > 1e-6 or min(pp) < -1e-8:
                bad.append(("pool_primal_simplex", salt))
            if abs(sum(pw) - 1) > 1e-6 or min(pw) < -1e-8:
                bad.append(("pool_dual_simplex", salt))
            if len(pw) != len(union):
                bad.append(("pool_dual_length", salt))
            achieved = max(sum(row[i] * pp[i] for i in range(K)) for row in union)
            if abs(achieved - pt) > 1e-7:
                bad.append(("pool_value", salt))
            for row in union:
                if sum(row[i] * pp[i] for i in range(K)) > pt + 1e-7:
                    bad.append(("pool_primal_row", salt))
            for i in range(K):
                if sum(pw[q] for q in range(len(union)) if union[q][i]) < plam - 1e-7:
                    bad.append(("pool_dual_cert", salt))
            if abs(pt - plam) > 1e-6:
                bad.append(("pool_duality", salt))
            if abs(deny(A, pp) - tr["arms"]["pool_robust"]) > 1e-9:
                bad.append(("pool_arm", salt))
    ck("certificate and transfer certificates", not bad, bad[:6])

    # recompute hypotheses
    exp = {}
    pairs_all = {}
    summ = {}
    for salt in ("primary", "replication"):
        rows = rep["sets"][salt]["rows"]
        tg = [r for r in rows if r["transfer"]]
        pairs = []
        for r in tg:
            for s in r["transfer"]["sources"]:
                src = next(x for x in rows if x["grammar"] == r["grammar"] and x["p1"] == r["p1"] and x["world"] == s)
                pairs.append({"gap": deny(r["k4"]["A"], src["k4"]["p"]) - r["k4"]["t"],
                              "concentration": max(src["k4"]["p"]) - min(src["k4"]["p"])})
        A = {k: mean(r["transfer"]["arms"][k] for r in tg)
             for k in ("oracle", "uniform", "mean", "pool_robust", "pool_avg", "nearest", "shrink50")}
        n = len(tg)
        fo = sum(1 for r in tg if r["transfer"]["arms"]["oracle"] < r["transfer"]["arms"]["mean"] - 1e-9) / n
        fu = sum(1 for r in tg if r["transfer"]["arms"]["mean"] > r["transfer"]["arms"]["uniform"] + 1e-9) / n
        fp = sum(1 for r in tg if r["transfer"]["arms"]["pool_robust"] < r["transfer"]["arms"]["mean"] - 1e-9) / n
        rho = spearman([p["concentration"] for p in pairs], [p["gap"] for p in pairs])
        gaps = A["mean"] - A["oracle"]
        mu = A["mean"] - A["uniform"]
        pg = A["pool_robust"] - A["mean"]
        pu = A["pool_robust"] - A["uniform"]
        nd = A["nearest"] - A["mean"]
        su = A["shrink50"] - A["uniform"]
        H = {
            "H1_transfer_loses_to_oracle": (gaps >= 0.05 and fo >= 0.80, round(gaps, 4), round(fo, 4)),
            "H2_transfer_loses_to_uniform": (mu >= 0.02 and fu >= 0.80, round(mu, 4), round(fu, 4)),
            "H3_robust_pooling_helps": (pg <= -0.05 and fp >= 0.50, round(pg, 4), round(fp, 4)),
            "H4_robust_still_loses_to_uniform": (pu > 0.02, round(pu, 4)),
            "H5_concentration_predicts_fragility": (rho >= 0.30 and abs(nd) <= 0.02, round(rho, 4), round(nd, 4)),
            "H6_shrinkage_insufficient": (su >= 0.02, round(su, 4)),
        }
        exp[salt] = H
        pairs_all[salt] = pairs
        summ[salt] = {"targets": n, "arms": A}

    H = rep["hypotheses"]
    for k, v in exp["primary"].items():
        ck(f"{k} verdict", H[k]["verdict"] == ("SUPPORTED" if v[0] else "NOT_SUPPORTED"))
    ck("H1 value", abs(H["H1_transfer_loses_to_oracle"]["mean_gap"] - exp["primary"]["H1_transfer_loses_to_oracle"][1]) < 2e-4)
    ck("H2 value", abs(H["H2_transfer_loses_to_uniform"]["mean_transfer_minus_uniform"] - exp["primary"]["H2_transfer_loses_to_uniform"][1]) < 2e-4)
    ck("H3 value", abs(H["H3_robust_pooling_helps"]["mean_pool_minus_transfer"] - exp["primary"]["H3_robust_pooling_helps"][1]) < 2e-4)
    ck("H4 value", abs(H["H4_robust_still_loses_to_uniform"]["mean_pool_minus_uniform"] - exp["primary"]["H4_robust_still_loses_to_uniform"][1]) < 2e-4)
    ck("H5 value", abs(H["H5_concentration_predicts_fragility"]["spearman_concentration_gap"] - exp["primary"]["H5_concentration_predicts_fragility"][1]) < 2e-4)
    ck("H6 value", abs(H["H6_shrinkage_insufficient"]["mean_shrink50_minus_uniform"] - exp["primary"]["H6_shrinkage_insufficient"][1]) < 2e-4)
    h7 = (exp["replication"]["H1_transfer_loses_to_oracle"][1] >= 0.05
          and exp["replication"]["H2_transfer_loses_to_uniform"][1] >= 0.02
          and exp["replication"]["H4_robust_still_loses_to_uniform"][1] > 0.02
          and exp["replication"]["H6_shrinkage_insufficient"][1] >= 0.02)
    ck("H7 replication", H["H7_replication"]["verdict"] == ("SUPPORTED" if h7 else "NOT_SUPPORTED"))
    ck("H7 value", abs(H["H7_replication"]["replication_mean_gap"] - exp["replication"]["H1_transfer_loses_to_oracle"][1]) < 2e-4)
    ck("H7 value uniform", abs(H["H7_replication"]["replication_transfer_minus_uniform"] - exp["replication"]["H2_transfer_loses_to_uniform"][1]) < 2e-4)
    ck("H7 value pool", abs(H["H7_replication"]["replication_pool_minus_uniform"] - exp["replication"]["H4_robust_still_loses_to_uniform"][1]) < 2e-4)
    ck("H7 value shrink", abs(H["H7_replication"]["replication_shrink_minus_uniform"] - exp["replication"]["H6_shrinkage_insufficient"][1]) < 2e-4)
    ck("H8 external", H["H8_external_review"]["verdict"] == "BLOCKED")
    req = ["H1_transfer_loses_to_oracle", "H2_transfer_loses_to_uniform", "H3_robust_pooling_helps",
           "H4_robust_still_loses_to_uniform", "H5_concentration_predicts_fragility",
           "H6_shrinkage_insufficient", "H7_replication"]
    verdict = ("TRANSFER_FRAGILITY_CONFIRMED"
               if all(H[k]["verdict"] == "SUPPORTED" for k in req) else "NOT_SUPPORTED")
    ck("verdict", verdict == rep["verdict"] == man.get("label"))
    # headline consistency
    p = summ["primary"]["arms"]
    f = rep["finding"]
    ck("finding consistent",
       abs(f["mean_gap_primary"] - (p["mean"] - p["oracle"])) < 2e-4
       and abs(f["transfer_minus_uniform_primary"] - (p["mean"] - p["uniform"])) < 2e-4
       and abs(f["pool_minus_uniform_primary"] - (p["pool_robust"] - p["uniform"])) < 2e-4
       and abs(f["spearman_primary"] - exp["primary"]["H5_concentration_predicts_fragility"][1]) < 2e-4)
    hl = man.get("headline", {})
    ck("manifest headline", hl.get("verdict") == verdict and hl.get("targets") == summ["primary"]["targets"]
       and abs(hl.get("transfer_minus_uniform", -9) - (p["mean"] - p["uniform"])) < 2e-4
       and abs(hl.get("mean_gap", -9) - (p["mean"] - p["oracle"])) < 2e-4)
    ch = chain(rep["sets"]["primary"]["rows"] + rep["sets"]["replication"]["rows"])
    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("status line", S in (B / "E331_FINAL_REPORT.md").read_text())
    ck("limits present", len(rep.get("limits", [])) >= 5)
    ck("zero model calls", rep["resources"]["model_calls"] == 0)
    ck("no API spend", rep["resources"]["api_spend_usd"] == 0.0)
    passed = sum(1 for x in c if x["ok"])
    print(json.dumps({"schema": "cain42.e331.verify.v1", "checks": len(c), "passed": passed,
                      "failed": [x for x in c if not x["ok"]], "verdict": verdict,
                      "oracle": round(p["oracle"], 4), "uniform": round(p["uniform"], 4),
                      "transfer": round(p["mean"], 4), "pool": round(p["pool_robust"], 4),
                      "targets": summ["primary"]["targets"]}, ensure_ascii=False))
    return 0 if passed == len(c) else 1


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