#!/usr/bin/env python3
"""E239 standalone verifier (imports no CAIN code).

Re-checks the signed record, budget ledger, model-output ordering, policy
validity, sealed witnesses, McNemar contrasts, forecast calibration and the
verdict. It does not re-run the learner's search.

Usage: python3 -I verify_e239_offline.py <bundle-dir>
"""
import hashlib, json, math, sys
from pathlib import Path

STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
GENESIS = "0" * 64
ENGINE = {"policy.py", "model.py", "run.py", "prereg.py", "engine.py"}
SPACE = {"generations": [1, 2, 3, 4, 5, 6], "macro_cap": [1, 2, 4, 6, 8, 12, 16],
         "accept": ["improve", "improve_retain", "margin"], "margin": [0.0, 0.03, 0.06, 0.1],
         "budget": [1000, 2000, 4000, 8000], "max_macro_len": [3, 4, 6, 8],
         "order": ["insertion", "shortest", "longest", "lexicographic"]}


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 _rot(s, k):
    out = []
    for ch in s:
        if "a" <= ch <= "z":
            out.append(chr((ord(ch) - 97 + k) % 26 + 97))
        elif "A" <= ch <= "Z":
            out.append(chr((ord(ch) - 65 + k) % 26 + 65))
        else:
            out.append(ch)
    return "".join(out)


PRIMS = {"upper": str.upper, "lower": str.lower, "rev": lambda s: s[::-1], "sort": lambda s: "".join(sorted(s)),
         "dedup": lambda s: "".join(dict.fromkeys(s)), "swap": str.swapcase, "take2": lambda s: s[:2],
         "drop2": lambda s: s[2:], "rep2": lambda s: s + s, "rot1": lambda s: _rot(s, 1),
         "rot2": lambda s: _rot(s, 2), "rot3": lambda s: _rot(s, 3)}


def apply_seq(seq, s):
    for op in seq:
        s = PRIMS[op](s)
    return s


def mc(child, parent):
    A, B = set(child), set(parent)
    b, c = len(A - B), len(B - A); n = b + c
    p = sum(math.comb(n, k) for k in range(b, n + 1)) / (2 ** n) if n else 1.0
    return {"child_only": b, "parent_only": c, "n": n, "p_one_sided": p}


