"""Replay: python -B signatures_223_224.py signatures_223_224_results.json.gz [evidence directory]"""
import gzip,json,sys,hashlib,itertools
from pathlib import Path
from collections import Counter,defaultdict
import numpy as np
D=Path(sys.argv[2]).resolve() if len(sys.argv)>2 else Path(__file__).resolve().parent
sys.path.insert(0,str(D))
from fixed_stream_133_135 import solved
from line_mechanism_108 import geometry

def sig(w):return bytes((b-a)%29 for a,b in zip(w,w[4:]))
def rebuild(start,d):
    out=list(start)
    for i,step in enumerate(d):out.append((out[i]+step)%29)
    return tuple(out)
def encrypt(w,k,pos):return tuple((a+k[(pos+i)%4])%29 for i,a in enumerate(w))
def extract(c,w,pos):
    k=[0]*4
    for i in range(4):k[(pos+i)%4]=(c[i]-w[i])%29
    return tuple(k)
def pack(y,l):
    j=0;rows=[]
    for n in l:rows.append((j,tuple(map(int,y[j:j+n]))));j+=n
    return rows
def panels(ws,omit=()):
    for j,(off,w) in enumerate(ws):
        if off in omit:continue
        if len(w)>=8:yield (off,(len(w),),w,(j,))
        if j+1<len(ws):
            q,ww=ws[j+1]
            if q==off+len(w) and q not in omit and len(w)+len(ww)>=10:yield(off,(len(w),len(ww)),w+ww,(j,j+1))
def lex(ws):
    r=defaultdict(set)
    for p in ws:
        for off,sh,w,ix in panels(p):r[sh].add(w)
    return r
def index(L):
    z=defaultdict(lambda:defaultdict(list))
    for sh,ws in L.items():
        for w in sorted(ws):z[sh][sig(w)].append(w)
    return z
def geomdata():
    geo,ws=geometry();s=[v for v in ws if v['section']==8];q=next(w for w in s if w['page']==51 and w['geo'][-1][0]==52)
    ww=[next(w for w in s if (w['page'],w['page_rune_offset'])==(p,n)) for p,n in ((40,101),(42,112),(46,7))]
    ids={w['rune_offset'] for w in [q]+ww};assert len(ids)==4
    return [(w['rune_offset'],tuple(w['values'])) for w in s],q,ww,ids
def run():
    pp,_=solved();sources={g:pack(y,l) for (g,s),(y,l) in pp.items()};assert len(sources)==7
    folds={};alias=[]
    for i,(g,ws) in enumerate(sorted(sources.items())):
        L=lex([ww for k,ww in sources.items() if k!=g]);I=index(L);out=[Counter(),Counter()];k=(i+1,3,12+2*i,26-i)
        for pos,sh,w,ix in panels(ws):
            st=out[len(sh)-1];st['sites']+=1;x=encrypt(w,k,pos);s=sig(x);assert sig(w)==s and w==rebuild(w[:4],s)
            match=I.get(sh,{}).get(s,[]);state='true' if w in match else 'absent';other=[u for u in match if u!=w];st[state+('_plus_alias' if other else '_only')]+=1;st['matches']+=len(match);st['compatible_candidates']+=len(L[sh])
            for target in match:
                kk=extract(x,target,pos);assert x==encrypt(target,kk,pos)
                if target==w:assert kk==k
                else:alias.append(dict(g=g,pos=pos,sh=sh,truth=w,other=target))
        folds[g]=out
    ws,q,prior,omit=geomdata();pan=list(panels(ws,omit));L=lex(list(sources.values()));I=index(L);rng=np.random.default_rng(223330100)
    chosen=set();plant=[]
    for off,sh,_,ix in pan:
        if sh in chosen or sh not in L:continue
        chosen.add(sh);w=min(L[sh]);k=tuple(map(int,rng.integers(0,29,size=4)))
        while k[:2]==k[2:]:k=tuple(map(int,rng.integers(0,29,size=4)))
        c=encrypt(w,k,off);assert w in I[sh][sig(c)] and extract(c,w,off)==k and rebuild(w[:4],sig(c))==w
        for i in range(len(c)):
            edited=list(c);edited[i]=(edited[i]+1)%29
            assert w not in I[sh].get(sig(edited),())
        plant.append(dict(offset=off,shape=sh,changed_positions=len(w)))
    row=[Counter(),Counter()];toy=[0.,0.];hits=[];details=[];moved=[];near=[]
    for off,sh,x,ix in pan:
        st=row[len(sh)-1];st['sites']+=1;n=len(x);cand=L.get(sh,());st['with_candidates']+=bool(cand);st['comparisons']+=len(cand);toy[len(sh)-1]+=len(cand)*29.**(4-n)
        S=sig(x);a=sum(sig(w)[:1]==S[:1] for w in cand);b=sum(sig(w)[:2]==S[:2] for w in cand);ms=I.get(sh,{}).get(S,[]);st['one']+=a;st['two']+=b;st['full']+=len(ms)
        details.append([off,sh,len(cand),a,b,len(ms)])
        for w in sorted(cand):
            sw=sig(w)
            if S[:2]==sw[:2] and S!=sw:
                fail=next(i for i,(a1,b1) in enumerate(zip(S,sw)) if a1!=b1)
                near.append(dict(off=off,sh=sh,form=w,cipher_trace=list(S),candidate_trace=list(sw),first_mismatch=fail))
        if cand:moved.append((ix,sh))
        for w in ms:
            k=extract(x,w,off);assert x==encrypt(w,k,off);aoff=q['rune_offset'];keyphase=tuple(k[(aoff+i)%4] for i in range(4))
            qt=tuple((v-k[(aoff+i)%4])%29 for i,v in enumerate(q['values']))
            agree=[j['page'] for j in prior if qt==tuple((v-k[(j['rune_offset']+i)%4])%29 for i,v in enumerate(j['values']))]
            hits.append(dict(off=off,sh=sh,w=w,key_anchor_phase=keyphase,matched_families=agree))
    # One shuffle per original word per replicate, shared by overlapping sites.
    rng=np.random.default_rng(224330100);B=1023
    arrays=[rng.permuted(np.tile(np.asarray(w,dtype=np.int16),(B,1)),axis=1) for off,w in ws]
    counts=np.zeros((2,B),dtype=int)
    for ix,sh in moved:
        z=np.hstack([arrays[j] for j in ix]);s=np.ascontiguousarray((z[:,4:]-z[:,:-4])%29,dtype='uint8');book=I[sh]
        vals=np.fromiter((len(book.get(t.tobytes(),())) for t in s),int,B);counts[len(sh)-1]+=vals
    meta={name:sum(len(ww) for sh,ww in L.items() if len(sh)==i) for i,name in ((1,'word_types'),(2,'phrase_types'))}
    return dict(sign_convention='next minus previous, modulo 29, lag four',folds=folds,alias=alias,lexicon=meta,plants=plant,excluded=sorted(omit),section=row,toy=toy,hits=hits,near=near,site_counts=details,null=dict(B=B,counts=counts.tolist()))
if __name__=='__main__':Path(sys.argv[1]).write_bytes(gzip.compress(json.dumps(run(),separators=(',',':')).encode(),mtime=0))
