"""Replay published source IDs with no coordinate collapsing."""
import json,hashlib
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/r83';P=R/'results/l70';rs=json.loads((O/'results.json').read_text())['records'];cp={x['filename']:x for x in json.loads((P/'results.json').read_text())['records']};out=[]
for row in rs:
 z=np.load(O/row['archive']);m=np.unpackbits(z['mask_bits'])[:int(np.prod(z['mask_shape']))].reshape(z['mask_shape']).astype(bool);items=[{'id':str(i),'mask':x,'quality':float(q),'eligible':bool(e)} for i,x,q,e in zip(z['ids'],m,z['quality'],z['eligible'])];a=np.load(P/cp[row['filename']]['archive']);refs=a['refs'];ids=a['annotation_ids'].tolist();scores={}
 for n in ('64','256'):
  eligible=sorted((x for x in items[:int(n)] if x['eligible']),key=lambda x:-x['quality']);kept,_=greedy_mask_nms(eligible,.8);scores[n]={}
  for budget in ('10','30','60','all'):
   arr=kept if budget=='all' else kept[:int(budget)];masks=np.stack([x['mask'] for x in arr]) if arr else np.zeros((0,540,540),bool);scores[n][budget]=match(refs,ids,masks,.5)['matched']
 out.append({'filename':row['filename'],'published_reference_count':len(ids),'scores':scores})
(O/'published-sensitivity.json').write_text(json.dumps({'source_results_sha256':hashlib.sha256((O/'results.json').read_bytes()).hexdigest(),'records':out},indent=2)+'\n');print('published',sum(x['published_reference_count'] for x in out),{n:sum(x['scores'][n]['all'] for x in out) for n in ('64','256')})
