"""python -B joint_291_292.py EVIDENCE_DIRECTORY OUT.json.gz ; Python 3.10+, numpy required by corpus helpers."""
import sys,json,gzip,hashlib,itertools,collections
from pathlib import Path
F=Path(sys.argv[1]).resolve();sys.path.insert(0,str(F))
import transfer_261_262 as tr
tr.D=F
from lp_core import LET,lp
from lexical_words import tokenize_words
def sig(w):
 m={};return tuple(m.setdefault(a,len(m)) for a in w)
def add(m,used,x,y):
 a=m.copy();u=set(used)
 for c,p in zip(x,y):
  if c in a:
   if a[c]!=p:return
  elif p in u:return
  else:a[c]=p;u.add(p)
 return a,u
def index(V):
 out=collections.defaultdict(list)
 for v in sorted(V):out[sig(v)].append(v)
 return out
def words(x):return list(map(lambda w:''.join(LET[i] for i in w), x))
def solve(cs,idx):
 # Reorder variables once by the number of available values. Phrases always returned in printed order.
 candidates=[idx[sig(c)] for c in cs];order=sorted(range(len(cs)),key=lambda j:len(candidates[j]));p=[None]*len(cs)
 def walk(z,m,u):
  if z==len(cs):yield tuple(p),m,u;return
  j=order[z]
  for w in candidates[j]:
   r=add(m,u,cs[j],w)
   if r is not None:
    p[j]=w;yield from walk(z+1,*r)
 yield from walk(0,{},set())
def middle(a,b,c,idx,check):
 ix=idx[sig(b)]
 outer=list(solve((a,c),idx)); positions=[set() for _ in b];closed=set()
 for (v,w),m,u in outer:
  free=set(range(29))-u
  for j,x in enumerate(b):
   if x in m:positions[j].add(m[x])
   else:positions[j].update(free)
  for y in ix:
   if y not in closed and add(m,u,b,y) is not None:closed.add(y)
 if check:
  # Independent cross-check: cross-word agreement iff two long concatenations have identical equality pattern.
  pat=sig(a+c);pat3=sig(a+b+c)
  test=sorted((v,w) for v in idx[sig(a)] for w in idx[sig(c)] if sig(v+w)==pat)
  assert set(test)=={p for p,m,u in outer}
  verify={y for v,w in test for y in ix if sig(v+y+w)==pat3};assert verify==closed
  # Add a single target rune to the exterior transcript, testing all 29 possible labels.
  for j,x in enumerate(b):
   realpat=sig(a+c+(x,))
   answers={i for v,w in test for i in range(29) if sig(v+w+(i,))==realpat}
   assert positions[j]==answers
 return len(outer), [next(iter(s)) if len(s)==1 else None for s in positions],sorted(closed)
def gradeforced(out,true,prefix,d):
 d[prefix+'_runes']+=len(out);d[prefix+'_rune_calls']+=sum(v is not None for v in out);d[prefix+'_word_calls']+=all(v is not None for v in out)
 if true is not None:
  d[prefix+'_correct_runes']+=sum(v==p for p,v in zip(true,out))
  d[prefix+'_correct_words']+=list(true)==out
