"""Apply one fixed marked-reset key to the old independently located two-word ciphertext recurrence. Run: python -B reset_244_transfer.py output.json"""
import json,sys
from pathlib import Path
from collections import Counter
from line_mechanism_108 import geometry
from lp_core import LET
def steps(h,c,k):
 if not c:yield h,0
 if c!=k[h]:yield (h+1)%len(k),(c-k[h])%29
def analysis(x,k,start,at,cuts):
 n=len(x);st={start:1};supports=[];stop=None
 for i,c in enumerate(x):
    if i in cuts and st:st={0:sum(st.values())}
    edges=[(h,h2,p) for h in st for h2,p in steps(h,c,k)];new=Counter()
    for h,h2,_ in edges:new[h2]+=st[h]
    supports.append(edges);st=dict(new)
    if not st:stop=i;break
 def strs(require_full):
    if len(supports)<at+6 or (require_full and stop is not None):return []
    end=len(supports) if require_full else at+6;live={b for a,b,v in supports[end-1]};vv=[]
    for i in range(end-1,at-1,-1):
        if i+1 in cuts and 0 in live:live=set(range(len(k)))
        edges=[e for e in supports[i] if e[1] in live];live={a for a,b,v in edges}
        if i<at+6:vv.append(edges)
    seq={(h,()) for h in live}
    for edges in reversed(vv):
        seq={(b,vals+(v,)) for a,vals in seq for aa,b,v in edges if aa==a}
    return sorted({vals for _,vals in seq})
 return dict(first_impossible=stop,whole_section_paths=sum(st.values()),local_phrase=strs(False),complete_phrase=strs(True))
def main():
 g,_=geometry();by={s:[a for a in g if a[1]==s] for s in [6,8]}
 def get(s,p,off):return [i for i,z in enumerate(by[s]) if z[0]==p][off]
 l=get(6,27,28);r=get(8,55,70);x=[z[3] for z in by[6]];y=[z[3] for z in by[8]];assert x[l:l+6]==y[r:r+6]
 k=[14]+[0]*7
 right=analysis(y,k,0,r,{2474,3008});assert right['complete_phrase']
 left={h:analysis(x,k,h,l,set()) for h in range(8)}
 for h,a in left.items():
    a['matching_local']=[z for z in a['local_phrase'] if z in right['complete_phrase']]
    a['matching_complete']=[z for z in a['complete_phrase'] if z in right['complete_phrase']]
    if a['first_impossible'] is not None:
        i=a['first_impossible'];p=by[6][i][0];a['conflict_address']=[p,sum(int(v[0]==p) for v in by[6][:i]),LET[x[i]]]
 k2=[14,0,0,0,0,0,0,0];pt=[1,2,0,3,15,6,0,4,2,3,4,21,5,6];c=[];h=0
 for u in pt:
    if not u:c.append(0)
    else:c.append((u+k2[h])%29);h=(h+1)%8
 z=analysis(c,k2,0,3,set());assert tuple(pt[3:9]) in z['complete_phrase']
 return dict(key=k,lookup=LET,printed=x[l:l+6],origin_6=6527,local_at_6=l,local_at_8=r,left=left,right=right)
if __name__=='__main__':
 a=main();Path(sys.argv[1]).write_text(json.dumps(a,separators=(',',':'))+'\n')
 print('right',a['right']);print('left',[(h,z['first_impossible'],z['local_phrase'],z['matching_local']) for h,z in a['left'].items()])
