"""Exact concentration for nominal periods 1..128. Usage: python -B lag_224_period.py output.json"""
from collections import Counter
from pathlib import Path
import sys,json
import numpy as np
from line_mechanism_108 import geometry
from fixed_stream_133_135 import solved
def cc(x,p):
    pos=np.arange(len(x))%p;h=np.bincount(pos*29+x,minlength=p*29).reshape(p,29);key=h.argmax(1)
    return int(h.max(1).sum()),key
def run():
    g,_=geometry();x=np.array([z[3] for z in g if z[1]==8])
    p,_=solved();y=np.array([v for name,(v0,l) in p.items() for v in v0],int)
    ny=len(y);ty=max(Counter(y).values());assert (ty,ny)==(349,2797)
    n=len(x);thr={'8%':(8,100),'10%':(10,100),'12%':(12,100),'pooled':(ty,ny)}
    result=[cc(x,k)[0] for k in range(1,129)]
    def status(a,b):return [k for k,v in enumerate(result,1) if v*b>=n*a]
    def witness(k):
        mx,key=cc(x,k);z=(x-np.resize(key,n))%29;assert (z==0).sum()==mx and np.array_equal(x,(z+np.resize(key,n))%29)
        return dict(period=k,count=mx,key=key.tolist())
    thresholds={}
    for label,(a,b) in thr.items():
        wins=status(a,b);thresholds[label]=dict(required=(n*a+b-1)//b,first=wins[0] if wins else None,passing=wins,witness=witness(wins[0]) if wins else None)
    rng=np.random.default_rng(2243301);nperm=255;firsts=[];p4=[];starts=np.arange(n)
    # Each draw repeats the whole bounded period sweep, stopping at the first passage of the pooled benchmark.
    for it in range(nperm):
        v=rng.permutation(x);p4.append(cc(v,4)[0]);firsts.append(next((k for k in range(1,129) if cc(v,k)[0]*ny>=n*ty),None))
    # Independent reference implementations on real text for every period, and on two positive controls.
    for k,m in enumerate(result,1):
        assert sum(max(Counter(x[i::k]).values()) for i in range(k))==m
    for k in [4,17]:
        ki=rng.integers(0,29,k);c=(y+ki[starts[:ny]%k])%29
        assert cc(y,k)[0]==cc(c,k)[0]>=ty
    return dict(n=n,reference=[ty,ny],counts=result,thresholds=thresholds,seed=2243301,shuffle_first=firsts,shuffle_four=p4,source='section 8, no deletions, global origin 9640; witness target plaintext is rune 0')
if __name__=='__main__':
    r=run();Path(sys.argv[1]).write_text(json.dumps(r,separators=(',',':'))+'\n');print([(k,v['required'],v['first'],len(v['passing'])) for k,v in r['thresholds'].items()]);print(Counter(r['shuffle_first']),np.quantile([v for v in r['shuffle_first'] if v is not None],[0,.5,1]));print([(p,r['counts'][p-1]) for p in [1,2,4,8,16,29,32,48,64,80,96,112,128]])
