"""Retrospective, reference-free edge-contact gating over two saved streams."""
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/l92'
def unpack(z,prefix):
 shape=tuple(z[prefix+'mask_shape']);return np.unpackbits(z[prefix+'mask_bits'])[:np.prod(shape)].reshape(shape).astype(bool)
def contact(m,rect):
 x0,y0,x1,y1=rect;return max(int(m[y0:y1,x0].sum()),int(m[y0:y1,x1-1].sum()),int(m[y0,x0:x1].sum()),int(m[y1-1,x0:x1].sum()))
def panel(rgb,ref,streams,path):
 im=Image.new('RGB',(1200,340),'white');d=ImageDraw.Draw(im)
 for k,(title,arr) in enumerate([('Selected source region',[ref]),('Variance-only top 10',stack(streams['baseline'][:10])),('Boundary-only top 10',stack(streams['boundary'][:10])),('Conditional list top 10',stack(streams['conditional'][:10]))]):
  tile=Image.fromarray(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')*100));tile=Image.alpha_composite(tile,lay)
  im.paste(tile.convert('RGB').resize((290,290)),(k*300+5,30));d.text((k*300+5,8),title,fill='#203a38')
 im.save(path)
def main():
 p=json.loads((O/'protocol.json').read_text())
 for f,h in p['inputs'].items():assert sha(R/f)==h
 out=[]
 for study in ('r107','r108'):
  cases=json.loads((R/'results'/study/'results.json').read_text())['records']
  for r in cases:
   ap=R/'results'/study/r['archive'];assert sha(ap)==r['archive_sha256'] and sha(R/r['source'])==r['source_sha256'];z=np.load(ap);ref=z['ref'];refid=int(z['refid']);rect=r['content_rect']
   if study=='r107':
    prior=R/r['prior_archive'];assert sha(prior)==r['prior_archive_sha256'];a=np.load(prior);am=unpack(a,'');bm=unpack(z,'');ai=a['ids'].tolist();bi=z['ids'].tolist();ar=r['rankings']['baseline'];br=r['rankings']['boundary'];name=str(r['id'])
   else:
    am=unpack(z,'variance_');bm=unpack(z,'boundary_');ai=z['variance_ids'].tolist();bi=z['boundary_ids'].tolist();ar=r['stats']['variance']['ranking'];br=r['stats']['boundary']['ranking'];name=str(r['index'])
   alook=dict(zip(ai,am));blook=dict(zip(bi,bm));a=[{'id':'baseline:'+x,'mask':alook[x]} for x in ar];b=[{'id':'boundary:'+x,'mask':blook[x]} for x in br];contacts=[contact(x['mask'],rect) for x in a[:10]];trigger=any(x>=8 for x in contacts);mixed=interleave(a,b) if trigger else a;streams={'baseline':a,'boundary':b,'conditional':mixed};scores={method:{str(n):{str(t):match(np.stack([ref]),[refid],stack(items if n=='all' else items[:n]),t) for t in (.5,.75)} for n in (10,30,60,'all')} for method,items in streams.items()};links=[]
   if trigger:
    for i,x in enumerate(a[:15]):
     for j,y in enumerate(b[:15]):
      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({'baseline_rank':i+1,'boundary_rank':j+1,'iou':iou})
   if r['view']=='clipped':
    image=(R/'results/l91'/r['clipped_image']) if study=='r107' else (R/'results/r108'/r['clipped_image']);assert sha(image)==r['clipped_image_sha256'];rgb=np.asarray(Image.open(image).convert('RGB'))
   else:
    src=Image.open(R/r['source']).convert('RGB');rgb=np.zeros((512,512,3),np.uint8);rgb[64:448]=np.asarray(src.resize((512,384),Image.Resampling.LANCZOS))
   stem=f'{study}-{name}-{r["view"]}';pic=O/(stem+'.png');panel(rgb,ref,streams,pic);out.append({'study':study,'name':name,'view':r['view'],'source':r['source'],'source_sha256':r['source_sha256'],'archive':r['archive'],'archive_sha256':r['archive_sha256'],'prior_archive':r.get('prior_archive'),'prior_archive_sha256':r.get('prior_archive_sha256'),'image':r.get('clipped_image'),'image_sha256':r.get('clipped_image_sha256'),'content_rect':rect,'trigger':trigger,'first10_edge_contact':contacts,'queries_if_executed':512 if trigger else 256,'encoding_upper_bound_if_separate':32 if trigger else 16,'rankings':{k:[x['id'] for x in v] for k,v in streams.items()},'scores':scores,'cross_stream_top15_iou08':links,'panel':pic.name,'panel_sha256':sha(pic)});print(stem,'trigger',trigger,'top30',*[scores[k]['30']['0.5']['matched'] for k in ('baseline','boundary','conditional')],flush=True)
 (O/'results.json').write_text(json.dumps({'protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'records':out},indent=2)+'\n')
if __name__=='__main__':main()
