"""All two-cut placements retaining the fitted p8 key. python -B reset_241_addresses.py out.json.gz"""
from pathlib import Path
import json,gzip,sys,hashlib,itertools
from line_mechanism_108 import geometry
def scan(x,k,sites=None):
 n=len(x);p=len(k);A=2**p-1;m=[sum(1<<h for h,v in enumerate(k) if v!=c)for c in range(29)]
 def f(h,c):
    a=h&m[c];return ((a<<1)&A)|(a>>(p-1))|(h if c==0 else 0)
 h=1;pre=[True]
 for c in x:h=f(h,c);pre.append(h!=0)
 h=A;suf=[False]*(n+1);suf[n]=True
 for i in range(n-1,-1,-1):
    c=x[i];h=(((h>>1)|((h&1)<<(p-1)))&m[c])|(h if c==0 else 0);suf[i]=bool(h&1)
 single={j for j in range(1,n) if pre[j] and suf[j]}
 S=set(range(1,n)) if sites is None else sites
 t,u=(2474,3008) if n==3316 else (2,n-2);with_left=[];with_right=[];total=both=0;dist={r:[0,0] for r in [3,8,16,32,64]}
 byfirst={};small=set()
 for i in range(1,n):
    if i not in S or not pre[i]:continue
    h=1;last=i
    for j in range(i+1,n):
        h=f(h,x[j-1])
        if not h:break
        last=j
        if j not in S or not suf[j]:continue
        total+=1;both+=i not in single and j not in single
        if n<20:small.add((i,j))
        if i==t:with_left.append(j)
        if j==u:with_right.append(i)
        for d in dist:
            if abs(i-t)<=d and abs(j-u)<=d:dist[d][0]+=1
    if last>i:byfirst[i]=last
 for d in dist:dist[d][1]=sum(i in S and j in S and 0<i<j<n for i in range(t-d,t+d+1) for j in range(u-d,u+d+1))
 return dict(candidate_gaps=len(S),possible_pairs=len(S)*(len(S)-1)//2,single_legal=sorted(single&S),total=total,neither_single_works=both,eligible_first_given_marked_second=with_right,eligible_second_given_marked_first=with_left,local_box=dist),small
def truth(x,k,st,en):
 s={0}
 for c in x[st:en]:
    s=({(h+1)%len(k) for h in s if c!=k[h]}|(s if c==0 else set()))
 return bool(s)
def run():
 g,w=geometry();o=next(i for i,z in enumerate(g) if z[1]==8);x=[z[3] for z in g if z[1]==8];words={z['rune_offset']-o for z in w if z['section']==8 and z['rune_offset']!=o}
 k=[14]+[0]*7;a,_=scan(x,k);b,_=scan(x,k,words)
 assert 3008 in a['eligible_second_given_marked_first'] and 2474 in a['eligible_first_given_marked_second']
 nf=0
 for p in [2,3]:
    for kk in itertools.product(range(2),repeat=p):
        for xx in itertools.product(range(2),repeat=5):
            toy=list(xx);ref={(i,j) for i,j in itertools.combinations(range(1,5),2) if all(truth(toy,kk,st,en) for st,en in [(0,i),(i,j),(j,5)])}
            _,s=scan(toy,kk);assert s==ref;nf+=1
 return dict(k=k,n=len(x),trials=nf,all_gaps=a,all_complete_word_starts=b,real=[2474,3008],source_sha256=hashlib.sha256(bytes(x)).hexdigest())
if __name__=='__main__':
 r=run();Path(sys.argv[1]).write_bytes(gzip.compress(json.dumps(r,separators=(',',':')).encode(),mtime=0));
 for s in ['all_gaps','all_complete_word_starts']:
    a=r[s];print(s,[a[v] for v in ['candidate_gaps','possible_pairs','total','neither_single_works','local_box']],len(a['single_legal']),[(k,len(a[k]))for k in ['eligible_first_given_marked_second','eligible_second_given_marked_first']])
