"""Run the two frozen checks. python -B grid_rows_325.py EVIDENCE OUT_DIR (standard library)."""
from pathlib import Path
from collections import defaultdict,Counter
from functools import reduce
from operator import xor
import argparse,hashlib,json,gzip,itertools
ALPH='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwx'
PINS={'grid_rows_next_324.txt':'d714b69c358f25f803d45f42fe3425e4ccb569fbad1110655ca8ffe8820b48b3',
      'grid_read_a_254.json':'d44599d3dad631240eea2f1a808f7a6b29952a1fc4ca86a6c896eff676d12dd3',
      'grid_read_b_254.json':'41c80e2ad5f74008d8ab0ecd29c6cc27b26983cecf7df5ed2119bb341d24c681',
      'grid_cells_254.json':'a6fd639ff34993c4a55b9cebe11386f5de7e7e154ed456d98402bfa9b3617040'}
def load(d,name):
 raw=(d/name).read_bytes();assert hashlib.sha256(raw).hexdigest()==PINS[name]
 return json.loads(raw) if name.endswith('.json') else raw
def val(t):
 assert len(t)==2 and t[0] in '01234' and t[1] in ALPH
 b=ALPH.index(t[0])*60+ALPH.index(t[1]);assert 0<=b<=255;return b
def masks(v):return (sum(v)%256,reduce(xor,v,0))
def predict(tag,c,v):return (sum(v)+c)%256 if tag=='sum' else reduce(xor,v,c)
def main(d):
 load(d,'grid_rows_next_324.txt')
 cells=load(d,'grid_cells_254.json')['cells'];readers=[load(d,f'grid_read_{x}_254.json')['rows'] for x in 'ab']
 addrs=[(v['page'],v['row'],v['col']) for v in cells]
 totals=Counter(p for p,_,_ in addrs);assert totals=={49:80,50:104,51:72}
 expected=[(p,row,col) for p,nt in sorted(totals.items()) for row in range(1,nt//8+1) for col in range(1,9)]
 assert addrs==expected and all(len(r)==32 for r in readers)
 # Structure is public; all numeric analyses below receive only the training rows.
 rows=[];masked=[]
 for i in range(32):
  cohort=cells[8*i:8*i+8];p,r,_=addrs[8*i]
  if p==51:
   masked.append((p,r));continue
  words=readers[0][i].split();assert words==readers[1][i].split()
  assert words==[c['a'] for c in cohort]==[c['b'] for c in cohort]==[c['archive'] for c in cohort]
  v=list(map(val,words));assert v==[c['byte'] for c in cohort]
  su,xo=masks(v[:7]);rows.append(dict(page=p,row=r,words=words,bytes=v,sum_first_seven_mod256=su,xor_first_seven=xo,required_sum=(v[7]-su)%256,required_xor=xo^v[7]))
 assert len(rows)==23 and len(masked)==9
 def stage2(tag,c):
  # Called only if every training row fits. All predictions are fixed before scoring.
  preds=[predict(tag,c,list(map(val,readers[0][23+i].split()[:7]))) for i in range(9)]
  return [dict(page=p,row=r,predicted=pred,actual=val(readers[0][23+i].split()[7])) for i,((p,r),pred) in enumerate(zip(masked,preds))]
 results={};calls=0
 for tag in ('sum','xor'):
  fits={c:[i+1 for i,x in enumerate(rows) if predict(tag,c,x['bytes'][:7])==x['bytes'][7]] for c in range(256)}
  for c,m in fits.items():assert m==[i+1 for i,r in enumerate(rows) if r['required_'+tag]==c]
  passing=[c for c,m in fits.items() if len(m)==len(rows)]
  pred=[]
  for c in passing:pred.append(dict(constant=c,rows=stage2(tag,c)));calls+=1
  results[tag]=dict(all_constants_training_matches=fits,perfect_constants=passing,distinct_constants_demanded=len({x['required_'+tag] for x in rows}),holdout=pred)
 out=dict(training_rows=rows,row_counts={p:nt//8 for p,nt in totals.items()},masked_coordinates=masked,holdout_scoring_calls=calls,source_sha256=PINS,results=results,units='Base-60 glyph pairs decoded to unsigned bytes; page/row/column one-based physical row/column on zero-based LP2 pages. Match row indices 1..23 across the first two pages.')
 return out
if __name__=='__main__':
 ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('evidence',type=Path);ap.add_argument('outputdir',type=Path);a=ap.parse_args()
 z=main(a.evidence);a.outputdir.mkdir(exist_ok=True,parents=True)
 (a.outputdir/'grid_rows_325_results.json.gz').write_bytes(gzip.compress((json.dumps(z,sort_keys=True,separators=(',',':'))+'\n').encode(),mtime=0))
