"""Replay when false alarms occur in the 100,000-path Take Rate simulation."""
import json
from math import sqrt
from random import Random
from statistics import NormalDist

SEED=381729
RUNS=100000


def replay():
    rng=Random(SEED)
    threshold=NormalDist().inv_cdf(.975)
    totals={'final':0,'any':0,'first_1_to_5':0,'first_6_to_10':0,'first_11_to_15':0,
            'first_16_to_20':0,'flagged_then_clear':0,'both':0,'opposite_sign_at_final':0}
    for _ in range(RUNS):
        first_step=0; first_sign=0; score=0
        for t in range(1,21):
            score+=rng.gauss(0,1)
            flagged=abs(score)/sqrt(t)>threshold
            if flagged and not first_step:
                first_step=t
                first_sign=1 if score>0 else -1
        totals['final']+=flagged
        totals['any']+=first_step>0
        if first_step:
            a=(first_step-1)//5*5+1
            totals[f'first_{a}_to_{a+4}']+=1
            totals['flagged_then_clear']+=not flagged
            totals['both']+=flagged
            totals['opposite_sign_at_final']+=flagged and (1 if score>0 else -1)!=first_sign
    assert totals['final']==4900 and totals['any']==24630
    return {'seed':SEED,'paths':RUNS,'counts':totals}


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