def group(name,cc,V,gold,loc,full):
 idx=index(V);tab={};pairs=[];tri=[];details=[];grade=collections.Counter()
 for n in (2,3):
  s=collections.Counter()
  for i in range(len(cc)-n+1):
   cs=cc[i:i+n];individual=all(idx[sig(x)] for x in cs);v=next(solve(cs,idx),None);ok=v is not None
   s['windows']+=1;s['individually']+=individual;s['joint']+=ok
   if gold is not None:
    pp=gold[i:i+n];vocab=all(y in V for y in pp);s['true_all_in_vocab']+=vocab;s['true_phrase_admitted']+=vocab and sig(sum(cs,()))==sig(sum(pp,()))
   if full:
    (pairs if n==2 else tri).append({'start':i,'ind':individual,'joint':ok})
   if ok: assert sig(sum(v[0],()))==sig(sum(cs,()))
  tab[n]=dict(s)
 longest=None
 if full:
  high=0;ll=[]
  for i in range(len(cc)):
   for e in range(i+max(1,high),len(cc)+1):
    witness=list(itertools.islice(solve(cc[i:e],idx),2))
    if not witness:break
    if e-i>high:high=e-i;ll=[]
    ll.append(dict(start=i,length=e-i,start_loc=loc[i],end_loc=loc[e-1],cipher=words(cc[i:e]),sample_phrases=[words(v[0]) for v in witness],sample_runes=[v[0] for v in witness]))
  # Follow-up count all assignments on the maximal spans; independently test each possible one-word-longer interval
  # via canonical equality signatures, without using the substitution backtracker or its word order.
  def alternative(cs):
   order=sorted(range(len(cs)),key=lambda j:len(idx[sig(cs[j])]))
   cs=tuple(cs[j] for j in order)
   target=[sig(sum(cs[:j+1],())) for j in range(len(cs))]
   def check(j,prev):
    if j==len(cs):return True
    return any(sig(prev+w)==target[j] and check(j+1,prev+w) for w in idx[sig(cs[j])])
   return check(0,())
  for q in ll:
   iv=cc[q['start']:q['start']+high]
   q['n_complete_assignments']=sum(1 for _ in solve(iv,idx))
   assert alternative(iv)
  assert all(not alternative(cc[i:i+high+1]) for i in range(len(cc)-high))
  longest={'length':high,'max_spans':ll}
 for i in range(1,len(cc)-1):
  a,b,c=cc[i-1:i+2];choices,forced,closed=middle(a,b,c,idx,check=(i==len(cc)//2 or (full and i in (1,2))))
  assert len({p for p in forced if p is not None})<=len(set(b))
  grade['windows']+=1;grade['exterior_possible']+=choices>0
  grade['closed_any']+=bool(closed);grade['closed_unique']+=len(closed)==1;grade['closed_nonunique']+=len(closed)>1
  grade['middle_alone_unique']+=len(idx[sig(b)])==1
  grade['closed_uniques_requiring_exterior']+=(len(closed)==1 and len(idx[sig(b)])>1)
  gradeforced(forced,gold[i] if gold else None,'open',grade)
  if gold is not None:
   l,m,r=gold[i-1:i+2]
   grade['closed_correct_unique']+=closed==[m]
   grade['true_anchors_in_vocab']+=(l in V and r in V)
   original=add({},set(),a+c,l+r)
   known=[None]*len(b)
   if original is not None:
    grade['oracle_exterior_compatible']+=1
    code,used=original
    free=set(range(29))-used
    known=[code[x] if x in code else next(iter(free)) if len(free)==1 else None for x in b]
   gradeforced(known,m,'oracle',grade)
   authentic=l in V and r in V and original is not None
   grade['true_anchor_assignment_admitted']+=authentic
   if authentic:
    grade['open_rune_calls_with_true_anchors_admitted']+=sum(j is not None for j in forced)
    assert all(y is None or y==z for y,z in zip(forced,m)) or name in ('welcome','second_koan','lp2_56')
  detail=dict(index=i,loc=loc[i] if loc else None,length=len(b),candidates_alone=len(idx[sig(b)]),outer_assignments=choices,open=forced,closed_count=len(closed),closed_guess=closed[0] if len(closed)==1 else None)
  if gold is not None:detail.update(truth=m,known_flank_forced=known)
  details.append(detail)
 return dict(counts=tab,longest=longest,grade=grade,grid_pairs=pairs,grid_triples=tri,centers=details)
def main():
 src=tr.sources();V=set(y for cc,pp in src.values() for y in pp)
 w=[w for w in tokenize_words('%'.join(lp[:56])) if w['section']==8];start=w[0]['rune_offset']
 z={}
 for name,lo,hi,sz in [('grid_left',2336,2474,33),('grid_right',2474,2644,40)]:
  piece=[u for u in w if lo<=u['rune_offset']-start<hi]
  assert len(piece)==sz and sum(len(a['values']) for a in piece)==hi-lo
  cc=tuple(tuple(a['values']) for a in piece);loc=[[a['page'],a['rune_offset']-start] for a in piece]
  z[name]=group(name,cc,V,None,loc,True)
 for name,(cc,pp) in src.items():
  vocab=set(y for g,(_,words_) in src.items() if g!=name for y in words_)
  z[name]=group(name,tuple(cc),vocab,tuple(pp),None,False)
 return dict(vocabulary_size=len(V),groups=z,source_hashes={s:hashlib.sha256((F/s).read_bytes()).hexdigest() for s in ['increment_calibration_sources.json','mechanism_coverage_results.json','liber-primus__transcription--master.txt']})
if __name__=='__main__':
 out=main();Path(sys.argv[2]).write_bytes(gzip.compress((json.dumps(out,sort_keys=True,separators=(',',':'))+'\n').encode(),mtime=0))
 for g,x in out['groups'].items():print(g,x['counts'],x['longest'] and (x['longest']['length'],len(x['longest']['max_spans'])),dict(x['grade']))
