"""python -B local_284.py INPUT_DIR output.json.gz. Conditional projection on four named models."""
from pathlib import Path
import json,sys,gzip,hashlib,itertools
from seam_284 import R
def paths(c,k,h):
 if c==0:yield h,0
 p=(c-k[h])%29
 if p:yield (h+1)%len(k),p
def project(Cs,k,lo=130,hi=147):
 # enumerate full 17-rune outputs over only states reachable from the prefix and compatible with the entire remaining suffix
 h=set(range(len(k)))
 for c in Cs[:lo]:h={a for u in h for a,r in paths(c,k,u)}
 s={(u,()) for u in h}
 for c in Cs[lo:hi]:s={(a,v+(r,)) for u,v in s for a,r in paths(c,k,u)}
 end=set(range(len(k)))
 for c in reversed(Cs[hi:]):end={u for u in range(len(k)) if any(a in end for a,r in paths(c,k,u))}
 return {v for a,v in s if a in end}
def main(d):
 p=d/'liber-primus__transcription--master.txt';raw=p.read_bytes();assert hashlib.sha256(raw).hexdigest()=='b0b2e13c3cd35512ee5955a2d9a56c22d7410e283d35dd9c90abbaa7b99279eb'
 t=raw.decode();pages=t[t.index('ᚱ-'):].split('%')[:73]
 # Independent extraction through section delimiters; both experiments must agree on geometry.
 chunks='%'.join(pages[15:15+56]).split('$');x=[R.index(c) for c in chunks[8] if c in R];assert len(x)==3316
 cs=x[2336:2644];ctr=cs[130:147];assert ctr==x[2466:2483]
 key=next(g['ordinal_key_values'] for g in json.loads((d/'mechanism_coverage_results.json').read_text())['known_method_groups'] if g['name']=='second_koan')
 models={'identity':{tuple(ctr)},'reflect2':{tuple((2-c)%29 for c in ctr)}}
 for b in (8,17):
  k=[(n+b)%29 for n in key];v=project(cs,k);models['second_plus_'+str(b)]=v
  # Independent forward simulation from every start; keep only output positions 130..146, then discard every partial path that dies.
  dp={(i,()) for i in range(len(k))}
  for i,c in enumerate(cs):
   nq=set()
   for h,word in dp:
    if c==0:nq.add((h,word+(0,) if 130<=i<147 else word))
    if c!=k[h]:
     p=(c-k[h])%29; nq.add(((h+1)%len(k),word+(p,) if 130<=i<147 else word))
   dp=nq
  assert v=={q for h,q in dp}
 assert all(models.values());sets={}
 for m,words in models.items():
  sets[m]=[[*sorted({v[i] for v in words})] for i in range(17)]
 def test(ix):
  q=[{tuple(s[i] for i in ix) for s in words} for words in models.values()]
  return all(a.isdisjoint(b) for a,b in itertools.combinations(q,2))
 one=[i for i in range(17) if test([i])]
 two=[(i,j) for i,j in itertools.combinations(range(17),2) if test([i,j])]
 # Exploratory word-shape counts. Join pages before tokenization, retaining cross-page words.
 def split_words(v):
  # Use actual historical tokenizer for word boundaries (punctuation and page/line continuation).
  sys.path.insert(0,str(d));from lexical_words import tokenize_words
  return [w['values'] for w in tokenize_words(v)]
 groups=json.loads((d/'mechanism_coverage_results.json').read_text())['known_method_groups']
 refs={g['name']:g['values'] for g in json.loads((d/'increment_calibration_sources.json').read_text())['groups']}
 census={}; forms=set()
 for g in groups:
  name=g['name'];plain=refs[name];assert hashlib.sha256(bytes(plain)).hexdigest()==g['plaintext_rune_values_sha256']
  i=0;ww=[]
  for c in split_words('%'.join(pages[j] for j in g['parsed_page_indices'])):
   a=tuple(plain[i:i+len(c)]);i+=len(c)
   if len(c)==3:ww.append(a)
  assert i==len(plain);forms.update(ww)
  census[name]={'three_runes':len(ww),'initial_double':sum(a==b for a,b,c in ww),'AAB':sum(a==b!=c for a,b,c in ww)}
 starts={m:sorted(set(v[8:10] for v in seq)) for m,seq in models.items()}
 return {'first_pair_options':starts,'word_shape_census':census,'distinct_3rune_forms':len(forms),'distinct_AAB_forms':sorted(w for w in forms if w[0]==w[1]!=w[2]),'length':17,'target_cipher':ctr,'seam_index':8,'unique_full_transcriptions_by_model':{k:len(v) for k,v in models.items()},'possible_plain_runes':sets,'unconditional_single_separators':one,'unconditional_pair_separators':two,'indexing':'zero-based within four words of 2+6 | 3+6 runes'}
if __name__=='__main__':
 z=main(Path(sys.argv[1]));Path(sys.argv[2]).write_bytes(gzip.compress((json.dumps(z,sort_keys=True,separators=(',',':'))+'\n').encode(),mtime=0))