def main():
    B = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    checks = []

    def ck(name, ok, detail=""):
        checks.append({"check": name, "ok": bool(ok), "detail": str(detail)[:300]})

    man = json.loads((B / "E239_MANIFEST.json").read_text())
    ck("status", man.get("status") == STATUS)
    ck("label set", man.get("label") in ("MODEL_PROPOSER_SUPPORTED", "NOT_SUPPORTED"))
    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("manifest signature", True)
    except Exception as ex:
        ck("manifest signature", False, ex)
    files = man.get("files", {})
    ck("files exist", all((B / k).exists() for k in files))
    bad = [k for k, h in files.items() if (B / k).exists() and sha((B / k).read_bytes()) != h]
    ck("file hashes", not bad, bad[:3])
    ck("merkle root", 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}
    extra = {"E239_MANIFEST.json", "E239_SIGNED_BODY.json", "E239_VERIFICATION_RESULTS.json", "MANIFEST.json",
             "MERKLE_ROOT.txt", "PUBLICATION.json", "E239_OMEGA_SEAL.json", "E239_TAMPER_RESULTS.json"}
    ck("no unlisted files", not (present - set(files) - extra), sorted(present - set(files) - extra)[:5])
    ck("engine withheld", not any((B / n).exists() for n in ENGINE))
    ck("no secrets", not any(x.endswith((".pem", ".key", ".env", ".db", ".sqlite")) for x in present))

    pre = json.loads((B / "E239_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E239_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E239_RUN_REPORT.json").read_text())
    mo = json.loads((B / "E239_MODEL_OUTPUTS.json").read_text())
    com = json.loads((B / "E239_MODEL_OUTPUTS_COMMITMENT.json").read_text())
    salts = json.loads((B / "E239_SALTS_REVEALED.json").read_text())["salts"]
    ck("prereg hash", sha((B / "E239_PREREGISTRATION.json").read_bytes()) == frz["preregistration_sha256"])
    ck("freeze precedes run", frz["frozen_at"] <= rep["generated_at"])
    ck("salt commitments", {k: sha(bytes.fromhex(v)) for k, v in salts.items()} == pre["salt_commitments_sha256"])
    ck("salt master", sha(json.dumps({k: sha(bytes.fromhex(v)) for k, v in salts.items()}, sort_keys=True).encode()) == pre["salt_master_commitment_sha256"])
    ck("model outputs hash", com["model_outputs_sha256"] == sha((B / "E239_MODEL_OUTPUTS.json").read_bytes()) == rep["model_outputs_commitment_sha256"])
    ck("model outputs before sealed", com["generated_at"] <= rep["generated_at"] and rep["sealed_after_model_commit"] is True)

    # ledger
    spent = 0.0
    calls = 0
    for line in (B / "E239_API_LEDGER.jsonl").read_text().splitlines():
        x = json.loads(line)
        if x["event"] == "settle":
            spent += x["usd"]; calls += 1
    ck("ledger within cap", spent <= rep["model"]["budget_usd"], f"{spent} <= {rep['model']['budget_usd']}")
    ck("ledger calls match", calls == rep["model"]["calls"], f"{calls} vs {rep['model']['calls']}")
    ck("ledger spend match", abs(round(spent, 6) - rep["model"]["spent_usd"]) < 1e-9, f"{spent} vs {rep['model']['spent_usd']}")
    ck("budget disclosed", rep["model"]["budget_usd"] == 5.60)

    # policies
    def valid(p):
        return isinstance(p, dict) and set(p) == set(SPACE) and all(p[k] in SPACE[k] for k in SPACE)
    ck("finalist policies valid", all(valid(f["policy"]) for f in rep["finalists"]) and len(rep["finalists"]) == 9)
    ck("proposal counts", rep["proposals"]["accepted"] == 64 and rep["proposals"]["random"] == 64 and rep["proposals"]["grid"] == 64)
    ck("screening rows", len(rep["screening"]["rows"]) == 192)
    ck("model outputs policies valid", all(valid(p) for p in (mo.get("finalists") and [f["policy"] for f in mo["finalists"]])))

    # sealed witnesses and counts
    arms = rep["sealed"]
    wit = 0
    for key, arm in arms.items():
        for fam, v in arm["families"].items():
            s = v["sealed"]
            good = True
            for w in s["witnesses"]:
                seq = w["seq"]
                if not seq or any(op not in PRIMS for op in seq) or len(seq) > 16:
                    good = False; break
                if any(apply_seq(seq, x) != y for x, y in zip(w["inputs"], w["outputs"])):
                    good = False; break
                if any(apply_seq(seq, x) != y for x, y in zip(w["probe_inputs"], w["probe_outputs"])):
                    good = False; break
                wit += 1
            ck(f"{key}/{fam} witnesses", good and s["solved_count"] == len(s["witnesses"]) == len(s["solved_uids"]),
               f"{len(s['witnesses'])}/{s['solved_count']}")
    ck("witnesses re-applied", wit > 0, wit)
    for key, arm in arms.items():
        pooled = sum(v["sealed"]["solved_count"] for v in arm["families"].values())
        ck(f"{key} pooled", pooled == arm["pooled_solved"], f"{pooled} vs {arm['pooled_solved']}")

    # hypotheses
    primary = rep["primary_arm"]
    for h, other in (("H1_model_gt_random", "random_best"), ("H2_model_gt_fixed", "fixed"), ("H3_model_gt_compute_max", "compute_max")):
        c = mc(arms[primary]["solved_keys"], arms[other]["solved_keys"])
        ck(f"{h} recomputed", c == rep["hypotheses"][h]["contrast"], c)
        exp = "SUPPORTED" if (c["child_only"] > c["parent_only"] and c["p_one_sided"] < 0.05) else "NOT_SUPPORTED"
        ck(f"{h} verdict", rep["hypotheses"][h]["verdict"] == exp, exp)
    # brier
    rows = []
    fid_to_arm = {v["finalist_id"]: k for k, v in arms.items()}
    for f in mo["forecasts"]:
        if f["a"] not in fid_to_arm or f["b"] not in fid_to_arm:
            continue
        ca, cb = arms[fid_to_arm[f["a"]]]["pooled_solved"], arms[fid_to_arm[f["b"]]]["pooled_solved"]
        if ca == cb:
            continue
        rows.append(((f["p_a"] - (1 if ca > cb else 0)) ** 2))
    brier = sum(rows) / len(rows) if rows else None
    ck("brier recomputed", brier is not None and abs(brier - rep["hypotheses"]["H4_forecast_calibration"]["brier"]) < 1e-9, brier)
    ck("H4 verdict", rep["hypotheses"]["H4_forecast_calibration"]["verdict"] == ("SUPPORTED" if (brier is not None and rep["hypotheses"]["H4_forecast_calibration"]["ci95"][1] < 0.25) else "NOT_SUPPORTED"))
    ck("H5 validity", rep["hypotheses"]["H5_policy_validity"]["verdict"] == "SUPPORTED")

    primary_ok = all(rep["hypotheses"][k]["verdict"] == "SUPPORTED" for k in ("H1_model_gt_random", "H2_model_gt_fixed", "H3_model_gt_compute_max", "H5_policy_validity"))
    verdict = "MODEL_PROPOSER_SUPPORTED" if primary_ok else "NOT_SUPPORTED"
    ck("verdict recomputed", verdict == rep["verdict"] == man["label"], f"{verdict} vs {rep['verdict']}")

    passed = sum(1 for c in checks if c["ok"])
    print(json.dumps({"schema": "cain42.e239.verify.v1", "checks": len(checks), "passed": passed,
                      "failed": [c for c in checks if not c["ok"]], "witnesses_reapplied": wit,
                      "verdict": verdict, "spend_usd": spent}, ensure_ascii=False))
    return 0 if passed == len(checks) else 1


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