"""One section, one frozen hidden-period experiment. Run alongside period_111.py."""
from collections import defaultdict
from concurrent.futures import ProcessPoolExecutor
import json
import numpy as np
import period_111 as h
from lp_core import lp,vals
from lexical_words import tokenize_words

def setup():
    spec=h.read('real_period_112_protocol.json')
    ss='%'.join(lp[:56]).split('$'); s=ss[spec['section']]
    base='$'.join(ss[:spec['section']]).count('%')
    ws=tokenize_words(s); end=lambda w:w['rune_offset']+len(w['values'])
    cut=next(end(w) for w in ws if end(w)>=350)
    ws=[w for w in ws if end(w)<=cut+200]; lens=[len(w['values']) for w in ws]
    c=[v for w in ws for v in w['values']]
    assert c==vals(s)[:len(c)].tolist() and ws[0]['rune_offset']==0 and cut in np.cumsum(lens)
    x=dict(c=c,st=[int(j==0) for n in lens for j in range(n)],en=[int(j==n-1) for n in lens for j in range(n)],cut=cut)
    known={g['name']:g['values'] for g in h.read('increment_calibration_sources.json')['groups']}
    train=[];bank=defaultdict(list)
    for g in h.read('mechanism_coverage_results.json')['known_method_groups']:
        src='%'.join(h.pages[i] for i in g['parsed_page_indices']); p=known[g['name']]
        assert len(vals(src))==len(p)
        train.append((src,p))
        for w in tokenize_words(src):
            n=len(w['values']);i=w['rune_offset'];bank[n].append(p[i:i+n])
    rng=np.random.default_rng(1123301)
    plain=[v for n in lens for v in bank[n][int(rng.integers(len(bank[n])))]]
    k=rng.integers(0,29,11).tolist();assert h.primitive(k)==k
    skips={i for i,(v,u) in enumerate(zip(plain,rng.random(len(c)))) if v==0 and u<.5}
    positive=dict(x,c=h.encode(plain,k,skips))
    cases=[('positive',positive),('original',x)]+[(str(i),h.shuffled(x,i)) for i in spec['shuffle_seeds']]
    assert len({h.digest(y) for _,y in cases})==len(cases)
    for _,y in cases[2:]:
        assert y['st']==x['st'] and y['en']==x['en'] and y['cut']==cut
        assert [i for i,v in enumerate(y['c']) if v==0]==[i for i,v in enumerate(c) if v==0]
    geom=dict(section=spec['section'],first_page=base+ws[0]['page'],last_page=base+ws[-1]['page'],
              word_lengths=lens,cut=cut,end=len(c),preview=24,tail=len(c)-cut-24)
    return cases,(plain,k,sorted(skips)),geom,h.model(train)

def run(args):
    name,x,t,u=args
    r=h.search(x,t,u)
    return name,r

def main():
    cases,truth,geom,(t,u)=setup(); scores={}
    with ProcessPoolExecutor(max_workers=3) as pool:
        for name,r in pool.map(run,[(name,x,t,u) for name,x in cases]):
            scores[name]=r
            print(name,r['period'],round(r['tail_score'],4),flush=True)
    pos=scores['positive']; p,key,skips=truth; recovered=pos['chosen'][:]
    for a in pos['swaps']:
        i=a['offset']
        if a['alternative']==p[i:i+2]: recovered[i:i+2]=a['alternative']
    check=dict(exact_key=key==pos['key'],exact_text=p==pos['chosen'],covered=recovered==p,exact_skips=skips==pos['skips'],tail_pass=pos['screen_pass'])
    good=check['exact_key'] and check['covered'] and check['tail_pass']
    real=scores['original']; nulls=[scores[k]['tail_score'] for k,_ in cases[2:]]
    rank=1+sum(z>=real['tail_score'] for z in nulls)
    for r in scores.values():
        r['plaintext_hash']=h.digest(r.pop('chosen'))
    result=dict(protocol_hash=h.digest(h.read('real_period_112_protocol.json')),geometry=geom,threshold=h.THRESHOLD,positive_checks=check,
        positive_gate=good,real_rank=rank,null_min=min(nulls),null_median=float(np.median(nulls)),null_max=max(nulls),null_absolute_passes=sum(z>h.THRESHOLD for z in nulls),
        real_gate=good and real['screen_pass'] and rank==1,rows=scores)
    (h.D/'real_period_112_results.json').write_text(json.dumps(result,separators=(',',':'))+'\n')

if __name__=='__main__':main()
