#!/usr/bin/env python3
"""E244 standalone verifier (imports no CAIN code). Re-applies integer-vector witnesses."""
import hashlib, json, math, sys
from pathlib import Path

STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENGINE = {"domain.py", "policy.py", "model.py", "run.py", "prereg.py", "engine.py"}
M = 101


def _psum(x):
    o, s = [], 0
    for v in x:
        s = (s + v) % M; o.append(s)
    return tuple(o)


PR = [lambda x: x[1:] + x[:1], lambda x: x[::-1], lambda x: (x[1], x[0]) + x[2:], lambda x: x[:3] + (x[4], x[3]),
      lambda x: tuple((v + 1) % M for v in x), lambda x: tuple(v * 3 % M for v in x),
      lambda x: tuple((v + i * 7) % M for i, v in enumerate(x)), _psum,
      lambda x: (x[0] * 5 % M,) + x[1:], lambda x: x[:2] + ((x[2] + x[0]) % M,) + x[3:],
      lambda x: x[:4] + ((x[4] + 2 * x[1]) % M,), lambda x: tuple(v * (i + 1) % M for i, v in enumerate(x))]


def run(seq, x):
    for i in seq:
        x = PR[i](x)
    return x


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 mc(child, parent):
    b = len(set(child) - set(parent)); c = len(set(parent) - set(child)); 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(n, ok, d=""): checks.append({"check": n, "ok": bool(ok), "detail": str(d)[:300]})
    man = json.loads((B / "E244_MANIFEST.json").read_text())
    ck("status", man.get("status") == STATUS)
    ck("label", man.get("label") in ("INTEGER_POLICY_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("signature", True)
    except Exception as ex: ck("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("hashes", not bad, bad[:3])
    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}
    extra = {"E244_MANIFEST.json", "E244_SIGNED_BODY.json", "E244_VERIFICATION_RESULTS.json", "MANIFEST.json",
             "MERKLE_ROOT.txt", "PUBLICATION.json", "E244_OMEGA_SEAL.json", "E244_TAMPER_RESULTS.json"}
    ck("no unlisted", not (present - set(files) - extra), sorted(present - set(files) - extra)[:5])
    ck("code 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 / "E244_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E244_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E244_RUN_REPORT.json").read_text())
    com = json.loads((B / "E244_MODEL_OUTPUTS_COMMITMENT.json").read_text())
    pc = json.loads((B / "E244_POLICY_COMMITMENTS.json").read_text())
    salt = json.loads((B / "E244_SALT_REVEALED.json").read_text())["salt"]
    ck("prereg hash", sha((B / "E244_PREREGISTRATION.json").read_bytes()) == frz["preregistration_sha256"])
    ck("freeze before run", frz["frozen_at"] <= rep["generated_at"])
    ck("salt commitment", sha(bytes.fromhex(salt)) == pre["salt_commitment_sha256"])
    ck("policy commitment", com["policy_commitments_sha256"] == sha((B / "E244_POLICY_COMMITMENTS.json").read_bytes()) == rep["policy_commitments_sha256"])
    ck("commit before sealed", com["generated_at"] <= rep["generated_at"] and rep["sealed_after_model_commit"] is True)
    ck("20 policies", len(pc["policies"]) == 20 and rep["proposals"]["requested"] == 20)

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

    arms = rep["sealed"]; wit = 0
    for key, arm in arms.items():
        good = True
        for w in arm["witnesses"]:
            seq = w["seq"]
            if not seq or any(not isinstance(i, int) or not (0 <= i <= 11) for i in seq) or len(seq) > 24:
                good = False; break
            if any(run(seq, tuple(x)) != tuple(y) for x, y in zip(w["xs"], w["ys"])):
                good = False; break
            if any(run(seq, tuple(x)) != tuple(y) for x, y in zip(w["hx"], w["hy"])):
                good = False; break
            wit += 1
        ck(f"{key} witnesses", good and arm["solved_count"] == len(arm["witnesses"]) == len(arm["solved_uids"]),
           f"{len(arm['witnesses'])}/{arm['solved_count']}")
    ck("witnesses", wit > 0, wit)

    primary = rep["primary_arm"]; solved = {k: set(v["solved_keys"]) for k, v in arms.items()}
    for h, other in (("H1_model_gt_reference", "reference"), ("H2_model_gt_primitives", "primitives_d4"),
                     ("H3_model_gt_compute_max", "primitives_d6_60k"), ("H5_model_gt_fixed", "fixed")):
        c = mc(solved[primary], solved[other])
        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)
    valid = sum(1 for p in pc["policies"] if p.get("screen", {}).get("ok"))
    h4_expected = "SUPPORTED" if valid >= 20 * 0.9 else "NOT_SUPPORTED"
    ck("H4 validity consistent", rep["hypotheses"]["H4_policy_validity"]["valid"] == valid and rep["hypotheses"]["H4_policy_validity"]["verdict"] == h4_expected, f"{valid}/20 -> {h4_expected}")
    primary_ok = all(rep["hypotheses"][k]["verdict"] == "SUPPORTED" for k in ("H1_model_gt_reference", "H2_model_gt_primitives", "H3_model_gt_compute_max", "H4_policy_validity", "H5_model_gt_fixed"))
    verdict = "INTEGER_POLICY_SUPPORTED" if primary_ok else "NOT_SUPPORTED"
    ck("verdict", 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.e244.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())
