"""Reproduce the null-experiment counts for the checkout peeking study.

Requires Python 3.9 or newer. Uses only synthetic Gaussian information increments.
Each run shares the same 20 increments across all planned look schedules.
"""
import json
from math import sqrt
from random import Random
from statistics import NormalDist

SEED=381729
REPLICATES=100000
LOOKS={
    1:(20,),
    2:(10,20),
    4:(5,10,15,20),
    10:tuple(range(2,21,2)),
    20:tuple(range(1,21)),
}

def run():
    rng=Random(SEED)
    n=NormalDist()
    critical=n.inv_cdf(.975)
    adjusted={k:n.inv_cdf(1-.05/(2*k)) for k in LOOKS}
    counts={k:[0,0] for k in LOOKS}
    normalizer=[1/sqrt(t) for t in range(1,21)]
    for _ in range(REPLICATES):
        state=0.0
        readings=[]
        for i in range(20):
            state+=rng.gauss(0,1)
            readings.append(abs(state)*normalizer[i])
        for k,steps in LOOKS.items():
            high=max(readings[i-1] for i in steps)
            counts[k][0]+=high>critical
            counts[k][1]+=high>adjusted[k]
    def value(count):
        p=count/REPLICATES
        return {'flags':count,'percent':round(100*p,3),
                'monte_carlo_se_pp':round(100*sqrt(p*(1-p)/REPLICATES),3)}
    results={k:{'look_steps':list(LOOKS[k]),'usual':value(counts[k][0]),
                'bonferroni':value(counts[k][1])} for k in LOOKS}
    assert 4.7<results[1]['usual']['percent']<5.3
    assert counts[1][0]==counts[1][1]
    assert all(counts[k][1]<=counts[k][0] for k in LOOKS)
    assert counts[20][0]>counts[10][0]>counts[4][0]>counts[2][0]>counts[1][0]
    return {'seed':SEED,'replicates':REPLICATES,'increments':20,'family_threshold':.05,'results':results}

if __name__=='__main__':
    print(json.dumps(run(),indent=2))
