"""Rebuild source clips, point choices, mask ranking and scores."""
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 l89_texture import variance_points
from r107_boundary import select_points
from r108_replay import clip
from r99_compete import stack
R=Path(__file__).resolve().parents[1];O=R/'results/r108';S=R/'results/r105';p=json.loads((O/'protocol.json').read_text());d=json.loads((O/'results.json').read_text());selection=json.loads((O/'selection.json').read_text());assert sha(O/'protocol.json')==d['protocol_sha256']==selection['protocol_sha256'] and sha(O/'selection.json')==d['selection_sha256'] and sha(R/'research/r108_select.py')==selection['script_sha256'] and sha(R/'research/r108_replay.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
assert len(selection['records'])==8 and len(d['records'])==16
for n,(sel,r) in enumerate((s,v) for s in selection['records'] for v in d['records'] if v['index']==s['index']):
 assert r['side']==sel['side'] and r['index']==sel['index'] and sha(R/r['source'])==r['source_sha256']==sel['source_sha256'] and sha(S/r['r105_archive'])==r['r105_archive_sha256']==sel['r105_archive_sha256'] and sha(O/r['archive'])==r['archive_sha256'] and sha(O/r['panel'])==r['panel_sha256'];z=np.load(S/r['r105_archive']);orig=z['refs'][sel['ref_index']];refid=int(z['ids'][sel['ref_index']]);assert refid==sel['annotation_id'] and int(orig.sum())==sel['source_area'];im=Image.open(R/r['source']).convert('RGB');whole=np.zeros((512,512,3),np.uint8);whole[64:448]=np.asarray(im.resize((512,384),Image.Resampling.LANCZOS));clipped,partial,rect=clip(whole,orig,sel['side'],sel['cut']);assert int(partial.sum())==sel['visible_area'] and sel['visible_fraction']==sel['visible_area']/sel['source_area']
 if r['view']=='clipped':assert sha(O/r['clipped_image'])==r['clipped_image_sha256'] and np.array_equal(clipped,np.asarray(Image.open(O/r['clipped_image']).convert('RGB'))) and r['visible_fraction']==sel['visible_fraction'];rgb=clipped;target=partial
 else:assert r['view']=='complete' and r['visible_fraction']==1.;rgb=whole;target=orig;rect=[0,64,512,448]
 assert rect==r['content_rect'];a=np.load(O/r['archive']);assert np.array_equal(a['ref'],target) and int(a['refid'])==refid
 for method in ('variance','boundary'):
  shape=tuple(a[method+'_mask_shape']);m=np.unpackbits(a[method+'_mask_bits'])[:np.prod(shape)].reshape(shape).astype(bool);q=a[method+'_quality'];assert len(m)==len(q)==256;raw=[];i=0
  for ty,y in enumerate((0,85,171,256)):
   for tx,x in enumerate((0,85,171,256)):
    if method=='variance':pts=[(u,v,'variance',q) for u,v,q in variance_points(rgb[y:y+256,x:x+256])]
    else:pts=select_points(rgb[y:y+256,x:x+256],x,y,rect)
    for j,(px,py,kind,var) in enumerate(pts):
     assert [x,y,x+256,y+256]==a[method+'_crops'][i].tolist() and [x+px,y+py]==a[method+'_points'][i].tolist() and kind==a[method+'_kind'][i] and var==a[method+'_variance'][i] and a[method+'_ids'][i]==f't{ty*4+tx}-q{j:02d}';sm=m[i][y:y+256,x:x+256];outside=m[i].copy();outside[y:y+256,x:x+256]=False;assert not outside.any();e=300<=int(m[i].sum())<=50000 and float(q[i])>=.6;edge=bool(sm[0].any() or sm[-1].any() or sm[:,0].any() or sm[:,-1].any());assert e==a[method+'_eligible'][i] and edge==a[method+'_edge'][i];raw.append({'id':str(a[method+'_ids'][i]),'mask':m[i],'quality':float(q[i]),'eligible':e,'edge':edge,'point':[x+px,y+py],'kind':kind});i+=1
  if method=='variance' and r['view']=='complete':
   for suffix in ('mask_bits','mask_shape','ids','quality','eligible','crops','points','variance','edge'):assert np.array_equal(a[method+'_'+suffix],z[method+'_'+suffix])
  inside=lambda v:rect[0]<=v['point'][0]<rect[2] and rect[1]<=v['point'][1]<rect[3];eligible=sorted((v for v in raw if v['eligible']),key=lambda v:-v['quality']);kept,aliases=greedy_mask_nms(eligible,.8);deferred=[v for v in kept if inside(v)]+[v for v in kept if not inside(v)];s=r['stats'][method];assert len(eligible)==s['eligible_count'] and len(kept)==s['kept_count'] and aliases==s['aliases'] and [x['id'] for x in deferred]==s['ranking'] and sum(v['kind']=='boundary' for v in raw)==s['boundary_points'] and sum(bool(target[v['point'][1],v['point'][0]]) for v in raw)==s['on_reference'] and sum(not inside(v) for v in raw)==s['raw_padding']
  for stage,items in [('raw',raw),('eligible',eligible)]:
   for t in (.5,.75):assert match(np.stack([target]),[refid],stack(items),t)==r['scores'][method][stage][str(t)]
  for budget in (10,30,60,'all'):
   for t in (.5,.75):assert match(np.stack([target]),[refid],stack(deferred if budget=='all' else deferred[:budget]),t)==r['scores'][method]['ranked'][str(budget)][str(t)]
 print(sel['index'],sel['side'],r['view'],'verified',flush=True)
print('Verified source hashes, shared clip/point selection, fixed-query outputs, reused full-view baseline, ranking and scores; inference not rerun.')
