"""python -B row_distance_327.py EVIDENCE OUTPUT.json.gz. Standard library only.
Exact distance to either of the two frozen rule families, training data only.
"""
import sys,json,itertools,hashlib,operator,gzip
from collections import Counter
from functools import reduce
from pathlib import Path
A='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwx'
def byte(token):return A.index(token[0])*60+A.index(token[1])
def token(v):return A[v//60]+A[v%60]
def k(row,rule):
 return (row[-1]-sum(row[:-1]))%256 if rule=='sum' else reduce(operator.xor,row)
def candidates(row,c,rule):
 # In each column exactly one replacement byte makes that particular row agree.
 wanted=k(row,rule)
 if c==wanted:return [(0,None,None)]
 out=[]
 for i,v in enumerate(row):
  w=(v^(wanted^c)) if rule=='xor' else ((v+(c-wanted if i==7 else wanted-c))%256)
  assert 0<=w<=255
  out.append((sum(x!=y for x,y in zip(token(v),token(w))),i,w))
 return out
def main(d):
 a=json.loads((d/'grid_read_a_254.json').read_bytes())
 b=json.loads((d/'grid_read_b_254.json').read_bytes())
 stats=json.loads((d/'grid_witnesses_249.json').read_bytes())
 n0,n1,n2=stats['per_page'];assert (n0,n1,n2)==(80,104,72)
 n=(n0+n1)//8; ts=[v.split() for v in a['rows'][:n]]
 assert a['rows'][:n]==b['rows'][:n] and all(len(r)==8 for r in ts)
 alts={x['index']:x['alternatives'] for x in b['uncertain'] if x['index']<8*n}
 var=[[tuple(map(byte,seq)) for seq in itertools.product(*(alts.get(i*8+j,[v]) for j,v in enumerate(t)))] for i,t in enumerate(ts)]
 assert len(alts)==8 and all(row[0]==tuple(map(byte,t)) for row,t in zip(var,ts))
 def addr(i):return [49,i+1] if 8*i<n0 else [50,i+1-n0//8]
 def evaluate(options,rule):
  cc=[];best={}
  # Optimize each row independently for each FIXED constant; never take a separate constant for each row.
  for c in range(256):
   vals=[];changes=[]
   for i,opts in enumerate(options):
    cand=[]
    for j,row in enumerate(opts):
     for glyphs,col,repl in candidates(row,c,rule):
      cand.append((glyphs,j, -1 if col is None else col, -1 if repl is None else repl))
    cost,j,col,repl=min(cand)
    vals.append(cost);rr=list(opts[j]);changes.append(dict(page_row=addr(i),baseline=' '.join(map(token,rr)),col=None if col<0 else col+1,replacement=None if repl<0 else token(repl)))
    if cost:rr[col]=repl
    assert k(rr,rule)==c and sum(x!=y for x,y in zip(''.join(map(token,rr)), ''.join(map(token,opts[j]))))==cost
   costs=[sum(x>0 for x in vals),sum(vals)]
   cc.append(costs)
   for idx,which in enumerate(('byte','glyph')):
    if which not in best or costs[idx]<best[which]['distance']:
     best[which]=dict(distance=costs[idx],one_constant=c,witness=changes)
  for idx,which in enumerate(('byte','glyph')):
   z=best[which]
   z['all_optimal_constants']=[i for i,ds in enumerate(cc) if ds[idx]==z['distance']]
   z['distance_histogram']=dict(sorted(Counter(x[idx] for x in cc).items()))
  return dict(best=best,all_constants=cc)
 # Validate the closed form by brute force over every one-byte replacement on each preferred training row,
 # all eight columns. The glyph bound is exact: no two-or-more-glyph repair can beat an existing 2-glyph repair.
 controls=0
 for opts in var:
  r=list(opts[0])
  for rule in ('sum','xor'):
   for i in range(8):
    ds={}
    for w in range(256):
     rr=r[:];rr[i]=w;c=k(rr,rule);assert c not in ds;ds[c]=w
    assert len(ds)==256
    for c,w in ds.items():
     if c==k(r,rule):assert w==r[i]
     else:assert candidates(r,c,rule)[i][2]==w
     controls+=1
 result={strat:{z:evaluate(opts,z) for z in ('sum','xor')} for strat,opts in [('preferred',[[r[0]] for r in var]),('free_IL_in_training',var)]}
 return dict(training_rows=n,training_cells=8*n,base60_digits_per_cell=2,train_variant_cells=sorted(alts),sha256_train_tokens=hashlib.sha256(('\n'.join(' '.join(v) for v in ts)+'\n').encode()).hexdigest(),checks=controls,results=result,notes='Distance only; no training constant chosen for prediction. page_row is one-based within the printed grid on that page, col is one-based. Witnesses are counterfactuals, not alternate readings of the page.')
if __name__=='__main__':Path(sys.argv[2]).write_bytes(gzip.compress((json.dumps(main(Path(sys.argv[1])),sort_keys=True,separators=(',',':'))+'\n').encode(),mtime=0))
