"""Retrospective untuned round-robin union of retained candidates; not independent validation."""
import json,hashlib
from pathlib import Path
import numpy as np
from PIL import Image,ImageDraw
from l70_cellpose import match
R=Path(__file__).resolve().parents[1];O=R/'results/r92';P=R/'results/l79'
def sha(path):
 h=hashlib.sha256()
 with open(path,'rb') as f:
  for b in iter(lambda:f.read(1048576),b''):h.update(b)
 return h.hexdigest()
l79=json.loads((P/'results.json').read_text()); real={r['id']:r for r in json.loads((R/'results/r91/results.json').read_text())['records']};syn={(r['pair'],r['condition']):r for r in json.loads((R/'results/r91/synthetic/results.json').read_text())['records']};records=[]
for r in l79['records']:
 z=np.load(P/r['archive']);old=np.load(R/r['source_archive']);refs=z['refs'];ids=z['refids'].tolist();labels=z['labels'];cp=[labels==j for j in r['candidate_order']];shape=tuple(old['mask_shape']);raw=np.unpackbits(old['baseline_bits'])[:np.prod(shape)].reshape(shape).astype(bool);points=[f'{x}-{y}' for x,y in old['points'].tolist()];lookup=dict(zip(points,raw));
 if r['group']=='real':oldrow=real[r['name'][5:]]
 else:
  _,pair,condition=r['name'].split('-',2);oldrow=syn[(int(pair),condition)]
 sam=[lookup[k] for k in oldrow['models']['baseline']['ranking']];combined=[]
 for i in range(max(len(cp),len(sam))):
  if i<len(sam):combined.append(sam[i])
  if i<len(cp):combined.append(cp[i])
 masks=np.stack(combined[:30]) if combined else np.zeros((0,512,512),bool);scores={str(t):match(refs,ids,masks,t) for t in (.5,.75)}
 imgpath=R/r['source']
 if r['group']=='real':
  rgb=Image.new('RGB',(512,512),'black');rgb.paste(Image.open(imgpath).convert('RGB').resize((512,384),Image.Resampling.LANCZOS),(0,64))
 else:rgb=Image.open(imgpath).convert('RGB')
 panel=Image.new('RGB',(1080,400),'white');d=ImageDraw.Draw(panel)
 for k,(title,arr) in enumerate([('Reference regions',refs),('Union top 30',masks),('Union all candidates',combined)]):
  tile=rgb.convert('RGBA')
  for i,m in enumerate(arr):
   lay=Image.new('RGBA',tile.size,['#008a70','#cd603b','#7357b4','#c29d2a'][i%4]);lay.putalpha(Image.fromarray(m.astype('uint8')*95));tile=Image.alpha_composite(tile,lay)
  panel.paste(tile.convert('RGB').resize((350,350)),(k*360+5,35));d.text((k*360+5,10),title,fill='#203a38')
 pic=O/(r['name']+'.png');panel.save(pic)
 records.append({'name':r['name'],'group':r['group'],'condition':r['condition'],'references':len(refs),'sam_candidates':len(sam),'cellpose_candidates':len(cp),'union_candidates':len(combined),'scores_top30':scores,'sam_scores_top30':r['mobile_sam']['30'],'cellpose_scores_top30':r['scores']['30'],'image':pic.name,'image_sha256':sha(pic),'l79_archive_sha256':r['archive_sha256'],'source_archive_sha256':r['source_archive_sha256']})
(O/'exploratory.json').write_text(json.dumps({'method':'After examining earlier results, interleave MobileSAM and Cellpose candidates in their native ranks, starting with MobileSAM. No duplicate suppression, truncation after 30; matching is one-to-one. Comparisons use each method top 30 and were not independent or prespecified.','l79_results_sha256':sha(P/'results.json'),'script_sha256':sha(__file__),'records':records},indent=2)+'\n')
for group in ('real','synthetic'):
 rr=[r for r in records if r['group']==group]
 for t in ('0.5','0.75'):
  print(group,t,'refs',sum(r['references'] for r in rr),'sam',sum(r['sam_scores_top30'][t]['matched'] for r in rr),'cellpose',sum(r['cellpose_scores_top30'][t]['matched'] for r in rr),'union',sum(r['scores_top30'][t]['matched'] for r in rr))
