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/l74';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;sources={k:json.loads((R/'results'/k/'results.json').read_text())['records'] for k in ('l71','r84')};bc=np.array([i.bit_count() for i in range(256)],np.uint8)
for rec in d['records']:
 r=sources[rec['source']][rec['index']];p=R/'results'/rec['source']/r['archive'];assert sha(p)==rec['archive_sha256'];z=np.load(p);m=np.unpackbits(z['mask_bits'])[:int(np.prod(z['mask_shape']))].reshape(z['mask_shape']).astype(bool);items=[{'id':str(k),'mask':v,'quality':float(q),'area':int(v.sum())} for k,v,q in zip(z['ids'],m,z['quality'])];eligible=sorted((x for x in items if 300<=x['area']<=50000 and x['quality']>=.45),key=lambda x:-x['quality']);packs=[np.packbits(x['mask'].ravel()) for x in eligible];links={}
 for j,x in enumerate(eligible):
  if x['quality']>=.6:continue
  ls=[]
  for k,y in enumerate(eligible):
   if k==j or min(x['area'],y['area'])/max(x['area'],y['area'])<.5:continue
   inter=int(bc[np.bitwise_and(packs[j],packs[k])].sum());iou=inter/(x['area']+y['area']-inter)
   if iou>=.5:ls.append({'id':y['id'],'iou':iou,'quality':y['quality']})
  links[x['id']]=ls
 assert links==rec['support_links']
 flags={'baseline':lambda x:x['quality']>=.6,'low_all':lambda x:True,'repeat_support':lambda x:x['quality']>=.6 or bool(links[x['id']]),'high_support':lambda x:x['quality']>=.6 or any(v['quality']>=.6 for v in links[x['id']])}
 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,flag in flags.items():
  admitted=[x for x in eligible if flag(x)];kept,aliases=greedy_mask_nms(admitted,.8);res=rec['policies'][name];assert len(admitted)==res['admitted'] and len(kept)==res['kept'] and [x['id'] for x in kept]==res['ranking'] and aliases==res['aliases']
  for b in ('10','30','60','all'):
   selected=kept if b=='all' else kept[:int(b)];arr=np.stack([x['mask'] for x in selected]) if selected else np.zeros((0,512,512),bool);assert match(refs,ids,arr,.5)['matched']==res['scores'][b]
print('Verified support links, admission, suppression and budgeted scores on all 40 fields.')
