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

Recomputes the redundancy law from the raw per-certificate curves: denial at budget 1 and at
budget k, forgery at each set's own min m (the corrected H4), the defender's cost and the
replication. It also records the as-shipped H4 aggregation bug and checks that the published
correction matches the raw rows. 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; verification is record-level.
"""
import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENG = ("redundancy.py", "run.py")
DEPS = 5
GRAMMARS = ("A", "B")
P1 = ("honest3", "two_decoy3")
KS = (1, 2, 4)
BMAX = 8
DRAWS = 200
EX = {"E316_MANIFEST.json", "E316_SIGNED_BODY.json", "E316_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E316_OMEGA_SEAL.json",
      "E316_TAMPER_RESULTS.json", "E316_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 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 / "E316_MANIFEST.json").read_text())
    ck("schema", man.get("schema") == "cain42.e316.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 / "E316_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E316_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E316_RUN_REPORT.json").read_text())
    rev = json.loads((B / "E316_SALT_REVEALED.json").read_text())
    corr = json.loads((B / "E316_ANALYSIS_CORRECTION.json").read_text())
    ck("prereg hash", sha((B / "E316_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 / "E316_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))
    ck("correction present", corr.get("schema") == "cain42.e316.analysis_correction.v1")

    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"]))
        if r["available"] > 4:
            bad.append(("too_many", r["grammar"], r["p1"], r["world"]))
        for k in KS:
            call = r["curves"].get(str(k))
            if call is None:
                continue
            ms = [c["m"] for c in r["certs"][:k]]
            if call["ms"] != ms:
                bad.append(("ms", k, r["grammar"], r["p1"], r["world"]))
            if call["total_rows"] != sum(c["size"] for c in r["certs"][:k]):
                bad.append(("rows", k, r["grammar"], r["p1"], r["world"]))
            for b in range(BMAX + 1):
                if call["denial"][str(b)]["draws"] != DRAWS:
                    bad.append(("denial_draws", k, b))
                if not (0 <= call["denial"][str(b)]["hits"] <= DRAWS):
                    bad.append(("denial_hits", k, b))
            if call["forgery"] is not None:
                for b in range(BMAX + 1):
                    if call["forgery"][str(b)]["draws"] != DRAWS:
                        bad.append(("forgery_draws", k, b))
                    if not (0 <= call["forgery"][str(b)]["hits"] <= DRAWS):
                        bad.append(("forgery_hits", k, b))
    ck("row consistency", not bad, bad[:5])

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

    def rate(rows, k, b, kind):
        h = n = 0
        for r in rows:
            call = r["curves"].get(str(k))
            if not call:
                continue
            cell = call[kind][str(b)]
            h += cell["hits"]
            n += cell["draws"]
        return h / max(1, n), h, n

    d1 = {k: rate(cap, k, 1, "denial")[0] for k in KS}
    dk = {k: rate(cap, k, k, "denial")[0] for k in KS}
    dk1 = {k: rate(cap, k, k - 1, "denial")[0] for k in KS if k > 1}
    # corrected H4: per certificate set, at that set's own min m
    f_at, f_below = {}, {}
    for k in (2, 4):
        a, bl = [], []
        for r in cap:
            call = r["curves"].get(str(k))
            if not call:
                continue
            m = min(call["ms"])
            a.append(call["forgery"][str(m)]["hits"] / call["forgery"][str(m)]["draws"])
            if m - 1 >= 0:
                bl.append(call["forgery"][str(m - 1)]["hits"] / call["forgery"][str(m - 1)]["draws"])
        f_at[k] = sum(a) / max(1, len(a))
        f_below[k] = sum(bl) / max(1, len(bl)) if bl else 0.0
    cost = {k: (sum(r["curves"][str(k)]["total_rows"] for r in allr if str(k) in r["curves"]) /
                max(1, sum(1 for r in allr if str(k) in r["curves"]))) for k in KS}

    h1 = abs(d1[1] - 1.0) < 0.02
    h2 = all(abs(d1[k] - 1.0 / k) < 0.08 for k in (2, 4))
    h3 = all(abs(dk[k] - 1.0) < 0.02 and dk1[k] < 0.98 for k in (2, 4))
    h4 = all(abs(f_at[k] - 1.0 / k) < 0.08 and f_below[k] < 0.02 for k in (2, 4))
    h5 = cost[4] > 3.0 * cost[1]
    rcap = [r for r in rep["sets"]["replication"]["rows"]
            if r["available"] >= 4 and not all(c["correct"] for c in r["certs"])]
    h6 = (rate(rcap, 4, 1, "denial")[0] < 0.4 and rate(rcap, 4, 4, "denial")[0] > 0.98 and
          rate(rcap, 4, 1, "forgery")[0] < 0.4)
    exp = {"H1": h1, "H2": h2, "H3": h3, "H4": h4, "H5": h5, "H6": h6}
    ck("H1", h1, d1[1])
    ck("H2", h2, {k: round(d1[k], 4) for k in (2, 4)})
    ck("H3", h3, {"at_k": {k: round(dk[k], 4) for k in (2, 4)},
                  "below": {k: round(dk1[k], 4) for k in (2, 4)}})
    ck("H4 corrected", h4, {"k2": round(f_at[2], 4), "k4": round(f_at[4], 4),
                            "below2": round(f_below[2], 4), "below4": round(f_below[4], 4)})
    ck("H5", h5, {"cost4": round(cost[4], 2), "cost1": round(cost[1], 2)})
    ck("H6", h6)
    ck("as-shipped H4 was the bug", rep["hypotheses"]["H4_forgery_price_divided_by_k"]["verdict"] == "NOT_SUPPORTED")
    ck("correction matches", abs(corr["corrected"]["k2"]["at_min"] - f_at[2]) < 0.0002 and
       abs(corr["corrected"]["k4"]["at_min"] - f_at[4]) < 0.0002)
    verdict = ("CERTIFICATE_REDUNDANCY_SUPPORTED" if all(exp.values()) else "NOT_SUPPORTED")
    ck("verdict corrected", verdict == corr["verdict_corrected"] == man.get("label"))
    ck("other hypotheses", all(rep["hypotheses"][k]["verdict"] == "SUPPORTED" for k in
                               ("H1_single_certificate_denial", "H2_redundancy_divides_denial",
                                "H3_denial_guarantee_costs_k", "H5_defender_cost", "H6_replication")))
    ck("certificate sets", sum(1 for r in allr if r["available"] >= 4) ==
       rep["resources"]["certificate_sets"])
    ck("manifest headline", man.get("headline", {}).get("verdict") == verdict and
       man.get("headline", {}).get("runs") == 48 and
       all(abs(man.get("headline", {}).get("denial_b1", {}).get(str(k), -1) - d1[k]) < 0.0002
           for k in KS) and
       all(abs(man.get("headline", {}).get("forgery_at_min", {}).get(str(k), -1) - f_at[k]) < 0.0002
           for k in (2, 4)))

    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 / "E316_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.e316.verify.v1", "checks": len(c),
                      "passed": passed, "failed": [x for x in c if not x["ok"]],
                      "verdict": verdict, "denial_b1": {str(k): round(d1[k], 4) for k in KS},
                      "forgery_at_min": {str(k): round(f_at.get(k, 1.0), 4) for k in KS}},
                     ensure_ascii=False))
    return 0 if passed == len(c) else 1


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