"""Post-hoc stage-level candidate and per-target availability diagnostics."""
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/r88';S=R/'results/l75';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 rows=json.loads((S/'results.json').read_text())['records'];out=[]
 for r in rows:
  p=S/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),'point':pt.tolist()} for k,v,q,e,pt in zip(z['ids'],m,z['quality'],z['eligible'],z['points'])];eligible=sorted((v for v in raw if v['eligible']),key=lambda v:-v['quality']);kept,aliases=greedy_mask_nms(eligible,.8);assert aliases==r['aliases'] and [v['id'] for v in kept]==r['rankings']['quality'];ref=z['refs_visible'];ids=r['included_visible_ids'];stages={'raw':raw,'eligible':eligible,'nms08':kept,'top30':kept[:30]};scores={};individual={}
  for name,items in stages.items():
   arr=np.stack([v['mask'] for v in items]) if items else np.zeros((0,512,512),bool);scores[name]=match(ref[ids],ids,arr,.5)
   for p in scores[name]['assignments']:p['candidate_id']=items[p['candidate_index']]['id']
   per=[]
   for i in ids:
    best=None
    for x in items:
     inter=int((ref[i]&x['mask']).sum());union=int((ref[i]|x['mask']).sum());iou=inter/union if union else 0
     if best is None or iou>best['iou']:best={'candidate_id':x['id'],'iou':iou,'quality':x['quality'],'point':x['point'],'eligible':x['eligible']}
    per.append({'reference_id':i,'best':best})
   individual[name]=per
  out.append({'pair':r['pair'],'split':r['split'],'condition':r['condition'],'reference_count':len(ids),'scores':scores,'individual_best':individual,'note':'Individual best masks may be shared by targets and are not a valid multi-instance score; stage one-to-one scores are separate.'});print(r['pair'],r['condition'],*[scores[k]['matched'] for k in stages],flush=True)
 (O/'diagnostic.json').write_text(json.dumps({'protocol_sha256':sha(O/'protocol.json'),'records':out},indent=2)+'\n')
if __name__=='__main__':main()
