"""Monte Carlo: identify one biased coin among 20 fair coins by most heads."""
import numpy as np
import csv

SEED, TRIALS, N_FAIR, TARGET = 20260929, 50_000, 20, 0.95
BIASES = [0.60, 0.70, 0.75, 0.80, 0.90]
TOSSES = np.unique(np.r_[np.arange(1, 31), np.arange(35, 101, 5),
                         np.arange(110, 301, 10), np.arange(325, 601, 25),
                         np.arange(650, 1501, 50)])
rng = np.random.default_rng(SEED)
rows = []
for p in BIASES:
    for n in TOSSES:
        rigged = rng.binomial(n, p, TRIALS)
        fair = rng.binomial(n, 0.5, (TRIALS, N_FAIR))
        fair_max = fair.max(axis=1)
        ties = (fair == rigged[:, None]).sum(axis=1)
        score = np.where(rigged > fair_max, 1.0,
                         np.where(rigged == fair_max, 1/(ties+1), 0.0))
        est = float(score.mean())
        se = float(score.std(ddof=1)/np.sqrt(TRIALS))
        rows.append((p, int(n), est, se, max(0, est-1.96*se), min(1, est+1.96*se)))
with open("rigged_coin_detection.csv", "w", newline="") as f:
    w = csv.writer(f)
    w.writerow(["rigged_heads_probability","tosses_per_coin",
                "identification_probability","monte_carlo_se","ci95_low","ci95_high"])
    w.writerows(rows)
for p in BIASES:
    hit = next((r for r in rows if r[0] == p and r[2] >= TARGET), None)
    print(p, hit)
