"""Rebuild image-guided points, crop geometry, filtering and all saved 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 r99_compete import stack
R=Path(__file__).resolve().parents[1];O=R/'results/l89/clean';C=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/l89_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((C/'results.json').read_text())['records'];source={(x['pair'],x['condition']):x for x in json.loads((S/'results.json').read_text())['records']};assert len(old)==len(d['records'])==16
for r,orig in zip(d['records'],old):
 key=(r['pair'],r['condition']);assert key==(orig['pair'],orig['condition']) and r['split']==orig['split'] and sha(C/r['image'])==r['image_sha256']==orig['clean_image_sha256'] and sha(C/r['reference_archive'])==r['reference_archive_sha256']==orig['archive_sha256'] and sha(O/r['archive'])==r['archive_sha256'] and sha(O/r['panel'])==r['panel_sha256'];img=np.asarray(Image.open(C/r['image']).convert('RGB'));z=np.load(O/r['archive']);refs=np.load(C/r['reference_archive'])['refs'];assert np.array_equal(z['refs'],refs);ids=source[key]['included_visible_ids']
 for method in ('uniform','variance'):
  shape=tuple(z[method+'_mask_shape']);m=np.unpackbits(z[method+'_mask_bits'])[:np.prod(shape)].reshape(shape).astype(bool);q=z[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)):
    pts=[(a,b,0.) for b in (32,96,160,224) for a in (32,96,160,224)] if method=='uniform' else variance_points(img[y:y+256,x:x+256])
    for j,(px,py,var) in enumerate(pts):
     assert [x,y,x+256,y+256]==z[method+'_crops'][i].tolist() and [x+px,y+py]==z[method+'_points'][i].tolist() and var==z[method+'_variance'][i] and z[method+'_ids'][i]==f't{ty*4+tx}-q{j:02d}';small=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(small[0].any() or small[-1].any() or small[:,0].any() or small[:,-1].any());assert e==z[method+'_eligible'][i] and edge==z[method+'_edge'][i];raw.append({'id':str(z[method+'_ids'][i]),'mask':m[i],'quality':float(q[i]),'eligible':e,'edge':edge,'point':[x+px,y+py]});i+=1
  eligible=sorted((x for x in raw if x['eligible']),key=lambda x:-x['quality']);kept,aliases=greedy_mask_nms(eligible,.8);s=r['stats'][method];assert len(eligible)==s['eligible'] and len(kept)==s['kept'] and aliases==s['aliases'] and [x['id'] for x in kept]==s['ranking'] and sum(x['edge'] for x in raw)==s['edge_raw'] and sum(x['edge'] for x in kept)==s['edge_kept'] and sum(bool(refs[:,v['point'][1],v['point'][0]].any()) for v in raw)==s['on_inserted_support']
  for stage,items in [('raw',raw),('eligible',eligible)]:
   for t in (.5,.75):assert match(refs[ids],ids,stack(items),t)==r['scores'][method][stage][str(t)]
  for n in (10,30,60,'all'):
   for t in (.5,.75):assert match(refs[ids],ids,stack(kept if n=='all' else kept[:n]),t)==r['scores'][method]['ranked'][str(n)][str(t)]
 print(key,'verified',flush=True)
print('Verified all source hashes, reference equality, image-selected and fixed points, bounds, candidate filtering, rankings and scores. Point selector, NMS and matcher shared; inference not rerun.')
