import json,hashlib
from pathlib import Path
import numpy as np
from l70_cellpose import match
from diatom_pilot.fast_mask_nms import greedy_mask_nms
R=Path(__file__).resolve().parents[1];O=R/'results/r86';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest();d=json.loads((O/'results.json').read_text());proto=json.loads((O/'protocol.json').read_text());assert d['protocol_sha256']==sha(O/'protocol.json') and len(d['records'])==40;sources={k:json.loads((R/'results'/k/'results.json').read_text())['records'] for k in ('l71','r84')}
for rec in d['records']:
 r=sources[rec['source']][rec['index']];path=R/'results'/rec['source']/r['archive'];assert sha(path)==rec['archive_sha256'];z=np.load(path);masks=np.unpackbits(z['mask_bits'])[:int(np.prod(z['mask_shape']))].reshape(z['mask_shape']).astype(bool);raw=[{'id':str(k),'mask':m,'quality':float(q),'area':int(m.sum())} for k,m,q in zip(z['ids'],masks,z['quality'])]
 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()
 for name,f in proto['filters'].items():
  eligible=sorted((x for x in raw if f['min_area']<=x['area']<=f['max_area'] and x['quality']>=f['min_quality']),key=lambda x:-x['quality']);kept,alias=greedy_mask_nms(eligible,.8);p=rec['policies'][name];assert len(eligible)==p['eligible'] and len(kept)==p['kept'] and [x['id'] for x in kept]==p['ranking'] and alias==p['aliases']
  for b in ('10','30','60','all'):
   selected=kept if b=='all' else kept[:int(b)];m=np.stack([x['mask'] for x in selected]) if selected else np.zeros((0,512,512),bool);assert match(refs,ids,m,.5)['matched']==p['scores'][b]
print('Verified filter eligibility, retained ranks, aliases and budget scores across all 40 development fields.')
