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

Re-derives every cost-constrained LP certificate: primal feasibility (A p <= t, simplex,
c . p <= B), dual feasibility (sum w = 1, A^T w + mu c >= nu, mu >= 0) and strong duality
(t = nu - mu B). Then recomputes the arms, 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 sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENG = ("budget.py", "run.py")
DEPS = 7
K = 4
EX = {"E333_MANIFEST.json", "E333_SIGNED_BODY.json", "E333_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E333_OMEGA_SEAL.json",
      "E333_TAMPER_RESULTS.json", "E333_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 mean(xs):
    xs = list(xs)
    return sum(xs) / len(xs) if xs 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 / "E333_MANIFEST.json").read_text())
    ck("schema", man.get("schema") == "cain42.e333.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 / "E333_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E333_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E333_RUN_REPORT.json").read_text())
    rev = json.loads((B / "E333_SALT_REVEALED.json").read_text())
    ck("prereg hash", sha((B / "E333_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 / "E333_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)
        for r in rows:
            bud = r["budget"]
            if not bud:
                continue
            A = r["k4"]["A"]
            costs = bud["costs"]
            if costs != [x["size"] for x in r["certs"][:K]]:
                bad.append(("costs", salt))
            free = r["k4"]
            p, t, w, mu, nu = free["p"], free["t"], free["w"], None, free["lam"]
            # the free certificate is the grid at B = max cost
            gf = bud["grid"][bud["free_index"]]
            if abs(gf["B"] - max(costs)) > 1e-9:
                bad.append(("free_B", salt))
            if abs(gf["t"] - t) > 1e-7 or abs(gf["p"][0] - p[0]) > 1e-7:
                bad.append(("free_arm", salt))
            if abs(sum(p) - 1) > 1e-6 or min(p) < -1e-8:
                bad.append(("free_simplex", salt))
            for row in A:
                if sum(row[i] * p[i] for i in range(K)) > t + 1e-7:
                    bad.append(("free_primal", salt))
            if abs(sum(gf["w"]) - 1) > 1e-6 or min(gf["w"]) < -1e-8:
                bad.append(("free_dual_simplex", salt))
            for i in range(K):
                if sum(gf["w"][q] for q in range(len(A)) if A[q][i]) + gf["mu"] * costs[i] < gf["nu"] - 1e-7:
                    bad.append(("free_dual_cert", salt))
            if abs(gf["nu"] - gf["mu"] * gf["B"] - t) > 1e-6:
                bad.append(("free_duality", salt))
            # every budget point
            for g in bud["grid"]:
                pp, tt, ww, nnu, mm = g["p"], g["t"], g["w"], g["nu"], g["mu"]
                if abs(sum(pp) - 1) > 1e-6 or min(pp) < -1e-8:
                    bad.append(("primal_simplex", salt))
                if sum(costs[i] * pp[i] for i in range(K)) > g["B"] + 1e-7:
                    bad.append(("primal_cost", salt))
                for row in A:
                    if sum(row[i] * pp[i] for i in range(K)) > tt + 1e-7:
                        bad.append(("primal_row", salt))
                if abs(sum(ww) - 1) > 1e-6 or min(ww) < -1e-8 or mm < -1e-9:
                    bad.append(("dual_simplex", salt))
                for i in range(K):
                    if sum(ww[q] for q in range(len(A)) if A[q][i]) + mm * costs[i] < nnu - 1e-7:
                        bad.append(("dual_cert", salt))
                if abs(nnu - mm * g["B"] - tt) > 1e-6:
                    bad.append(("duality", salt))
                if abs(sum(costs[i] * pp[i] for i in range(K)) - g["cost"]) > 1e-7:
                    bad.append(("cost_value", salt))
            if any(bud["grid"][j + 1]["t"] > bud["grid"][j]["t"] + 1e-9
                   for j in range(len(bud["grid"]) - 1)):
                bad.append(("monotone", salt, r["grammar"], r["p1"], r["world"]))
            if abs(bud["grid"][bud["match_index"]]["B"] - bud["uniform"]["cost"]) > 1e-9:
                bad.append(("match_B", salt))
            if abs(bud["uniform"]["t"] - free["uniform"]) > 1e-9:
                bad.append(("uniform", salt))
            ci = min(range(K), key=lambda j: (costs[j], j))
            if ci != bud["cheapest"]["index"]:
                bad.append(("cheapest_index", salt))
            cp = [0.0] * K
            cp[ci] = 1.0
            if abs(max(sum(A[q][i] * cp[i] for i in range(K)) for q in range(len(A))) - bud["cheapest"]["t"]) > 1e-9:
                bad.append(("cheapest_t", salt))
    ck("cost-constrained LP certificates", not bad, bad[:6])

    def analyse(salt):
        fam = [r for r in rep["sets"][salt]["rows"] if r["budget"]]
        gains = [r["budget"]["uniform"]["t"] - r["budget"]["grid"][r["budget"]["match_index"]]["t"] for r in fam]
        strict = sum(1 for g in gains if g > 1e-9)
        dev = [abs(r["k4"]["free_cost"] - r["budget"]["uniform"]["cost"]) / r["budget"]["uniform"]["cost"] for r in fam]
        mono = all(all(r["budget"]["grid"][j + 1]["t"] <= r["budget"]["grid"][j]["t"] + 1e-9
                       for j in range(len(r["budget"]["grid"]) - 1)) for r in fam)
        span = sum(1 for r in fam if r["budget"]["grid"][0]["t"] - r["budget"]["grid"][-1]["t"] > 1e-9) / len(fam)
        cheap = [r["budget"]["cheapest"]["t"] - r["budget"]["grid"][r["budget"]["match_index"]]["t"] for r in fam]
        afford = sum(1 for r in fam if r["budget"]["grid"][r["budget"]["match_index"]]["t"]
                     - r["budget"]["grid"][-1]["t"] <= 0.01) / len(fam)
        return {"n": len(fam), "gain": mean(gains), "strict": strict / len(fam),
                "h1": sum(1 for d in dev if d >= 0.05) / len(fam), "mono": mono, "span": span,
                "cheap": mean(cheap), "afford": afford,
                "uniform": mean(r["budget"]["uniform"]["t"] for r in fam),
                "match": mean(r["budget"]["grid"][r["budget"]["match_index"]]["t"] for r in fam),
                "free": mean(r["budget"]["grid"][-1]["t"] for r in fam),
                "cheapest": mean(r["budget"]["cheapest"]["t"] for r in fam),
                "ucost": mean(r["budget"]["uniform"]["cost"] for r in fam),
                "fcost": mean(r["k4"]["free_cost"] for r in fam)}

    P, R = analyse("primary"), analyse("replication")
    H = rep["hypotheses"]
    h1 = P["h1"] >= 0.25
    h2 = P["gain"] >= 0.02 and P["strict"] >= 0.20
    h3 = P["mono"] and P["span"] >= 0.60
    h4 = P["cheap"] >= 0.05
    h5 = P["afford"] >= 0.70
    h6 = (R["gain"] >= 0.02 and R["mono"] and R["span"] >= 0.60 and R["cheap"] >= 0.05 and R["afford"] >= 0.70)
    exp = {"H1_cost_is_a_real_constraint": h1, "H2_equal_cost_gain": h2, "H3_budget_monotone": h3,
           "H4_cheapest_concentration_fails": h4, "H5_affordable_optimum": h5, "H6_replication": h6}
    for k, ok in exp.items():
        ck(f"{k} verdict", H[k]["verdict"] == ("SUPPORTED" if ok else "NOT_SUPPORTED"))
    ck("H1 value", abs(H["H1_cost_is_a_real_constraint"]["fraction_free_cost_deviation_ge_5pct"] - P["h1"]) < 2e-4)
    ck("H2 value", abs(H["H2_equal_cost_gain"]["mean_uniform_minus_match"] - P["gain"]) < 2e-4
       and abs(H["H2_equal_cost_gain"]["fraction_strict_improvement"] - P["strict"]) < 2e-4)
    ck("H3 value", H["H3_budget_monotone"]["monotone_every_family"] == P["mono"]
       and abs(H["H3_budget_monotone"]["fraction_strict_span"] - P["span"]) < 2e-4)
    ck("H4 value", abs(H["H4_cheapest_concentration_fails"]["mean_cheapest_minus_match"] - P["cheap"]) < 2e-4)
    ck("H5 value", abs(H["H5_affordable_optimum"]["fraction_within_0.01_of_free"] - P["afford"]) < 2e-4)
    ck("H6 value", abs(H["H6_replication"]["replication_mean_uniform_minus_match"] - R["gain"]) < 2e-4
       and abs(H["H6_replication"]["replication_cheapest_minus_match"] - R["cheap"]) < 2e-4
       and abs(H["H6_replication"]["replication_affordable"] - R["afford"]) < 2e-4)
    ck("H7 external", H["H7_external_review"]["verdict"] == "BLOCKED")
    req = list(exp)
    verdict = ("COST_CONSTRAINED_AUDIT_SUPPORTED" if all(exp.values()) else "NOT_SUPPORTED")
    ck("verdict", verdict == rep["verdict"] == man.get("label"))
    f = rep["finding"]
    ck("finding consistent", abs(f["mean_gain_primary"] - P["gain"]) < 2e-4
       and abs(f["affordable_primary"] - P["afford"]) < 2e-4
       and abs(f["cheapest_gap_primary"] - P["cheap"]) < 2e-4)
    hl = man.get("headline", {})
    ck("manifest headline", hl.get("verdict") == verdict and hl.get("families") == P["n"]
       and abs(hl.get("uniform", -9) - P["uniform"]) < 2e-4
       and abs(hl.get("match", -9) - P["match"]) < 2e-4
       and abs(hl.get("gain", -9) - P["gain"]) < 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 / "E333_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.e333.verify.v1", "checks": len(c), "passed": passed,
                      "failed": [x for x in c if not x["ok"]], "verdict": verdict,
                      "uniform": round(P["uniform"], 4), "match": round(P["match"], 4),
                      "free": round(P["free"], 4), "gain": round(P["gain"], 4),
                      "families": P["n"]}, ensure_ascii=False))
    return 0 if passed == len(c) else 1


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