"""Audit same-stream suppression against archived raw dense-grid masks."""
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/l73';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 sources=[('l71',x) for x in json.loads((R/'results/l71/results.json').read_text())['records']]+[('r84',x) for x in json.loads((R/'results/r84/results.json').read_text())['records']];results=[]
 for i,(tag,r) in enumerate(sources):
  p=R/'results'/tag/r['archive'];assert sha(p)==r['archive_sha256'];z=np.load(p);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),'eligible':bool(e)} for k,m,q,e in zip(z['ids'],masks,z['quality'],z['eligible'])];eligible=sorted((x for x in raw if x['eligible']),key=lambda x:-x['quality']);kept08,alias08=greedy_mask_nms(eligible,.8);kept095,alias095=greedy_mask_nms(eligible,.95);ids08={x['id'] for x in kept08};deferred=kept08+[x for x in eligible if x['id'] not in ids08];ranks={'nms08':kept08,'defer08':deferred,'nms095':kept095,'eligible':eligible}
  assert [x['id'] for x in kept08]==r['policies']['256']['ranking'] and len(deferred)==len(eligible)
  if tag=='l71':ref=np.load(R/'results/r78'/r['ref_archive'])['refs_visible'];ids=list(range(len(ref)));group=r['group']+' '+str(r.get('condition') or '')
  else:ref=z['refs'];ids=z['annotation_ids'].tolist();group='new source '+r['species_from_folder']
  rawm=np.stack([x['mask'] for x in raw]);oracle=match(ref,ids,rawm,.5)['matched'];scores={}
  for name,items in ranks.items():
   scores[name]={}
   for b in (10,30,60,'all'):
    chosen=items if b=='all' else items[:b];ms=np.stack([x['mask'] for x in chosen]) if chosen else np.zeros((0,512,512),bool);scores[name][str(b)]=match(ref,ids,ms,.5)['matched']
  assert scores['eligible']['all']==scores['defer08']['all']<=oracle
  item={'source':tag,'index':r['index'],'group':group,'references':len(ref),'raw_oracle_all':oracle,'eligible_count':len(eligible),'nms08_count':len(kept08),'nms095_count':len(kept095),'rankings':{k:[x['id'] for x in v] for k,v in ranks.items()},'aliases08':alias08,'aliases095':alias095,'scores':scores};results.append(item);print(i+1,group,len(ref),'all 08/95/eligible/raw',*[scores[k]['all'] for k in ('nms08','nms095','eligible')],oracle,flush=True)
 (O/'results.json').write_text(json.dumps({'format':'l73-nms-audit-v1','protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'records':results},indent=2)+'\n')
if __name__=='__main__':main()
