"""Rebuild matched images, grid filtering, points, scores from saved outputs."""
import json
from pathlib import Path
import numpy as np
from PIL import Image
from diatom_pilot.fast_mask_nms import greedy_mask_nms
from l70_cellpose import match
from l86_oracle import sha
from r99_compete import plan,stack,interleave
R=Path(__file__).resolve().parents[1];O=R/'results/r100';S=R/'results/l75';p=json.loads((O/'protocol.json').read_text());d=json.loads((O/'results.json').read_text());assert sha(O/'protocol.json')==d['protocol_sha256'] and sha(R/'research/r100_clean.py')==d['script_sha256'] and sha('/tmp/mobile_sam.pt')==d['checkpoint_sha256']
for f,h in p['inputs'].items():assert sha(R/f)==h
old=json.loads((S/'results.json').read_text())['records'];assert len(d['records'])==len(old)==16
for r,prior in zip(d['records'],old):
 assert (r['pair'],r['condition'],r['split'])==(prior['pair'],prior['condition'],prior['split']) and sha(S/r['source_image'])==r['source_image_sha256']==prior['image_sha256'] and sha(S/r['source_archive'])==r['source_archive_sha256']==prior['archive_sha256'] and sha(O/r['clean_image'])==r['clean_image_sha256'] and sha(O/r['archive'])==r['archive_sha256'] and sha(O/r['panel'])==r['panel_sha256'];z=np.load(S/r['source_archive']);a=np.load(O/r['archive']);refs=z['refs_visible'];full=z['refs_full_in_frame'];assert np.array_equal(refs,a['refs']) and np.array_equal(full,a['full']);busy=np.asarray(Image.open(S/r['source_image']).convert('RGB'));union=np.any(full,axis=0);median=np.median(busy[~union],axis=0).astype('uint8');image=busy.copy();image[~union]=median;assert median.tolist()==r['median_rgb'] and np.array_equal(image,np.asarray(Image.open(O/r['clean_image']).convert('RGB')));shape=tuple(a['raw_shape']);mm=np.unpackbits(a['raw_bits'])[:np.prod(shape)].reshape(shape).astype(bool);q=a['raw_quality'];raw=[{'id':k,'mask':m,'quality':float(v),'eligible':300<=int(m.sum())<=50000 and float(v)>=.6} for k,m,v in zip(a['raw_ids'].tolist(),mm,q)];assert len(raw)==len(z['points'])==r['raw_count']==256 and [x['id'] for x in raw]==[f'{x}-{y}' for x,y in z['points']] and [x['eligible'] for x in raw]==a['raw_eligible'].tolist();eligible=sorted([x for x in raw if x['eligible']],key=lambda x:-x['quality']);kept,aliases=greedy_mask_nms(eligible,.8);assert len(eligible)==r['eligible_count'] and len(kept)==r['kept_count'] and aliases==r['aliases'];plans,abstain=plan(kept);assert plans==r['plans'] and abstain==r['abstained_anchors'];directed=[{'positive':x['a_point'],'negative':x['b_point'],'source':x['a'],'other':x['b']} for x in plans]+[{'positive':x['b_point'],'negative':x['a_point'],'source':x['b'],'other':x['a']} for x in plans];assert directed==r['directed'] and len(directed)==r['added_queries_per_arm'];categories={'different':0,'same':0,'one':0,'neither':0}
 for v in directed:
  def at(pt):
   x,y=pt
   if refs[0,y,x]:return 0
   if refs[1,y,x]:return 1
   return None
  a1=at(v['positive']);b1=at(v['negative']);c=('same' if a1==b1 else 'different') if a1 is not None and b1 is not None else 'neither' if a1 is None and b1 is None else 'one';categories[c]+=1
 assert categories==r['point_categories'];streams={'baseline':kept};stages={'raw_grid':raw,'eligible_grid':eligible};shape=tuple(a['added_shape'])
 for k in ('positive','negative'):
  m=np.unpackbits(a[k+'_bits'])[:np.prod(shape)].reshape(shape).astype(bool);q=a[k+'_quality'];assert len(m)==len(q)==len(directed);add=[{'id':f'{k}:{i}','mask':x,'quality':float(v)} for i,(x,v) in enumerate(zip(m,q)) if 300<=int(x.sum())<=50000 and float(v)>=.6];assert len(add)==r['added_eligible'][k];streams[k]=interleave(kept,add);stages[k]=raw+[{'mask':v} for v in m]
 ids=prior['included_visible_ids']
 for name,items in streams.items():
  assert [x['id'] for x in items]==r['rankings'][name]
  for n in (10,30,60,'all'):
   for t in (.5,.75):assert match(refs[ids],ids,stack(items if n=='all' else items[:n]),t)==r['scores'][name][str(n)][str(t)]
 for name,items in stages.items():
  for t in (.5,.75):assert match(refs[ids],ids,stack(items),t)==r['stage_scores'][name][str(t)]
 print(r['pair'],r['condition'],'verified',flush=True)
print('Verified all clean image pixels, source hashes, candidate filtering, shared planner, rankings, stages and scores; no model inference rerun.')
