"""Frozen cross-model candidate deferral on R79 freshwater fields."""
import hashlib,json
from pathlib import Path
import numpy as np
from PIL import Image,ImageDraw
from diatom_pilot.demote_alternatives import defer_cross_model
import r79_combine as base
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/l69';SRC=ROOT/'results/r79';CP=ROOT/'results/r78'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def panel(image,refs,ranks,path):
 out=Image.new('RGB',(1250,295),'white');draw=ImageDraw.Draw(out)
 for k,(name,masks) in enumerate([('Source references',refs),('SAM first: top 10',[c['mask'] for c in ranks['sam_first'][:10]]),('Defer at 0.8: top 10',[c['mask'] for c in ranks['sam_first_08'][:10]]),('Defer at 0.95: top 10',[c['mask'] for c in ranks['sam_first_095'][:10]]),('Deferred at 0.8',[c['mask'] for c in ranks['deferred_08']])]):
  tile=Image.fromarray(image).convert('RGBA')
  for i,m in enumerate(masks):
   lay=Image.new('RGBA',tile.size,['#008a70','#cd603b','#7357b4','#c29d2a'][i%4]);lay.putalpha(Image.fromarray(m.astype('uint8')*100));tile=Image.alpha_composite(tile,lay)
  out.paste(tile.convert('RGB').resize((245,245)),(k*250+2,38));draw.text((k*250+3,7),name,fill='#203a38')
 out.save(path)
def main():
 p=json.loads((OUT/'protocol.json').read_text())
 for x in p['inputs']:
  if sha(x['path'])!=x['sha256']:raise ValueError('Changed input: '+x['path'])
 prior=json.loads((SRC/'results.json').read_text());cp={r['image_id']:r for r in json.loads((CP/'results.json').read_text())['records'] if r['group']=='menne'};records=[]
 for r in prior['records']:
  c=cp[r['image_id']];a=np.load(SRC/r['sam_archive'],allow_pickle=False);shape=tuple(a['mask_shape']);raw=np.unpackbits(a['mask_bits'])[:int(np.prod(shape))].reshape(shape).astype(bool);sam={'sam:'+str(i):{'id':'sam:'+str(i),'source':'sam','mask':m} for i,m in zip(a['ids'],raw)};data=np.load(CP/c['archive'],allow_pickle=False);labels=data['labels'];cell={'cellpose:'+v['id']:{'id':'cellpose:'+v['id'],'source':'cellpose','mask':labels==int(v['id'])} for v in c['ranking']};lookup={**sam,**cell};refs=list(data['refs_visible']);ann_ids=r['annotation_ids'];ranks={name:[lookup[i] for i in ids] for name,ids in r['rankings'].items()};links={}
  for method in ('sam_first','cp_first'):
   for suffix,threshold in (('08',.8),('095',.95)):
    name=method+'_'+suffix;ranks[name],links[name]=defer_cross_model(ranks[method],threshold);assert len(ranks[name])==len(ranks[method]) and {x['id'] for x in ranks[name]}=={x['id'] for x in ranks[method]}
  scores={}
  for method,items in ranks.items():
   scores[method]={}
   for n in (5,10,20,'all'):
    selected=items if n=='all' else items[:n];scores[method][str(n)]={'iou05':base.match(refs,ann_ids,selected,.5),'iou075':base.match(refs,ann_ids,selected,.75),'near_pairs_iou08':base.diagnostic(selected)}
  for method in ('sam','cellpose','sam_first','cp_first'):
   for n in ('5','10','20','all'):assert scores[method][n]==r['scores'][method][n]
  for method in ('sam_first','cp_first'):
   for suffix in ('08','095'):
    d=scores[method+'_'+suffix]['all'];b=scores[method]['all'];assert d['iou05']['matched']==b['iou05']['matched'] and d['iou075']['matched']==b['iou075']['matched']
  image=np.asarray(Image.open(c['source_image_path']).convert('RGB'));deferred_ids={x['candidate'] for x in links['sam_first_08']};panel_ranks={**ranks,'deferred_08':[x for x in ranks['sam_first_08'] if x['id'] in deferred_ids]};pic=OUT/f"menne-{r['image_id']}.png";panel(image,refs,panel_ranks,pic)
  record={'image_id':r['image_id'],'slide':r['slide'],'category':r['category'],'reference_count':len(refs),'annotation_ids':ann_ids,'sam_archive':r['sam_archive'],'sam_archive_sha256':r['sam_archive_sha256'],'cellpose_archive':r['cellpose_archive'],'cellpose_archive_sha256':r['cellpose_archive_sha256'],'rankings':{k:[x['id'] for x in v] for k,v in ranks.items()},'deferrals':links,'scores':scores,'image':pic.name,'image_sha256':sha(pic)};records.append(record);print(r['image_id'],{n:scores[n]['10']['iou05']['matched'] for n in ('sam','sam_first','sam_first_08','sam_first_095','cp_first_08')},flush=True)
 (OUT/'results.json').write_text(json.dumps({'format':'l69-deferral-v1','protocol_sha256':sha(OUT/'protocol.json'),'records':records,'warning':'Previously examined, incompletely labeled development fields; ranking deferrals do not assert identity. Cellpose is pixel-exclusive and R79 SAM candidates were already subject to within-stream NMS. No real overlap or false-positive claim.'},indent=2)+'\n')
if __name__=='__main__':main()
