"""OPENBLAS_NUM_THREADS=1 python3 -B phase_149_audit.py summary.json; beside 145-149 files."""
import gzip,json,sys,math
from collections import Counter
from pathlib import Path
import numpy as np
from phase_145_149 import solved,layout_known,train,readout,seeds,plain,extend,trim,ordered
D=Path(__file__).resolve().parent
def count(rs,fun):return sum(bool(fun(r)) for r in rs)
def rot(k,t):return tuple(k[t:])+tuple(k[:t])
def run():
    rows=json.load(gzip.open(D/'phase_145_149_results.json.gz'))['rows']
    P,_=solved();L,_=layout_known();M={g:train(L,g) for g,_ in P};oracle=[];nc=[];st=[];ws={};families={};pos=lambda r:r['cases']['positive']
    for r in rows:
        c=pos(r);p=len(r['key']);z=c['result']['widths']['16']['chosen'];g=r['g'];a=r['start'];y=P[g,0][0][a:a+88];m=M[g];b=c['b'];stop=b+8;tk=r['key'].copy();slot=r['id']%p;tk[slot]=(tk[slot]+1)%29
        xx=np.array(c['cipher']);truth=tuple(r['key']);bank=extend({(truth,32%p,int(y[31])):0},xx[32:b],m[1]);phdiag={}
        for num in (1,4):
            v=trim(bank,num);end=extend(v,xx[b:stop],m[1]);first=ordered(end)[0];ans=readout(first,xx,y,stop,m,truth,c['endphase'])
            phdiag[str(num)]=dict(breakphase=any(t==c['phase'] for k,t,last in v),right=ans['right'],exact=ans['exact'])
        oracle.append(dict(id=r['id'],widths=phdiag))
        x=np.array(c['cipher']);n=len(x)-stop;x[stop:]=(y[stop:]+np.array(tk)[(c['endphase']+np.arange(n))%p])%29
        frozen=(tuple(z['k']),z['t'],z['last']);ans=readout(frozen,x,y,stop,m,tuple(tk),c['endphase'])
        nc.append(dict(id=r['id'],slot=slot,accept=ans['accept'],quality=ans['quality'],right=ans['right'],exact=ans['exact']))
        for kind,rr in [('positive',z),('progressive',r['cases']['progressive']['result']['widths']['16']['chosen']),('substitution',r['cases']['substitution']['result']['widths']['16']['chosen']),('switch',r['cases']['switch']['chosen']),('one_slot_switch',ans)]:families.setdefault(kind,[]).append(rr)
        if 'stress' in r:
            v=r['stress'];x=np.array(v['cipher']);line=dict(id=r['id'],group=g,printed=v['printed'],clean=z['right'],hole=v['hole'])
            for tag in ['ignore','allow']:
                s,_=seeds(x[:32],m,tag=='allow');sc=v['out'][tag];live=rot(r['key'],31%p)
                dec=sc['chosen'];truth=rot(r['key'],(v['b']+8-len(v['skip']))%p);at=rot(dec['k'],dec['t'])
                line[tag]=dict(seed_equivalent=any(rot(k,t)==live for k,t,_ in s),seed_key_and_phase=sc['seed_clock'],seed_key=sc['seed_key'],chosen_equivalent=at==truth,future=dec['right'],rotated_exact=(at==truth and dec['k']!=r['key']))
                assert (at==truth)==dec['exact']
            st.append(line)
    def fam(v):
        return dict(n=len(v),accept=count(v,lambda a:a['accept']),exact=count(v,lambda a:a['exact']),both=count(v,lambda a:a['exact'] and a['accept']),accepted_wrong_ids=[r['id'] for r,a in zip(rows,v) if a['accept'] and not a['exact']],runes=sum(a['right'] for a in v))
    fams={k:fam(v) for k,v in families.items()}
    for width in ['1','4','16','0']:
        zz=[pos(r)['result']['widths'][width] for r in rows]
        ws[width]=dict(phase_at_break=count(zz,lambda a:a['survives']),phase_after_preview=count(zz,lambda a:a['post_survives']),exact=count(zz,lambda a:a['chosen']['exact']),runes=sum(a['chosen']['right'] for a in zz),gains=[],losses=[])
        for r,z in zip(rows,zz):
            first=pos(r)['result']['widths']['1']['chosen'];after=z['chosen']
            if first['exact']!=after['exact']:ws[width]['gains' if after['exact'] else 'losses'].append(r['id'])
    vp=ws['16'];base=ws['1'];f=fams['positive']
    gate=dict(coverage=f['both']/len(rows)>=.75,control=all(fams[k]['accept']/len(rows)<=.05 for k in ['progressive','substitution','switch']),additional=vp['exact']-base['exact']>=2,groups=sum(sum((r['id'] in vp['gains'])-(r['id'] in vp['losses']) for r in rows if r['g']==g)>0 for g,_ in P)>=2)
    return dict(windows=len(rows),widths=ws,families=fams,decision=gate,lp2=all(gate.values()),stress=st,one_slot_twins=nc,known_key_diagnostic=oracle)
if __name__=='__main__':Path(sys.argv[1]).write_text(json.dumps(run(),indent=2)+'\n')
