"""Independent scalar rescore of every retained bank, confidence decision and blind grade. python -B clock_184_verify.py"""
from words_155_163 import Model,solved,layout_known
from line_mechanism_108 import source
from lexical_words import tokenize_words
from lp_core import R
from itertools import combinations,accumulate
from collections import defaultdict,Counter
from pathlib import Path
import gzip,json,math
D=Path(__file__).resolve().parent
def read(n):return json.loads(gzip.decompress((D/n).read_bytes()))
def dec(x,k,ph,h=()):
    ret=[]
    for i,c in enumerate(x):
        if i in h:assert c==0;ret.append(0)
        else:ret.append((c-k[ph%len(k)])%29);ph+=1
    return ret,ph%len(k)
def masks(x,b):
    for t in range(b+1):yield from combinations([i for i,c in enumerate(x) if c==0],t)
def main():
    P,_=solved();L,_=layout_known();d=read('clock_175_184_cases.json.gz');fl=json.loads((D/'words_155_163_summary.json').read_text())['thresholds'];ms={g:Model(P,L,{g}) for g,_ in P};counts=Counter()
    for row in d['rows']:
        x=row['x'];y=row['y'];k=row['truth'];g=row['g'];a=row['a'];hs=row['holds'];Y,ll=P[g,0];m=ms[g]
        assert y==Y[a:a+170].tolist() and dec(x,k,0,hs)[0]==y
        bounds=[(i-a,j-a) for i,j in zip([0]+list(accumulate(ll)),accumulate(ll))]
        def wd(z,n):
            out=0.;nr=0;nw=0
            for i,j in bounds:
                if n<=i<j<=n+len(z):
                    w=tuple(z[i-n:j-n]);v=(29,29)+w+(29,);sp=math.exp(sum(m.sp[b,c,e] for b,c,e in zip(v,v[1:],v[2:])));out+=math.log(.5*(sp+m.lex[w]/m.n));nr+=j-i;nw+=1
            return out,nr,nw
        def pairs(z):return float(m.q[z[0]]+sum(m.B[i,j] for i,j in zip(z,z[1:]))) if z else 0.
        for method,v in row['methods'].items():
            bank=row['banks'][method];K={tuple(e[0]) for e in bank}
            if method=='wrong':assert all(len(t)!=len(k) or not any(list(t[j:]+t[:j])==k for j in range(len(k))) for t in K)
            opts=[];half=defaultdict(lambda:-1e99)
            for rank,(kk,ph,sh) in enumerate(bank):
                assert dec(x[:72],kk,0,sh)[1]==ph
                for h in masks(x[72:122],0 if method=='fixed' else 2):
                    z,end=dec(x[72:122],kk,ph,h);s=wd(z,72)[0];o=(-round(s,9),rank,len(h),h)
                    opts.append((o,tuple(kk),end,sh,h,s,rank))
                    for t,(seg,n) in enumerate([(z[:25],72),(z[25:],97)]):
                        val,nn,_=wd(seg,n);half[tuple(kk),t]=max(half[tuple(kk),t],val)
            chosen=min(opts)[1];assert list(chosen)==v['key'];states={}
            for o,kk,ph,sh,h,s,rank in sorted(opts):
                if kk==chosen and ph not in states:states[ph]=(s,rank,h)
            keys=list(dict.fromkeys(tuple(entry[0]) for entry in bank));cert=True
            for t in [0,1]:
                order=sorted(keys,key=lambda ky:-round(half[ky,t],9));win=order[0];gap=half[win,t]-half[order[1],t] if len(keys)>1 else None;num=wd(x[72+t*25:97+t*25],72+t*25)[1];llh=half[win,t]/num if num else None;b=v['halves'][t]
                assert list(win)==b[0] and ((gap==b[1]) or abs(gap-b[1])<1e-7) and ((llh==b[2]) or abs(llh-b[2])<1e-7)
                cert=cert and win==chosen and gap is not None and gap>=math.log(3) and llh is not None and llh>=fl[g]
            assert cert==v['cert']
            for name,e in v['variants'].items():
                n=int(name[4:]);rr=[]
                for ph,(s,rank,h) in states.items():
                    z,_=dec(x[122:122+n],chosen,ph);word,_,nw=wd(z,122);val=word if name.startswith('word') else pairs(z)
                    rr.append((-round(s+val,9),rank,len(h),h,ph))
                ph=min(rr)[-1];z,_=dec(x[138:],chosen,ph+16);assert e['ph']==ph and e['preview_words']==nw and e['hits']==sum(i==j for i,j in zip(z,y[138:]));counts['blind_grades']+=1
            counts['banks']+=1
        if row.get('tail'):
            v=row['methods']['hidden'];t=row['tail'];kk=v['key'];ph=v['variants']['word16']['ph']+16
            assert dec(t['x'],k,138-len(hs),[t['planted']])[0]==y[138:]
            al=[]
            for h in masks(t['x'],1):
                z,_=dec(t['x'],kk,ph,h);al.append((-round(wd(z,138)[0],9),len(h),list(h),sum(a==b for a,b in zip(z,y[138:]))))
            assert al[0][-1]==t['blind'] and min(al)[-2:]==(t['called'],t['adapt']);counts['tail_cases']+=1
    ss=source.split('%');ws=tokenize_words(source);runes=[[x for x in pg if x in R] for pg in ss];starts=list(accumulate([0]+[len(pg) for pg in runes]))
    for t in d['layout']:
        p=t['p'];n=t['n'];pg=runes[p];pos=[i+1 for i,c in enumerate(pg) if c==R[0] and i+1+n<=len(pg)]
        def nw(start):return sum(start<=w['rune_offset'] and w['rune_offset']+len(w['values'])<=start+n for w in ws)
        assert t['inside']==len(pos) and t['withword']==sum(nw(starts[p]+i)>0 for i in pos)
        can=p+1<len(runes) and len(pg)>0 and len(runes[p+1])>=n
        assert can==t['cross'] and t['lastF']==bool(pg and pg[-1]==R[0]) and t['crosswords']==(nw(starts[p+1]) if can else None);counts['layout_rows']+=1
    for t in read('clock_182_limit_results.json.gz')['rows']:
        k=[0]*t['p'];k[120%len(k)]=7;Y,_=P[t['g'],0];y=list(map(int,Y[t['a']:t['a']+170]));u=122 if t['tag']=='advance' else 121
        for n,ph,hits,vs in t['records']:
            z=[(yy+k[(u+i)%len(k)])%29 for i,yy in enumerate(y[122:])];m=ms[t['g']];pred=[pairs(dec(z[:n],k,b)[0]) for b in (122,121)];assert all(abs(x-y)<1e-7 for x,y in zip(vs,pred));b=121 if round(pred[1]-pred[0],9)>0 else 122;assert b%len(k)==ph and sum(i==j for i,j in zip(dec(z[16:],k,b+16)[0],y[138:]))==hits;counts['stress_grades']+=1
    print(dict(counts))
if __name__=='__main__':main()
