"""Compare reference-free mixed uniform/variance tile streams at fixed mask budgets."""
import json
from pathlib import Path
import numpy as np
from PIL import Image,ImageDraw
from l70_cellpose import match
from l86_oracle import sha
from r99_compete import stack,interleave
R=Path(__file__).resolve().parents[1];O=R/'results/r102';U=R/'results/l88';V=R/'results/l89';S=R/'results/l75'
def load(folder,row,prefix):
 path=folder/row['archive'];assert sha(path)==row['archive_sha256'];z=np.load(path);shape=tuple(z['mask_shape']);m=np.unpackbits(z['mask_bits'])[:np.prod(shape)].reshape(shape).astype(bool);lookup=dict(zip(z['ids'].tolist(),m));return z,[{'id':prefix+':'+v,'mask':lookup[v]} for v in row['ranking']]
def paint(rgb,refs,streams,path):
 out=Image.new('RGB',(1200,340),'white');d=ImageDraw.Draw(out)
 for k,(title,masks) in enumerate([('Source visible supports',refs),('Uniform tile top 30',stack(streams['uniform'][:30])),('Variance tile top 30',stack(streams['variance'][:30])),('Mixed, uniform first top 30',stack(streams['uniform_first'][:30]))]):
  tile=Image.fromarray(rgb).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')*95));tile=Image.alpha_composite(tile,lay)
  out.paste(tile.convert('RGB').resize((290,290)),(k*300+5,30));d.text((k*300+5,8),title,fill='#203a38')
 out.save(path)
def main():
 p=json.loads((O/'protocol.json').read_text())
 for f,h in p['inputs'].items():assert sha(R/f)==h
 u=json.loads((U/'results.json').read_text())['records'];v=json.loads((V/'results.json').read_text())['records'];src={(x['pair'],x['condition']):x for x in json.loads((S/'results.json').read_text())['records']};assert len(u)==len(v)==16;records=[]
 for a,b in zip(u,v):
  key=(a['pair'],a['condition']);assert key==(b['pair'],b['condition']) and a['source_image_sha256']==b['source_image_sha256'];za,uniform=load(U,a,'uniform');zb,variance=load(V,b,'variance');assert np.array_equal(za['refs'],zb['refs']);refs=za['refs'];ids=src[key]['included_visible_ids'];streams={'uniform':uniform,'variance':variance,'uniform_first':interleave(uniform,variance),'variance_first':interleave(variance,uniform)};scores={}
  for method,items in streams.items():scores[method]={str(n):{str(t):match(refs[ids],ids,stack(items if n=='all' else items[:n]),t) for t in (.5,.75)} for n in (10,30,60,120,'all')}
  links=[]
  for i,x in enumerate(uniform[:30]):
   for j,y in enumerate(variance[:30]):
    inter=int(np.count_nonzero(x['mask']&y['mask']));union=int(np.count_nonzero(x['mask']|y['mask']));iou=inter/union if union else 0
    if iou>=.8:links.append({'uniform_rank':i+1,'variance_rank':j+1,'iou':iou})
  name=f"pair-{a['pair']}-{a['condition']}";pic=O/(name+'.png');ip=S/a['source_image'];assert sha(ip)==a['source_image_sha256'];paint(np.asarray(Image.open(ip).convert('RGB')),refs,streams,pic);rec={'pair':a['pair'],'condition':a['condition'],'split':a['split'],'source_image':a['source_image'],'source_image_sha256':a['source_image_sha256'],'uniform_archive':a['archive'],'uniform_archive_sha256':a['archive_sha256'],'variance_archive':b['archive'],'variance_archive_sha256':b['archive_sha256'],'panel':pic.name,'panel_sha256':sha(pic),'rankings':{k:[x['id'] for x in v] for k,v in streams.items()},'scores':scores,'top30_cross_stream_iou08':links};records.append(rec);print(len(records),name,'top30',*[scores[k]['30']['0.5']['matched'] for k in streams],flush=True)
 (O/'results.json').write_text(json.dumps({'protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'records':records},indent=2)+'\n')
if __name__=='__main__':main()
