"""Replay: python -B blockkeys_242_243.py blockkeys_242_243_results.json.gz [notebook files directory]. Requires g++ and NumPy."""
from pathlib import Path
import gzip,hashlib,json,sys,subprocess,tempfile
from itertools import accumulate
from math import prod
SELF=Path(__file__).resolve().parent
D=Path(sys.argv[2]).resolve() if len(sys.argv)>2 else SELF;sys.path.insert(0,str(D))
from line_mechanism_108 import geometry
from fixed_stream_133_135 import solved
from literal_230_strict import primary,span,wordopts
PK=[(1,7,13,22),(21,9,2,16),(3,15,27,8),(11,4,19,26),(24,8,6,17),(2,12,23,5)]
LIM=29**4
def key(id):return [(id//29**i)%29 for i in range(4)]
def encode(p,k):
    c=[];j=0
    for v in p:
        c.append((v+k[j])%29 if v else 0);j=(j+int(v!=0))%4
    return c
def ranges(cuts):return list(zip([0]+list(cuts),list(cuts)+[3316]))
def choose(ws,a,b):
    whole=[(i,j) for i,j in ws if a<=i and j<=b]
    return next(((i,j,'at_two_thirds') for i,j in whole if 3*(i-a)>=2*(b-a)),next(((i,j,'last_with_prefix') for i,j in reversed(whole) if i>a),(a,a,'none')))
def witness(x,k,mode):
    st={0:0};hist=[]
    for c in x:
        nxt={};back={}
        for j,score in st.items():
            acts=([(j,0)] if not c else [])+([((j+1)%4,(c-k[j])%29)] if c!=k[j] else [])
            for h,p in acts:
                v=score+(p!=c if mode=='changes' else p==18)
                if h not in nxt or v>nxt[h]:nxt[h]=v;back[h]=(j,p)
        st=nxt;hist.append(back)
    j=max(st,key=st.get);opt=st[j];out=[]
    for back in reversed(hist):j,p=back[j];out.append(p)
    out=out[::-1];assert encode(out,k)==x
    return dict(relative_key=k,score=opt,plaintext_sha256=hashlib.sha256(bytes(out)).hexdigest())
def rle(bits):
    z=[];a=None
    for i,bit in enumerate(list(bits)+['x']):
        if bit=='0' and a is None:a=i
        if bit!='0' and a is not None:z.append([a,i]);a=None
    return z
def distinct_words(x,w0,w1):
    # Post-protocol ambiguity check, restricted to the three real primary words. Keep only whole-block-extendible histories.
    kk,_=primary(x);outs=set();touch=[set() for _ in range(w1-w0)];identity=0
    for k in kk:
        nxt=set()
        for h,out in wordopts(x[w0:w1],k,span(x[:w0],k,{0})):
            if span(x[w1:],k,{h}):nxt.add(out)
        assert nxt
        identity+=tuple(x[w0:w1]) in nxt
        for out in nxt:
            outs.add(out)
            for j,v in enumerate(out):touch[j].add(v)
    return dict(full_block_keys=len(kk),distinct_complete_word_readings=len(outs),possible_rune_values_by_position=list(map(len,touch)),keys_allowing_printed_word=identity)
def maskid(k):return sum(v*29**j for j,v in enumerate(k))
def run():
    mf=next(p for p in (D/'marks_235_freeze.json',SELF/'marks_235_freeze.json',SELF.parent/'layout'/'marks_235_freeze.json') if p.exists())
    marks=json.loads(mf.read_text());cuts={t:marks[t+'_cuts'] for t in ('primary','secondary')}
    g,w=geometry();x=[a[3] for a in g if a[1]==8];assert len(x)==3316
    base=next(i for i,a in enumerate(g) if a[1]==8);w8=[v for v in w if v['section']==8];words=[(v['rune_offset']-base,v['rune_offset']-base+len(v['values'])) for v in w8]
    wordpos={v['rune_offset']-base:[v['page'],v['page_rune_offset']] for v in w8}
    pp,_=solved();gold0=[];gdlen=[]
    for (name,part),(y,l) in sorted(pp.items()):gold0.extend(map(int,y));gdlen.extend(map(int,l))
    gold=(gold0*2)[:len(x)];ends=[q for q in accumulate(gdlen*2) if q<=len(x)];goldw=list(zip([0]+ends[:-1],ends))
    with tempfile.TemporaryDirectory() as td:
        prog=Path(td)/'strict';subprocess.run(['c++','-std=c++17','-O3',str(SELF/'blockkeys_242_243.cpp'),'-o',str(prog)],check=True)
        memo={}
        def block(c,sp,word,detail,wanted=None,check=False):
            a,b=sp;i,j,choice=word;xx=c[a:b];u=i-a;v=j-a;gg=gold[i:j] if wanted is not None else [-1]*(j-i)
            tag=(tuple(xx),u,v,detail,tuple(gg))
            if tag in memo:return memo[tag]
            inp=' '.join(map(str,[b-a,u,v,int(detail)]+xx+gg))+'\n'
            line=subprocess.check_output([str(prog)],input=inp,text=True).split();npre,nword,nfull,changed,md,me,kd,ke,ng,ngfull=map(int,line[:10]);bits=line[10];bm=int(line[11],16);assert len(bits)==len(xx) and bm.bit_count()==nfull
            if check:
                kk,ct=primary(xx);raw=bm.to_bytes((LIM+7)//8,'little');assert len(kk)==nfull and all((raw[(t:=maskid(k))//8]>>(t%8))&1 for k in kk)
                assert (u==0 or ct[u-1]==npre) and (v==0 or ct[v-1]==nword)
            z=dict(interval=sp,length=b-a,word_interval=[i,j],choice=choice,prefix_keys=npre,through_word_keys=nword,block_keys=nfull)
            if wanted is None and i in wordpos:z['word_page_offset']=wordpos[i]
            if detail:
                z.update(keys_with_changed_output=changed,forced_copy=sum(q=='0' for q in bits),forced_ranges_local=rle(bits),max_changes=md,max_E=me,
                         change_witness=witness(xx,key(kd),'changes'),E_witness=witness(xx,key(ke),'E'))
                assert z['change_witness']['score']==md and z['E_witness']['score']==me
            if wanted is not None:
                assert bm&(1<<maskid(wanted)) and encode(gold[a:b],wanted)==xx and (not gg or ngfull>0)
                z.update(planted_key=wanted,keys_fitting_known_word=ng,whole_block_keys_fitting_known_word=ngfull)
            memo[tag]=(z,bm);return z,bm
        def scheme(c,sp,ww,d=True,plant=False,ch=False):
            items=[];common=(1<<LIM)-1
            for t,(a,b) in enumerate(sp):
                z,m=block(c,(a,b),choose(ww,a,b),d,PK[t] if plant else None,ch);items.append(z);common&=m
            legal=prod(z['block_keys'] for z in items)
            out=dict(blocks=items,independent_tuple_count=str(legal),same_ordered_keys=common.bit_count(),
                     nonzero_inherited_examples=[key(j) for j in range(1,LIM) if common.bit_length()>j and common>>j&1][:5])
            if d:out.update(tuples_with_at_least_one_changed_reading=str(legal-prod(z['block_keys']-z['keys_with_changed_output'] for z in items)),forced_copy=sum(z['forced_copy'] for z in items),max_changes=sum(z['max_changes'] for z in items),max_E=sum(z['max_E'] for z in items))
            return out
        real={'unbroken':scheme(x,[(0,len(x))],words,ch=True)};rot={};pl={}
        for name,mark in cuts.items():
            sp=ranges(mark);real[name]=scheme(x,sp,words,ch=True);rr=[b-a for a,b in sp]; rot[name]=[]
            for h in range(1,len(rr)):
                lens=rr[h:]+rr[:h];newcuts=list(accumulate(lens))[:-1];ns=ranges(newcuts)
                r=scheme(x,ns,words);rot[name].append(dict(cuts=newcuts,**{s:r[s] for s in ('independent_tuple_count','same_ordered_keys','forced_copy','max_changes','max_E')}))
            sx=sum((encode(gold[a:b],PK[j]) for j,(a,b) in enumerate(sp)),[])
            pl[name]=scheme(sx,sp,goldw,d=False,plant=True)
        for z in real['primary']['blocks']:
            a,b=z['interval'];i,j=z['word_interval'];z['word_ambiguity']=distinct_words(x[a:b],i-a,j-a)
        return dict(mark_sha256=hashlib.sha256(mf.read_bytes()).hexdigest(),section_start=base,length=len(x),key_space=LIM,real=real,rotated_length_controls=rot,planted=pl)
if __name__=='__main__':Path(sys.argv[1]).write_bytes(gzip.compress((json.dumps(run(),separators=(',',':'))+'\n').encode(),mtime=0))
