import hashlib,json
from pathlib import Path
import numpy as np
from diatom_pilot.fast_mask_nms import greedy_mask_nms
from l70_cellpose import match
R=Path(__file__).resolve().parents[1];O=R/'results/l73';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest();d=json.loads((O/'results.json').read_text());assert d['protocol_sha256']==sha(O/'protocol.json') and len(d['records'])==40;source={k:json.loads((R/'results'/k/'results.json').read_text())['records'] for k in ('l71','r84')}
for rec in d['records']:
 r=source[rec['source']][rec['index']];p=R/'results'/rec['source']/r['archive'];assert sha(p)==r['archive_sha256'];z=np.load(p);m=np.unpackbits(z['mask_bits'])[:int(np.prod(z['mask_shape']))].reshape(z['mask_shape']).astype(bool);raw=[{'id':str(k),'mask':v,'quality':float(q),'eligible':bool(e)} for k,v,q,e in zip(z['ids'],m,z['quality'],z['eligible'])];eligible=sorted((x for x in raw if x['eligible']),key=lambda x:-x['quality']);k8,a8=greedy_mask_nms(eligible,.8);k95,a95=greedy_mask_nms(eligible,.95);assert a8==rec['aliases08'] and a95==rec['aliases095'];ids8={x['id'] for x in k8};ranks={'nms08':k8,'nms095':k95,'eligible':eligible,'defer08':k8+[x for x in eligible if x['id'] not in ids8]}
 if rec['source']=='l71':refs=np.load(R/'results/r78'/r['ref_archive'])['refs_visible'];ids=list(range(len(refs)))
 else:refs=z['refs'];ids=z['annotation_ids'].tolist()
 assert match(refs,ids,np.stack([x['mask'] for x in raw]),.5)['matched']==rec['raw_oracle_all']
 for name,items in ranks.items():
  assert [x['id'] for x in items]==rec['rankings'][name]
  for b in ('10','30','60','all'):
   selected=items if b=='all' else items[:int(b)];masks=np.stack([x['mask'] for x in selected]) if selected else np.zeros((0,512,512),bool);assert match(refs,ids,masks,.5)['matched']==rec['scores'][name][b]
print('Verified raw masks, greedy NMS links, candidate deferrals and all score counts across 40 fields.')
