"""python -B column_variants_337.py EVIDENCE OUTPUT.json.gz ; Python 3.10+, stdlib.
Independent check of existing fixed predictor. Only the 23 eligible lines get decoded.
"""
import sys,json,gzip,itertools,math,hashlib
from fractions import Fraction
from collections import Counter
from pathlib import Path
D='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwx'
def value(t):
 v=60*D.index(t[0])+D.index(t[1]);assert len(t)==2 and v<256;return v
def main(d):
 def load(x):return json.loads((d/x).read_bytes())
 a=load('grid_read_a_254.json');b=load('grid_read_b_254.json')
 W=load('grid_witnesses_249.json');assert W['per_page']==[80,104,72]
 assert [hashlib.sha256((d/p).read_bytes()).hexdigest() for p in ('grid_read_a_254.json','grid_read_b_254.json')]==W['read_hashes']
 n=sum(W['per_page'][:2]);s=n//8;first=W['per_page'][0]
 toks=' '.join(a['rows'][:s]).split();assert toks==' '.join(b['rows'][:s]).split() and len(toks)==n
 edits={it['index']:it['alternatives'] for it in b['uncertain'] if it['index']<n}
 assert sorted(edits)==[i for i,t in enumerate(toks) if t[1] in 'Il']
 slots=[];base=bytes(map(value,toks))
 for i,options in sorted(edits.items()):
  assert len(options)==2 and options[0]==toks[i] and {v[1] for v in options}=={'l','I'} and len({v[0] for v in options})==1
  vals=list(map(value,options));bins=[v//64 for v in vals]
  slots.append(dict(index=i,page=49+int(i>=first),row=(i if i<first else i-first)//8+1,col=i%8+1,source=options,values=vals,bins=bins,crosses=bins[0]!=bins[1]))
 categorical=Counter();unique=set()
 for pick in itertools.product((0,1),repeat=len(slots)):
  bs=bytearray(base)
  for row,k in zip(slots,pick):bs[row['index']]=row['values'][k]
  unique.add(bytes(bs));categorical[bytes(v//64 for v in bs)]+=1
 def evaluate(x):
  tr=x[:first];te=x[first:]
  C=[[tr[c::8].count(j) for j in range(4)] for c in range(8)]
  P=[tr.count(j) for j in range(4)]
  numden=[[Fraction((2*C[c][j]+1)*(2*first+4),(2*(first//8)+4)*(2*P[j]+1)) for j in range(4)] for c in range(8)]
  raw=[];columnparts=[]
  for h in range(8):
   cr=[math.prod(numden[(c+h)%8][v] for v in te[c::8]) for c in range(8)]
   raw.append(math.prod(cr));columnparts.append([math.log2(v) for v in cr])
  z=raw[0];rank=1+sum(r>z for r in raw[1:])
  return dict(numerical_phase_convention='test column j uses training column (j+h) mod 8, j=0..7',train_by_column=C,pool=P,phase_gains_bits=[math.log2(f) for f in raw],fixed_gain_per_test_column=columnparts[0],fixed_rank=rank,phase_ties=sum(f==z for f in raw),fixed_positive=bool(z>1),fixed_unique_best=all(z>f for f in raw[1:]),test_by_column=[[te[c::8].count(j) for j in range(4)] for c in range(8)])
 results=[dict(categorical_sha256=hashlib.sha256(x).hexdigest(),mask_multiplicity=m,**evaluate(x)) for x,m in categorical.items()]
 assert len(unique)==256 and sum(categorical.values())==256
 typography={}
 for page,segment in ((49,base[:first]),(50,base[first:])):
  cnt=Counter((min(v//60,3),v//64) for v in segment)
  typography[page]=dict(total=len(segment),same=sum(n for (a,b),n in cnt.items() if a==b),different_by_value=[v for v in segment if min(v//60,3)!=v//64])
 return dict(typography=typography,slots=slots,distinct_byte_readings=len(unique),distinct_category_matrices=len(categorical),cells_total=n,scores=results,note='No page 51 row values passed to the analysis. Existing permutation result is inherited if categories are unchanged; no p-value search over masks.')
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))
