"""Hidden-period synthetic controls; retain verified local FF alternatives."""
import json, math
from collections import Counter
import numpy as np
from phase_carry_109 import D, LET, letters, pages, model, train_key, decode, digest, read
from phase_swaps_109 import encode, decode as replay

PENALTY=math.log(29)
THRESHOLD=-PENALTY+0.10


def primitive(k):
    return next(k[:d] for d in range(1,len(k)+1) if len(k)%d==0 and k==k[:d]*(len(k)//d))


def construct(row):
    pre,post=letters(row['prefix']),letters(row['tail'])
    words=pre+post
    cut=sum(map(len,pre)); j=post.index(letters(row['target'])[0]); i=cut+sum(map(len,post[:j]))+row['pair']
    p=[v for w in words for v in w]
    assert i>=cut+24 and p[i:i+2].count(0)==1
    st=[int(i==0) for w in words for i in range(len(w))]
    en=[int(i==len(w)-1) for w in words for i in range(len(w))]
    rng=np.random.default_rng(row['seed']); L=row['period']
    for attempt in range(1,101):
        key=rng.integers(0,29,L).tolist()
        fs={j for j,(v,u) in enumerate(zip(p,rng.random(len(p)))) if v==0 and u<.5}
        a=i+p[i:i+2].index(0)
        fs.add(a)
        phase=(i-sum(j<i for j in fs))%L
        key[phase]=(-next(v for v in p[i:i+2] if v!=0))%29
        if primitive(key)!=key:continue
        c=encode(p,key,fs)
        assert c[i:i+2]==[0,0]
        if c[i-1]==0 or c[i+2]==0:continue
        public=dict(c=c,st=st,en=en,cut=cut)
        private=dict(key=key,p=p,skips=sorted(fs),collision=i,attempt=attempt)
        return public,private
    raise RuntimeError('constructor budget exhausted')


def shuffled(x,seed):
    rng=np.random.default_rng(seed); c=np.array(x['c']); before=c.copy()
    limits=[0,x['cut'],x['cut']+24,len(c)]
    for a,b in zip(limits,limits[1:]):
        ii=np.flatnonzero(c[a:b])+a; c[ii]=rng.permutation(c[ii])
        assert sorted(c[a:b])==sorted(before[a:b])
    assert list(np.flatnonzero(c==0))==list(np.flatnonzero(before==0))
    assert np.any(c!=before)
    return dict(x,c=c.tolist())


def search(x,t,u):
    c,st,en=x['c'],x['st'],x['en'];cut=x['cut']; rows=[]
    for L in range(3,17):
        k,info=train_key(c[:cut],st[:cut],en[:cut],L,t,u)
        p=primitive(k)
        rows.append(dict(tested_period=L,key=p,period=len(p),
                         penalized=float(info['prefix_score'])-len(p)*PENALTY))
    canonical={}
    for z in rows:
        sig=tuple(z['key'])
        if sig not in canonical or z['penalized']>canonical[sig]['penalized']:canonical[sig]=z
    ranking=sorted(canonical.values(),key=lambda r:(-r['penalized'],r['period'],r['tested_period']))
    win=ranking[0]; k=win['key'];pred=decode(dict(x,period=len(k)),k,t,True)
    tail=cut+24;p=pred['p']; fs=set(pred['fs'])
    score=float(sum(t[29 if st[i] else p[i-1],p[i]]+(t[p[i],29] if en[i] else 0.)
                for i in range(tail,len(c)))/(len(c)-tail))
    assert encode(p,k,fs)==c
    alternatives=[]
    for i in range(len(c)-1):
        if c[i:i+2]!=[0,0] or (i>0 and c[i-1]==0) or (i+2<len(c) and c[i+2]==0):continue
        if len(fs&{i,i+1})!=1 or p[i]==p[i+1]:continue
        alt=replay(c,k,fs^{i,i+1})
        assert encode(alt,k,fs^{i,i+1})==c and alt[:i]==p[:i] and alt[i+2:]==p[i+2:]
        assert alt[i:i+2]==p[i:i+2][::-1]
        alternatives.append(dict(offset=i,pair=p[i:i+2],alternative=alt[i:i+2]))
    # Simultaneous-swap witness for the product of disjoint local choices.
    all_offsets={j for z in alternatives for j in (z['offset'],z['offset']+1)}
    combined=p.copy()
    for z in alternatives:combined[z['offset']:z['offset']+2]=z['alternative']
    assert len(all_offsets)==2*len(alternatives) and encode(combined,k,fs^all_offsets)==c
    return dict(input_hash=digest(x),key=k,period=len(k),rankings=rows,distinct_keys=len(ranking),
                margin=win['penalized']-ranking[1]['penalized'] if len(ranking)>1 else None,
                tail_score=score,screen_pass=score>THRESHOLD,tail_n=len(c)-tail,
                chosen=p,skips=pred['fs'],swaps=alternatives)


def grade(result,truth):
    p=result['chosen']; q=truth['p']; seek=list(p)
    needed=0
    for alt in result['swaps']:
        i=alt['offset']
        if q[i:i+2]==alt['alternative']:
            seek[i:i+2]=alt['alternative']
            needed+=1
    n=result['tail_n']
    return dict(true_period=len(truth['key']),exact_key=result['key']==truth['key'],exact_plaintext=p==q,
                exact_skips=result['skips']==truth['skips'],covered_plaintext=seek==q,
                tail_exact=p[-n:]==q[-n:],tail_covered=seek[-n:]==q[-n:],
                mismatch_count=sum(a!=b for a,b in zip(p,q)),gold_tail_collision=truth['collision'],
                collision_carried=any(a['offset']==truth['collision'] for a in result['swaps']),
                alternatives_needed=needed)


def main():
    rec=read('mechanism_coverage_results.json')['known_method_groups']
    known={q['name']:q['values'] for q in read('increment_calibration_sources.json')['groups']}
    t,u=model([('%'.join(pages[i] for i in q['parsed_page_indices']),known[q['name']]) for q in rec])
    rows=[]
    for row in read('period_111_prose.json'):
        x,y=construct(row); z=shuffled(x,row['seed']+9187)
        a=search(x,t,u); a.update(grade(a,y))
        b=search(z,t,u)
        for r in (a,b):
            r['plaintext_hash']=digest(r.pop('chosen'))
        rows.append(dict(id=row['id'],positive=a,shuffled=b,constructor_tries=y['attempt']))
        print(row['id'], a['true_period'],a['period'],a['exact_key'],a['tail_score'],a['covered_plaintext'],
              a['exact_plaintext'],a['mismatch_count'],a['collision_carried'],b['period'],b['tail_score'],flush=True)
    gate=all(r['positive']['exact_key'] and r['positive']['covered_plaintext'] and
             r['positive']['screen_pass'] and not r['shuffled']['screen_pass'] for r in rows)
    print('gate',gate)
    (D/'period_111_results.json').write_text(json.dumps(dict(
        test_hashes={f:digest(read(f)) for f in ('period_111_protocol.json','period_111_prose.json')},
        threshold=THRESHOLD,gate=gate,controls=rows),separators=(',',':'))+'\n')

if __name__=='__main__':main()
