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

Recomputes the corruption-budget law from the raw run rows: the strategic price, its ratio
to the identifier's lie set, the strategic/random comparison, the quorum and the one-row
denial. 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 = ("budget.py", "run.py")
DEPS = 5
GRAMMARS = ("A", "B")
P1 = ("honest3", "two_decoy3")
BMAX = 8
RAND_DRAWS = 20
EX = {"E312_MANIFEST.json", "E312_SIGNED_BODY.json", "E312_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E312_OMEGA_SEAL.json",
      "E312_TAMPER_RESULTS.json", "E312_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 / "E312_MANIFEST.json").read_text())
    ck("schema", man.get("schema") == "cain42.e312.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 / "E312_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E312_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E312_RUN_REPORT.json").read_text())
    rev = json.loads((B / "E312_SALT_REVEALED.json").read_text())
    ck("prereg hash", sha((B / "E312_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 / "E312_EXTERNAL_REVIEW_STATUS.json").read_text()).get("status") == "NOT_OBTAINED")
    ck("pinned dependency", len(pre.get("dependency_sha256", {})) == DEPS)
    dev = json.loads((B / "E312_DEVIATIONS.json").read_text())
    ck("deviation recorded", len(dev.get("deviations", [])) >= 1 and
       all(d.get("design_unchanged") and d.get("salt_commitments_unchanged") for d in dev["deviations"]))
    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:
        expect_correct = bool(r["accepted"] and r["claimed_mask"] == r["truth_mask"])
        if r["correct"] != expect_correct:
            bad.append(("correct", r["grammar"], r["p1"], r["world"]))
        if not r["accepted"]:
            continue
        if r["cert_size"] != len(r["cert_rows"]):
            bad.append(("cert_size", r["grammar"], r["p1"], r["world"]))
        if not (0 <= r["cert_in_D"] <= min(r["cert_size"], r["D_size"])):
            bad.append(("cert_in_D", r["grammar"], r["p1"], r["world"]))
        if expect_correct:
            if r["min_strategic_budget"] != 0:
                bad.append(("honest_min", r["grammar"], r["p1"], r["world"]))
        else:
            if r["min_strategic_budget"] != r["cert_in_D"]:
                bad.append(("min_budget", r["grammar"], r["p1"], r["world"]))
        if set(r["strategic"]) != {str(b) for b in range(BMAX + 1)}:
            bad.append(("strategic_keys", r["grammar"], r["p1"], r["world"]))
        for b in range(BMAX + 1):
            if r["random"][str(b)]["draws"] != RAND_DRAWS:
                bad.append(("draws", b))
            if not (0 <= r["random"][str(b)]["forges"] <= RAND_DRAWS):
                bad.append(("forges", b))
        if not isinstance(r["quorum_one"], bool) or not isinstance(r["quorum_two"], bool):
            bad.append(("quorum_bool", r["grammar"], r["p1"], r["world"]))
        if not isinstance(r["denial_b1"], bool):
            bad.append(("denial_bool", r["grammar"], r["p1"], r["world"]))
    ck("row consistency", not bad, bad[:5])

    acc = [r for r in allr if r["accepted"]]
    cap = [r for r in acc if not r["correct"]]
    hon = [r for r in acc if r["correct"]]
    cap_m = sum(r["cert_in_D"] for r in cap) / len(cap)
    cap_D = sum(r["D_size"] for r in cap) / len(cap)

    h1 = all(r["min_strategic_budget"] == r["cert_in_D"] for r in cap)
    h2 = cap_m <= 0.25 * cap_D
    strat_m = sum(1 for r in cap if r["strategic"][str(r["cert_in_D"])])
    rand_m = sum(r["random"][str(r["cert_in_D"])]["forges"] for r in cap)
    rand_n = sum(r["random"][str(r["cert_in_D"])]["draws"] for r in cap)
    h3 = strat_m == len(cap) and rand_m / max(1, rand_n) < 0.5
    h4 = (sum(1 for r in cap if r["quorum_one"]) == 0 and
          sum(1 for r in cap if r["quorum_two"]) == len(cap))
    deny_cap = sum(1 for r in cap if not r["denial_b1"])
    deny_hon = sum(1 for r in hon if not r["denial_b1"])
    h5 = deny_cap == len(cap) and deny_hon == len(hon)
    rcap = [r for r in rep["sets"]["replication"]["rows"] if r["accepted"] and not r["correct"]]
    h7 = (len(rcap) > 0 and all(r["min_strategic_budget"] == r["cert_in_D"] for r in rcap) and
          sum(1 for r in rcap if r["quorum_two"]) == len(rcap) and
          sum(1 for r in rcap if r["quorum_one"]) == 0)
    exp = {"H1_strategic_price_is_contamination": h1, "H2_price_compression": h2,
           "H3_strategy_beats_luck": h3, "H4_quorum_doubles_the_price": h4,
           "H5_denial_costs_one": h5, "H7_replication": h7}
    H = rep["hypotheses"]
    for k, ok in exp.items():
        ck(f"{k} verdict", H[k]["verdict"] == ("SUPPORTED" if ok else "NOT_SUPPORTED"))
    ck("H1 counts", H["H1_strategic_price_is_contamination"]["captured"] == len(cap) and
       H["H1_strategic_price_is_contamination"]["min_budget_equals_m"] ==
       sum(1 for r in cap if r["min_strategic_budget"] == r["cert_in_D"]))
    ck("H2 ratio", abs(H["H2_price_compression"]["mean_m"] - cap_m) < 0.0051 and
       abs(H["H2_price_compression"]["mean_D"] - cap_D) < 0.0051)
    ck("H3 counts", H["H3_strategy_beats_luck"]["strategic_forges"] == strat_m and
       H["H3_strategy_beats_luck"]["random_forges"] == rand_m and
       H["H3_strategy_beats_luck"]["random_draws"] == rand_n)
    ck("H4 counts", H["H4_quorum_doubles_the_price"]["one_strategic_forges"] ==
       sum(1 for r in cap if r["quorum_one"]) and
       H["H4_quorum_doubles_the_price"]["two_strategic_forges"] ==
       sum(1 for r in cap if r["quorum_two"]))
    ck("H5 counts", H["H5_denial_costs_one"]["captured_denied"] == deny_cap and
       H["H5_denial_costs_one"]["honest_denied"] == deny_hon)
    verdict = ("CORRUPTION_BUDGET_SUPPORTED" if all(exp.values()) else "NOT_SUPPORTED")
    ck("verdict", verdict == rep["verdict"] == man.get("label"))
    f = rep["finding"]
    ck("finding consistent", f["mean_m"] == round(cap_m, 2) and
       f["mean_D"] == round(cap_D, 2) and f["strategic_forgery_at_m"] == strat_m and
       f["random_forgery_at_m"] == rand_m and
       f["quorum_one_forges"] == sum(1 for r in cap if r["quorum_one"]) and
       f["quorum_two_forges"] == sum(1 for r in cap if r["quorum_two"]) and
       f["denial_captured"] == deny_cap and f["denial_honest"] == deny_hon)
    ck("price compression", cap_m < cap_D)
    ck("certificates", len(acc) == rep["resources"]["certificates"] and len(acc) > 0)
    ck("decisions", rep["resources"]["decisions"] ==
       len(acc) * ((BMAX + 1) * (1 + RAND_DRAWS) + 3))
    ck("manifest headline", man.get("headline", {}).get("verdict") == rep["verdict"] and
       man.get("headline", {}).get("runs") == 48 and
       man.get("headline", {}).get("certificates") == len(acc))

    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 / "E312_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.e312.verify.v1", "checks": len(c),
                      "passed": passed, "failed": [x for x in c if not x["ok"]],
                      "verdict": verdict, "mean_m": round(cap_m, 2), "mean_D": round(cap_D, 2),
                      "quorum": [sum(1 for r in cap if r["quorum_one"]),
                                 sum(1 for r in cap if r["quorum_two"])]},
                     ensure_ascii=False))
    return 0 if passed == len(c) else 1


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