"""Evaluate frozen SAM/Cellpose mixing and deferral on R48 components."""
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
from r80_progress import update
import r79_combine as base
R=Path(__file__).resolve().parents[1];O=R/'results/r80'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def panel(image,refs,ranks,path):
 out=Image.new('RGB',(1250,240),'white');draw=ImageDraw.Draw(out)
 for i,(label,ms) in enumerate([('Source components',refs),('MobileSAM top 10',[x['mask'] for x in ranks['sam'][:10]]),('Cellpose top 10',[x['mask'] for x in ranks['cellpose'][:10]]),('Mixed top 10',[x['mask'] for x in ranks['sam_first'][:10]]),('Deferred 0.8 top 10',[x['mask'] for x in ranks['sam_first_08'][:10]])]):
  tile=Image.fromarray(image).convert('RGBA')
  for j,m in enumerate(ms):
   layer=Image.new('RGBA',tile.size,['#008a70','#cd603b','#7357b4','#c29d2a'][j%4]);layer.putalpha(Image.fromarray(m.astype('uint8')*100));tile=Image.alpha_composite(tile,layer)
  out.paste(tile.convert('RGB').resize((245,184)),(i*250+2,38));draw.text((i*250+3,7),label,fill='#203a38')
 out.save(path)
def main():
 p=json.loads((O/'protocol.json').read_text())
 for x in p['inputs']:
  if sha(x['path'])!=x['sha256']:raise ValueError('Changed input: '+x['path'])
 sam=json.loads((O/'baseline.json').read_text());cp=json.loads((O/'cellpose.json').read_text());assert sam['protocol_sha256']==cp['protocol_sha256']==sha(O/'protocol.json') and len(sam['records'])==len(cp['records'])==24;source={x['id']:x for x in json.loads((O/'source-audit.json').read_text())['targets']};records=[]
 for n,(s,c) in enumerate(zip(sam['records'],cp['records']),1):
  ident=s['id'];assert c['id']==ident and sha(O/s['archive'])==s['archive_sha256'] and sha(O/c['archive'])==c['archive_sha256'];a=np.load(O/s['archive'],allow_pickle=False);shape=tuple(a['mask_shape']);raw=np.unpackbits(a['mask_bits'])[:int(np.prod(shape))].reshape(shape).astype(bool);lookup={'sam:'+str(x):{'id':'sam:'+str(x),'source':'sam','mask':m} for x,m in zip(a['ids'],raw)};b=np.load(O/c['archive'],allow_pickle=False);labels=b['labels'];lookup.update({'cellpose:'+x['id']:{'id':'cellpose:'+x['id'],'source':'cellpose','mask':labels==int(x['id'])} for x in c['ranking']});samrank=[lookup['sam:'+x] for x in s['combined_ranking']];cprank=[lookup['cellpose:'+x['id']] for x in c['ranking']];ranks={'sam':samrank,'cellpose':cprank,'sam_first':base.mix(samrank,cprank),'cp_first':base.mix(cprank,samrank)};links={}
  for order in ('sam_first','cp_first'):
   for suffix,thr in (('08',.8),('095',.95)):
    key=order+'_'+suffix;ranks[key],links[key]=defer_cross_model(ranks[order],thr);assert len(ranks[key])==len(ranks[order]) and {q['id'] for q in ranks[key]}=={q['id'] for q in ranks[order]}
  refs=list(a['refs']);refids=[x['box_index'] for x in s['instances']];scores={}
  for name,items in ranks.items():
   scores[name]={}
   for budget in (5,10,20,'all'):
    chosen=items if budget=='all' else items[:budget];scores[name][str(budget)]={'iou05':base.match(refs,refids,chosen,.5),'iou075':base.match(refs,refids,chosen,.75),'near_pairs_iou08':base.diagnostic(chosen)}
  for budget in ('5','10','20'):
   for key in ('iou05','iou075'):assert scores['sam'][budget][key]['matched']==s['scores'][budget][key]['matched']
  for order in ('sam_first','cp_first'):
   for suffix in ('08','095'):
    for metric in ('iou05','iou075'):assert scores[order+'_'+suffix]['all'][metric]['matched']==scores[order]['all'][metric]['matched']
  image=np.asarray(Image.open(source[ident]['image_path']).convert('RGB').resize((768,576),Image.Resampling.LANCZOS));pic=O/f'case-{ident}.png';panel(image,refs,ranks,pic);rec={'id':ident,'reference_count':len(refs),'reference_box_indices':refids,'sam_archive':s['archive'],'sam_archive_sha256':s['archive_sha256'],'cellpose_archive':c['archive'],'cellpose_archive_sha256':c['archive_sha256'],'rankings':{k:[q['id'] for q in v] for k,v in ranks.items()},'deferrals':links,'scores':scores,'image':pic.name,'image_sha256':sha(pic)};records.append(rec);update('Scoring',n,24,f'Case {ident}: fixed rankings scored.');print(f"{n}/24 case {ident}: "+' '.join(f"{k}={scores[k]['10']['iou05']['matched']}" for k in ('sam','cellpose','sam_first','sam_first_08')),flush=True)
 (O/'results.json').write_text(json.dumps({'format':'r80-mixed-deferral-v1','protocol_sha256':sha(O/'protocol.json'),'baseline_sha256':sha(O/'baseline.json'),'cellpose_sha256':sha(O/'cellpose.json'),'records':records,'warning':'Previously viewed structurally derived non-overlap components; unknown model and biological independence. No false-positive, real-overlap or human-level claim.'},indent=2)+'\n');update('Scoring complete',24,24,'Results saved; verification and visual report remain.')
if __name__=='__main__':main()
