"""Score fixed candidate interleavings on real projected-overlap annotations."""
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 r81_progress import update
import r79_combine as base
import r38_synthetic_crossings as masks
R=Path(__file__).resolve().parents[1];O=R/'results/r81'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def pair_diagnostic(refs,annids,items,assignment):
 lookup={x['id']:x['mask'] for x in items};index={aid:i for i,aid in enumerate(annids)};pairs=[];a=assignment['assignments']
 for j in range(len(a)):
  for k in range(j):
   x,y=a[j],a[k];pred_iou=masks.iou(lookup[x['candidate_id']],lookup[y['candidate_id']]);inter=int(np.count_nonzero(refs[index[x['annotation_id']]]&refs[index[y['annotation_id']]]))
   if pred_iou>=.8:pairs.append({'candidate_ids':[x['candidate_id'],y['candidate_id']],'annotation_ids':[x['annotation_id'],y['annotation_id']],'prediction_iou':float(pred_iou),'reference_shared_pixels':inter})
 return pairs
def panel(image,refs,ranks,path):
 w,h=image.size;scale=min(1,768/w);tw,th=round(w*scale),round(h*scale);out=Image.new('RGB',(790,(th+30)*5),'white');draw=ImageDraw.Draw(out)
 for i,(title,ms) in enumerate([('Source polygons',refs),('Specialist YOLO top 10',[x['mask'] for x in ranks['yolo'][:10]]),('Cellpose top 10',[x['mask'] for x in ranks['cellpose'][:10]]),('YOLO-first mixed top 10',[x['mask'] for x in ranks['yolo_first'][:10]]),('0.8-deferred top 10',[x['mask'] for x in ranks['yolo_first_08'][:10]])]):
  tile=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)
  y=i*(th+30);draw.text((4,y+4),title,fill='#203a38');out.paste(tile.convert('RGB').resize((tw,th)),(4,y+24))
 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'])
 spec=json.loads((O/'specialist.json').read_text());cp=json.loads((O/'cellpose.json').read_text());audit=json.loads((O/'source-audit.json').read_text())['selected'];assert spec['protocol_sha256']==cp['protocol_sha256']==sha(O/'protocol.json') and len(spec['records'])==len(cp['records'])==len(audit)==12;records=[]
 for n,(s,c,source) in enumerate(zip(spec['records'],cp['records'],audit),1):
  ident=s['image_id'];assert c['image_id']==source['image_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);refs=list(a['refs']);annids=[int(x) for x in a['annotation_ids']];overlap=[int(x) for x in a['overlap_indices']];yolo=[{'id':f'yolo:{i}','source':'yolo','mask':m} for i,m in enumerate(raw)];b=np.load(O/c['archive'],allow_pickle=False);labels=b['labels'];cell=[{'id':'cellpose:'+x['id'],'source':'cellpose','mask':labels==int(x['id'])} for x in c['ranking']];ranks={'yolo':yolo,'cellpose':cell,'yolo_first':base.mix(yolo,cell),'cp_first':base.mix(cell,yolo)};links={}
  for order in ('yolo_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 {x['id'] for x in ranks[key]}=={x['id'] for x in ranks[order]}
  subset=[refs[i] for i in overlap];subset_ids=[annids[i] for i in overlap];scores={}
  for name,items in ranks.items():
   scores[name]={}
   for budget in (5,10,20,30,'all'):
    chosen=items if budget=='all' else items[:budget];score05=base.match(refs,annids,chosen,.5);score075=base.match(refs,annids,chosen,.75);ov05=base.match(subset,subset_ids,chosen,.5);ov075=base.match(subset,subset_ids,chosen,.75);scores[name][str(budget)]={'all05':score05,'all075':score075,'overlap05':ov05,'overlap075':ov075,'near_pairs_iou08':base.diagnostic(chosen),'matched_near_pairs':pair_diagnostic(refs,annids,chosen,score05)}
  prior=s['observed'];assert scores['yolo']['30']['all05']['matched']==prior['all_05'] and scores['yolo']['30']['all075']['matched']==prior['all_075'] and scores['yolo']['30']['overlap05']['matched']==prior['overlap_subset_05']
  for name in ('yolo_first','cp_first'):
   for suffix in ('08','095'):
    for k in ('all05','all075','overlap05','overlap075'):assert scores[name+'_'+suffix]['all'][k]['matched']==scores[name]['all'][k]['matched']
  image=Image.open(source['path']).convert('RGB').resize(tuple(source['size_resized']),Image.Resampling.LANCZOS);pic=O/f'field-{ident}.png';panel(image,refs,ranks,pic);record={'image_id':ident,'filename':source['filename'],'group':source['group'],'reference_count':len(refs),'annotation_ids':annids,'overlap_reference_indices':overlap,'specialist_archive':s['archive'],'specialist_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(record);update('Scoring',n,12,f'Field {ident}: fixed rankings scored.');print(f"{n}/12 {ident} "+' '.join(f"{k}={scores[k]['10']['overlap05']['matched']}/{len(overlap)}" for k in ('yolo','cellpose','yolo_first','yolo_first_08')),flush=True)
 (O/'results.json').write_text(json.dumps({'format':'r81-real-chain-deferral-v1','protocol_sha256':sha(O/'protocol.json'),'specialist_sha256':sha(O/'specialist.json'),'cellpose_sha256':sha(O/'cellpose.json'),'records':records,'warning':'Previously viewed marine chain crops; model training provenance and biological independence unknown. Overlap means >=10 shared rasterized reference pixels, not proven physical occlusion. No freshwater, false-positive, species identification or human-level claim.'},indent=2)+'\n');update('Scoring complete',12,12,'Results saved; independent verification and report remain.')
if __name__=='__main__':main()
