"""Predeclared filter controls and reference-assisted failure 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/r86';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 protocol=json.loads((O/'protocol.json').read_text());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']];rows=[]
 for i,(tag,r) in enumerate(sources):
  p=R/'results'/tag/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':a,'quality':float(q),'area':int(a.sum())} for k,a,q in zip(z['ids'],m,z['quality'])]
  if tag=='l71':refs=np.load(R/'results/r78'/r['ref_archive'])['refs_visible'];ids=list(range(len(refs)));group=r['group']+' '+str(r.get('condition') or '')
  else:refs=z['refs'];ids=z['annotation_ids'].tolist();group='new source '+r['species_from_folder']
  policies={}
  for name,f in protocol['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,aliases=greedy_mask_nms(eligible,.8);scores={}
   for b in (10,30,60,'all'):
    chosen=kept if b=='all' else kept[:b];arr=np.stack([x['mask'] for x in chosen]) if chosen else np.zeros((0,512,512),bool);scores[str(b)]=match(refs,ids,arr,.5)['matched']
   policies[name]={'eligible':len(eligible),'kept':len(kept),'ranking':[x['id'] for x in kept],'aliases':aliases,'scores':scores}
  assert policies['baseline']['ranking']==r['policies']['256']['ranking'];oracle=match(refs,ids,np.stack([x['mask'] for x in raw]),.5);explanations=[]
  if oracle['matched']>policies['baseline']['scores']['all']:
   lookup={x['id']:x for x in raw};
   for a in oracle['assignments']:
    item=raw[a['candidate_index']];explanations.append({'annotation_id':a['annotation_id'],'candidate_id':item['id'],'iou':a['iou'],'area':item['area'],'quality':item['quality'],'eligible_baseline':300<=item['area']<=50000 and item['quality']>=.6})
  rows.append({'source':tag,'index':r['index'],'group':group,'references':len(refs),'archive_sha256':r['archive_sha256'],'oracle_matches':oracle['matched'],'oracle_assignments_if_gap':explanations,'policies':policies});print(i+1,tag,group,'all',*[policies[k]['scores']['all'] for k in protocol['filters']],flush=True)
 (O/'results.json').write_text(json.dumps({'format':'r86-filters-v1','protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'records':rows},indent=2)+'\n')
if __name__=='__main__':main()
