#!/usr/bin/env python3
"""Gate 6.6: power of the D1 primary test from the chosen template's step-0 profile (simulation).

    python3 d1_power.py <scan summary.json> [--variants 32] [--k 6] [--sims 2000] [--seed 20261116]

Step-0 per-variant rates (K = 2 estimates) are shrunk toward the pooled rate (beta posterior, prior strength 2) to get a
plausible held-out profile; each simulated study draws 32 variant rates from that profile, samples K step-0 and K
last-checkpoint episodes per variant (last = step-0 rate + gain, capped at 1), and applies the pre-registered paired variant
bootstrap (percentile 95% CI, lower bound > 0; 2,000 resamples here for speed, 10,000 in the real verdict). Power = share
of simulated studies whose lower bound is above 0. The type-I rate is the gain-0 row.
"""
import argparse, json, random, statistics

ap = argparse.ArgumentParser()
ap.add_argument("summary"); ap.add_argument("--variants", type=int, default=32); ap.add_argument("--k", type=int, default=6)
ap.add_argument("--sims", type=int, default=2000); ap.add_argument("--boot", type=int, default=2000)
ap.add_argument("--seed", type=int, default=20261116)
a = ap.parse_args()
s = json.load(open(a.summary))
pooled = s["pooled_rate"]
prof = [(v["successes"] + 2 * pooled) / (v["scored"] + 2) for v in s["per_variant"] if v["scored"]]
rng = random.Random(a.seed)

def lower_bound(diffs):
    m = len(diffs); boots = []
    for _ in range(a.boot):
        boots.append(sum(diffs[rng.randrange(m)] for _ in range(m)) / m)
    boots.sort(); return boots[int(0.025 * a.boot)]

def power(gain):
    hits = 0
    for _ in range(a.sims):
        diffs = []
        for _ in range(a.variants):
            p0 = rng.choice(prof); p1 = min(1.0, p0 + gain)
            r0 = sum(rng.random() < p0 for _ in range(a.k)) / a.k
            r1 = sum(rng.random() < p1 for _ in range(a.k)) / a.k
            diffs.append(r1 - r0)
        if lower_bound(diffs) > 0: hits += 1
    return hits / a.sims

out = {"family": s["family"], "pooled_step0": round(pooled, 4), "profile_mean": round(statistics.mean(prof), 4),
       "profile_sd": round(statistics.pstdev(prof), 4), "variants": a.variants, "k": a.k, "sims": a.sims,
       "power": {str(g): power(g) for g in (0.0, 0.05, 0.10, 0.15, 0.20)}}
print(json.dumps(out, indent=1))
