"""python -B fit_330.py EVIDENCE OUTPUT.json.gz. Uses only coordinate boxes and S329 margins."""
from pathlib import Path
from collections import Counter,defaultdict
from statistics import median
import json,gzip,sys,itertools,hashlib
H='a590966c299a942b031069cac72495f921be979f1b53177eb8b0fd793a5b7a9a'
def load(path):return json.loads(gzip.decompress(path.read_bytes()))
def desc(arr):
 arr=sorted(arr)
 return [min(arr),arr[(len(arr)-1)//4],median(arr),arr[(3*(len(arr)-1))//4],max(arr)]
def calc(d,bands):
 raw=d/'grid_geometry_245.json.gz'
 assert hashlib.sha256(raw.read_bytes()).hexdigest()==H
 grouper=defaultdict(dict)
 for cell in load(raw):
  p,r,c=(cell[k] for k in ('page','row','col'));left,_,right,_=cell['bbox']
  assert right>left and c not in grouper[p,r]
  grouper[p,r][c]=(left,right)
 rows={k:[z[j] for j in range(1,9)] for k,z in sorted(grouper.items())}
 assert all(len(v)==8 for v in grouper.values()) and Counter(p for p,r in rows)=={49:10,50:13,51:9}
 result=dict(bands=bands,geometry_sha256=H,summaries={},donors={},rows=[],stats_order='min, lower quartile (indexed), median, upper quartile (indexed), max; pixel intervals left-inclusive/right-exclusive')
 for p in (49,50,51):
  rr=[v for (pg,r),v in rows.items() if pg!=p]
  widths=[b-a for v in rr for a,b in v];gaps=[v[i][0]-v[i-1][1] for v in rr for i in range(1,8)]
  assert min(gaps)>0
  real=Counter(v[i][1]-v[i-1][1] for v in rr for i in range(1,8))
  cross=Counter(w+g for w,g in itertools.product(widths,gaps))
  result['donors'][p]={'n_widths':len(widths),'n_gaps':len(gaps),'width_px':desc(widths),'gap_px':desc(gaps),'increment_px_cross':desc(cross.elements()),'increment_px_paired':desc(real.elements()),'cross_hist':sorted(cross.items()),'paired_hist':sorted(real.items())}
  for (pg,r),v in rows.items():
   if pg!=p:continue
   l,R=v[0][0],v[-1][1];span=R-l
   obj=dict(page=p,row=r,ink=[l,R],span=span,ink_center=(l+R)/2,metrics={})
   for name,(L,U) in bands.items():
    assert L<U
    base0=(L<=l and R<=U);base1=(span<=U-L)
    # Both extrema are attainable in each finite donor collection; count all mixed cases separately.
    configs=dict(fixed=(base0,U-R),recentered=(base1,U-L-span))
    mids={'center_page':2400,'center_observed_row':l+R}
    for mode,h in mids.items():
     maxspan=min(U-L,h-2*L+1,2*U-h+1)
     configs[mode]=(span<=maxspan,maxspan-span)
    for mode,(can8,room) in configs.items():
     u={'eight_fits':can8,'spare':room}
     for label,h in (('cross',cross),('paired',real)):
      count=sum(n for a,n in h.items() if a<=room);total=sum(h.values())
      status=('invalid' if not can8 else 'no' if count==0 else 'yes' if count==total else 'depends')
      u[label]=[status,count if can8 else None,total]
      # Independent check: fit a ninth box in place, or explicitly place whole configuration
      # at each of the two adjacent integer centers (for a center lying between pixels).
      for a in set(h):
       full=span+a;w=U-L;L9=L+(w-full)//2
       alt=(L<=l and R+a<=U) if mode=='fixed' else (L<=L9 and L9+full<=U)
       if mode in mids:
        h=mids[mode];floor=(h-full)//2
        alt=any(L<=x and x+full<=U and abs(2*x+full-h)<=1 for x in (floor,floor+1))
       assert alt==(can8 and a<=room)
     obj['metrics'].setdefault(name,{})[mode]=u
   result['rows'].append(obj)
 result['rows'].sort(key=lambda x:(x['page'],x['row']))
 for tag in bands:
  cond={}
  for mode in ('fixed','recentered','center_page','center_observed_row'):
   for panel in ('all',49,50,51):
    q=[r for r in result['rows'] if panel=='all' or r['page']==panel];ms=[r['metrics'][tag][mode] for r in q]
    z=dict(n=len(q),baseline=sum(m['eight_fits'] for m in ms),spare_range=desc(m['spare'] for m in ms))
    for k in ('cross','paired'):
     z[k]=dict(Counter(m[k][0] for m in ms))
    cond.setdefault(mode,{})[str(panel)]=z
  result['summaries'][tag]=cond
 result['actual_spans']=desc(v[-1][1]-v[0][0] for v in rows.values())
 result['actual_centers']=desc((v[-1][1]+v[0][0])/2 for v in rows.values())
 return result
def main(d,path):
 m=load(d/'margins_329_results.json.gz');bands=m['bands']
 res=calc(d,bands);res['margins_sha256']=hashlib.sha256((d/'margins_329_results.json.gz').read_bytes()).hexdigest()
 path.write_bytes(gzip.compress((json.dumps(res,sort_keys=True,separators=(',',':'))+'\n').encode(),mtime=0))
if __name__=='__main__':main(Path(sys.argv[1]),Path(sys.argv[2]))
