#!/usr/bin/env python3
"""E150 independent recomputation of E149 from the published bundle (stdlib only, fresh code).
   python3 -I recompute_e149.py <e149_bundle_dir>"""
import json, math, re, statistics as st, sys, hashlib
B = sys.argv[1]
def rows(p): return [json.loads(l) for l in open(f"{B}/{p}")]
R, Q = rows("raw/blocks.jsonl"), rows("raw/reproduction_blocks.jsonl")
P = sorted([r for r in R if r["tag"] == "e149-primary"], key=lambda r: r["block"])
out = {}
d = [r["arms"]["candidate"]["verified_discoveries"] - r["arms"]["parent"]["verified_discoveries"] for r in P]
out["1_primary_blocks"] = len(P)
out["2_task_outcomes"] = sum(len(r["arms"]["candidate"]["per_task"]) for r in P)
out["3_mean_gain_per_block"] = round(st.mean(d), 4)
w, l = sum(x > 0 for x in d), sum(x < 0 for x in d); out["4_W_L_T"] = [w, l, len(d) - w - l]
n = w + l; out["5_exact_sign_p_one_sided"] = sum(math.comb(n, k) for k in range(w, n + 1)) / 2 ** n
tot = lambda a, f: sum(r["arms"][a][f] for r in P)
out["6_question_increase_pct"] = round(100 * (tot("candidate", "queries_total") / tot("parent", "queries_total") - 1), 2)
cpd = lambda a: tot(a, "hyp_evals_total") / tot(a, "verified_discoveries")
out["7_compute_per_discovery_increase_pct"] = round(100 * (cpd("candidate") / cpd("parent") - 1), 2)
out["8_cost_aware_reward_diff_per_task"] = round(st.mean(r["arms"]["candidate"]["efficiency_mean"] - r["arms"]["parent"]["efficiency_mean"] for r in P), 5)
g = lambda a: st.mean(r["arms"][a]["verified_discoveries"] - r["arms"]["parent"]["verified_discoveries"] for r in P)
out["9_tempering_share_of_gain"] = round(g("p_temper") / g("candidate"), 4)
# 10: narrowly defined content comparison
HEX128 = re.compile(r"[0-9a-f]{128}")
problems = []
for a, b in zip(R, Q):
    if set(a) != set(b): problems.append(("keyset", a.get("tag"), a.get("block")))
    diff = [k for k in a if a[k] != b[k]]
    if diff != ["signature"]: problems.append(("fields_differ", a["tag"], a["block"], diff))
    if not (HEX128.fullmatch(a["signature"]) and HEX128.fullmatch(b["signature"])): problems.append(("sig_format", a["tag"], a["block"]))
out["10_content_identical_excluding_only_signature"] = {"blocks": len(R), "problems": problems[:5], "n_problems": len(problems),
    "signatures_all_differ": all(a["signature"] != b["signature"] for a, b in zip(R, Q)),
    "tasks_sha256_identical": all(a["tasks_sha256"] == b["tasks_sha256"] for a, b in zip(R, Q))}
# per-task eff recomputed from (ok, used, budget) to audit the reward's definition and units
bad_eff = sum(1 for r in P for a in r["arms"].values() for t in a["per_task"] if abs(t[2] - round(t[0] - 0.3 * t[1] / t[4], 6)) > 1e-9)
out["reward_definition_audit"] = {"formula": "eff = ok - 0.3 * used / budget (per task; dimensionless; range [-0.3, 1])", "rows_not_matching_formula": bad_eff}
print(json.dumps(out, indent=1))
