"""python -B echo_294.py EVIDENCE RESULT.json.gz. Three local five-step crib tests."""
import sys,json,gzip
from pathlib import Path
from lexicon_293 import inputs,gp,pack,LET,sig
def solve(c,anchor,p):
 assert len(p)==8 and p[:3]==p[5:] and 0 not in p
 k=tuple((a-b)%29 for a,b in zip(c[anchor:anchor+5],p[:5]));assert all((v+k[j%5])%29==n for j,(n,v) in enumerate(zip(c[anchor:anchor+8],p)))
 def fwd(i,states,remember=False):
  t=set()
  for h,buf in states:
   if i==anchor and h!=0:continue
   for plain,hh in ((0,h),((c[i]-k[h])%29,(h+1)%5)):
    if hh==h and c[i]!=0 or hh!=h and plain==0:continue
    if anchor<=i<anchor+8 and p[i-anchor]!=plain:continue
    t.add((hh,buf+(plain,) if remember and i<3 else buf))
  return t
 # Independent arms must meet the exact slot zero fixed by this crib; no best-looking phase.
 h={0};left=0
 for v in c[:anchor][::-1]:
  h={j for j in range(5) if ((j+1)%5 in h and v!=k[j]) or (v==0 and j in h)}
  if not h:break
  left+=1
 st={(0,())};right=0
 for i in range(anchor,len(c)):
  st=fwd(i,st)
  if not st:break
  right+=1
 ss={(j,()) for j in range(5)};short=None
 for i in range(len(c)):
  ss=fwd(i,ss,True)
  if i==anchor+7:short=sorted({p for j,p in ss})
 full=sorted({p for j,p in ss})
 assert bool(short)==(left==anchor) and bool(full)==(left==anchor and right==len(c)-anchor)
 return dict(measured_key=k,left_steps=left,right_steps_including_crib=right,print_before=anchor,print_from_crib=len(c)-anchor,through_crib=short,through_full=full)
def main(d):
 h,fw,sec=inputs(d);v=tuple(n for w in fw[33:] for n in w);assert len(v)==170
 z=json.loads(gzip.decompress((d/'lexicon_293_slice.json.gz').read_bytes()));t=v[43:51];g=sig(t);words=z['tested_shape_examples'][g];assert len(words)==z['tested_shape_base_headword_counts'][g]==3 and len(set(t[:5]))==5
 # Positive control: plant a 5-slot schedule with F holds in the unobserved corridor between opener and crib.
 key=(3,18,4,20,12);p=gp('outshout');plain=(17,3,5,7,0,12,0,10,9)+p+(24,3,4,0,13);hidx=(-sum(x!=0 for x in plain[:9]))%5;c=[]
 for a in plain:
  if a==0:c.append(0)
  else:c.append((a+key[hidx])%29);hidx=(hidx+1)%5
 chk=solve(tuple(c),9,p);assert chk['measured_key']==key and tuple(plain[:3]) in chk['through_full']
 return dict(target=t,control_ok=True,trials={w:solve(v,43,gp(w)) for w in words})
if __name__=='__main__':pack(Path(sys.argv[2]),main(Path(sys.argv[1]).resolve()))
