"""python shiftbridge_433.py BOOK_FILES OUT. Two-word windows exactly equal up to one shared cyclic shift, preserving word break."""
from pathlib import Path
from crib_373 import pairs,R
import sys,json
from collections import defaultdict
def key(a,b):
 v=[R.index(t) for t in a+b];return len(a),tuple((i-v[0])%29 for i in v)
def main(d,o):
 raw=(d/'liber-primus__transcription--master.txt').read_text();pg=raw[raw.index('ᚱ-'):].split('%')
 def ab(k):return ''.join(R[(R.index(c)+k)%29] for c in 'ᛞᛄᚢ'),''.join(R[(R.index(c)+k)%29] for c in 'ᛒᛖᛁ')
 assert all(key(*ab(k))==key(*ab(0)) for k in range(29));a,b=ab(7);assert key(a,b)!=key(a,b[:-1]+R[(R.index(b[-1])+1)%29])
 out={}
 for n in (5,6,7):
  gs=defaultdict(list)
  for i in range(56):
   for j,a,b in pairs(pg[i+15]):
    if min(len(a),len(b))>=2 and len(a+b)>=n:gs[key(a,b)].append((i,j,a,b))
  matches=[]
  for vals in gs.values():
   for a in vals:
    for b in vals:
     if a[0]<b[0]:matches.append(dict(first=a,second=b,offset=(R.index(b[2][0])-R.index(a[2][0]))%29))
  out[n]={'cross_page_matches':len(matches),'exact':sum(i['offset']==0 for i in matches),'target':[v for v in matches if 27<=v['first'][0]<=32 and 54<=v['second'][0]<=55],'nonzero_examples':sorted([v for v in matches if v['offset']],key=lambda v:-len(v['first'][2]+v['first'][3]))[:12]}
 (o/'shiftbridge_433_results.json').write_text(json.dumps(out,ensure_ascii=False,indent=2)+'\n');print([(k,v['cross_page_matches'],v['exact'],len(v['target'])) for k,v in out.items()])
if __name__=='__main__':main(*map(Path,sys.argv[1:]))
