"""Independent direct-rune enumeration on a small challenge; archived-score replay on the real benchmark."""
import itertools,sys,subprocess,os
from pathlib import Path
import numpy as np
from exact_lp2_117 import original,tables,factor,h,top2,fs_at,maskslots,EPS,fixed
def test(exe):
    cases,_,_,t,old=original()
    c=[0,2,8,0,21,16,2,23,6,0,0,19,22,3,6,7,13,2,11,0]
    lens=[1,4,2,3,1,5,4];st=sum(([int(i==0) for i in range(l)] for l in lens),[]);en=sum(([int(i==l-1) for i in range(l)] for l in lens),[])
    x=dict(c=c,st=st,en=en,cut=len(c));fs=np.flatnonzero(np.array(c)==0)
    inp=' '.join(map(str,[len(c),*c,*st,*en,*t.ravel()]));a=subprocess.run([str(exe)],input=inp.encode(),stdout=subprocess.PIPE,check=True,env={**os.environ,'OMP_NUM_THREADS':'2'})
    ub=np.frombuffer(a.stdout,dtype=np.float64).reshape(16,32)
    tabs=tables(x,t);nchecks=0;brute=0
    for L in range(1,17):
        if L<=3:keys=np.array(list(itertools.product(range(29),repeat=L)))
        for m,b in enumerate(ub[L-1]):
            E,sk=factor(x,L,m,tabs,fs);q=np.zeros(29)
            for A in E:q=(q[:,None]+A).max(axis=0)
            assert abs(q.max()-L*h.PENALTY-b)<1e-7
            winners=top2(E);assert winners[0][1]-L*h.PENALTY<=b+1e-7;nchecks+=1
            if L<=3:
                # Score the literal next rune from scratch, without factor tables or cycle optimization.
                phase=0;y0=29;v=np.zeros(len(keys))
                for i,cv in enumerate(c):
                    if i in sk:y=0
                    else:y=(cv-keys[:,phase])%29;phase=(phase+1)%L
                    v+=t[29 if st[i] else y0,y]+(t[y,29] if en[i] else 0.);y0=y
                hi=np.partition(v,-2)[-2:];assert np.allclose(sorted(hi,reverse=True),[v for _,v in winners],rtol=0,atol=1e-8);brute+=len(v)
    for name,x in cases:
        r=old['rows'][name];a,_=fixed(x,r['key'],t);assert a['tail_score']==r['tail_score'] and a['plaintext_hash']==r['plaintext_hash']
    print(nchecks,'bounds checked;',brute,'literal key/mask scores enumerated; all 21 archived continuations match.')
if __name__=='__main__':test(Path(sys.argv[1]).resolve())
