"""Compare frozen, image-only alternative ordering on saved toy-focus masks."""
import hashlib,json,time,html
from pathlib import Path
import numpy as np
from PIL import Image,ImageDraw
from diatom_pilot.phase_hypotheses import translation_hypotheses
from diatom_pilot.multiplane_hypotheses import build_variants
import r58_focal_controls as controls
import r44_score_fields as scoring
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r60'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def panel(image, groups, path):
 canvas=Image.new('RGB',(4*320,350),'white');d=ImageDraw.Draw(canvas)
 for i,(name,masks) in enumerate(groups):
  im=Image.fromarray(image).convert('RGBA');layer=Image.new('RGBA',im.size,(0,0,0,0))
  for j,m in enumerate(masks):
   color=['#00b886','#e85956','#9670df','#e7ba16'][j%4];c=Image.new('RGBA',im.size,color);c.putalpha(Image.fromarray(m.astype('uint8')*100));layer=Image.alpha_composite(layer,c)
  canvas.paste(Image.alpha_composite(im,layer).convert('RGB').resize((310,310)),(i*320,30));d.text((i*320+4,5),name,fill='#202a28')
 canvas.save(path,quality=85)
def main():
 p=json.loads((OUT/'protocol.json').read_text())
 for item in p['inputs']:
  if sha(ROOT/item['path'])!=item['sha256']:raise ValueError('Frozen input changed: '+item['path'])
 if (OUT/'results.json').exists():raise FileExistsError('Preserve previous result')
 records=[]
 for index,src in enumerate(p['selection'],1):
  started=time.monotonic();path=ROOT/src['archive'];a=np.load(path,allow_pickle=False);shape=tuple(a['candidate_shape']);masks=np.unpackbits(a['candidate_bits'])[:np.prod(shape)].reshape(shape).astype(bool)
  raw=[{'id':str(i),'z':int(z),'mask':m} for i,z,m in zip(a['candidate_ids'],a['candidate_z'],masks)]
  if len({x['id'] for x in raw})!=len(raw):raise ValueError('Nonunique candidate IDs')
  planes=a['planes'];refs=list(a['full_masks'].astype(bool));peaks={};metadata={}
  for z in range(5):
   if z==2:continue
   info=translation_hypotheses(planes[2],planes[z],window='hann');metadata[str(z)]={k:v for k,v in info.items() if k!='surface'};peaks[z]=info['peaks']
  variants=build_variants(raw,peaks);all_variants=variants['multi_interleaved']
  np.savez_compressed(OUT/f'alternatives-{index:02d}.npz',candidate_bits=np.packbits(np.stack([x['mask'] for x in all_variants]).ravel()) if all_variants else np.array([],dtype='uint8'),candidate_shape=np.array([len(all_variants),*planes.shape[1:]]),candidate_ids=np.array([x['id'] for x in all_variants]),source_ids=np.array([x['source_id'] for x in all_variants]),z=np.array([x['z'] for x in all_variants]),dx=np.array([x['dx'] for x in all_variants]),dy=np.array([x['dy'] for x in all_variants]),branch=np.array([x['branch'] for x in all_variants]))
  scores={};kept_modes={}
  for mode,items in variants.items():
   nonempty=[x for x in items if x['mask'].any()];kept,aliases=controls.nms(nonempty,.8);kept_modes[mode]=kept
   scores[mode]={'expanded':len(items),'empty_after_shift':len(items)-len(nonempty),'retained':len(kept),'aliases':aliases,'ranking':[x['id'] for x in kept], 'budgets':{str(n):scoring.match(refs,kept[:n],.5) for n in (5,10,20)},'all':scoring.match(refs,kept,.5)}
  # Verify raw pooling reproduces the previously published R58 score.
  if src['dataset']=='r58':
   previous=src['previous_top20']
   if scores['unregistered']['budgets']['20']['matched']!=previous:raise ValueError('Raw score does not reproduce prior result')
  panel(planes[2],[('Synthetic full masks',refs),('Unregistered top 20',[x['mask'] for x in kept_modes['unregistered'][:20]]),('One shift top 20',[x['mask'] for x in kept_modes['phase_single'][:20]]),('Alternatives top 20',[x['mask'] for x in kept_modes['multi_interleaved'][:20]])],OUT/f'scene-{index:02d}.jpg')
  rec={**src,'raw_candidates':len(raw),'alignment_peaks':metadata,'scores':scores,'elapsed_seconds':round(time.monotonic()-started,3),'alternatives_archive':f'alternatives-{index:02d}.npz','image':f'scene-{index:02d}.jpg'};records.append(rec)
  print(f"{index}/{len(p['selection'])}: {src['dataset']} {src['condition']} pair {src['pair']} "+' '.join(f"{k}:{v['budgets']['20']['matched']}/2" for k,v in scores.items()),flush=True)
 out={'format':'r60-alignment-hypotheses-v1','protocol_sha256':sha(OUT/'protocol.json'),'records':records,'warning':'Synthetic amodal masks and previously inspected sources; no expert labels, no real optical validation or real false-positive estimates. Only alignment and postprocessing timed; precomputed model inference is excluded.'};(OUT/'results.json').write_text(json.dumps(out,indent=2)+'\n')
 cards=[]
 for r in records:
  s=r['scores'];cards.append('<article><h2>'+html.escape(r['condition'])+' · pair '+str(r['pair'])+'</h2><img src="'+r['image']+'" alt="Synthetic masks and three segmentation alternatives"><p>Top 20 matched: raw '+str(s['unregistered']['budgets']['20']['matched'])+'/2; single shift '+str(s['phase_single']['budgets']['20']['matched'])+'/2; alternatives '+str(s['multi_interleaved']['budgets']['20']['matched'])+'/2. Expanded alternatives '+str(s['multi_interleaved']['expanded'])+', retained after suppression '+str(s['multi_interleaved']['retained'])+'.</p></article>')
 table=''
 for mode in ('unregistered','phase_single','multi_primary','multi_interleaved'):
  sums=[sum(r['scores'][mode]['budgets'][str(n)]['matched'] for r in records) for n in (5,10,20)];full=sum(r['scores'][mode]['all']['matched'] for r in records);expanded=sum(r['scores'][mode]['expanded'] for r in records);kept=sum(r['scores'][mode]['retained'] for r in records)
  table+=f'<tr><td>{mode}</td><td>{sums[0]}</td><td>{sums[1]}</td><td>{sums[2]}</td><td>{full}</td><td>{expanded} → {kept}</td></tr>'
 page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Alignment alternatives and segmentation</title><style>body{font:16px/1.5 system-ui;background:#f3f6ef;color:#203a38}main{max-width:1320px;margin:auto;padding:24px}.notice{background:#fff2d6;padding:16px}article{background:white;padding:14px;margin:16px 0}img{width:100%}table{border-collapse:collapse}th,td{padding:8px;border:1px solid #aaa;text-align:left}</style><main><nav><a href="/results/performance/">Performance monitor</a> · <a href="/research/R60.md">Research notes</a></nav><h1>Do alternative alignments recover overlapping diatoms?</h1><p class="notice">These are synthetic crossings made from public diatom images and local backgrounds. Full masks are synthetic targets, not scientist annotations. The same three source pairs recur across conditions. Real overlap accuracy, false positives and human-level performance remain unknown.</p><p>Each source candidate is aligned using either no shift, the strongest image-only phase peak, or up to three image-only peaks plus no shift. We test two candidate orderings. Candidates are suppressed at mask IoU 0.8 and matched one-to-one to synthetic targets at IoU ≥0.5. Full-score matching has no review-budget limit. Raw predictions and all pre-suppression alternatives remain available. Phase peaks are not calibrated confidence.</p><table><tr><th>Ordering</th><th>Top 5 / 30</th><th>Top 10 / 30</th><th>Top 20 / 30</th><th>All / 30</th><th>Expanded → retained</th></tr>TABLE</table><p>Model predictions were precomputed; timings exclude model inference. The image columns show synthetic target masks, raw top 20, single-shift top 20 and interleaved alternatives top 20. Colors distinguish overlays and do not identify individual diatoms. Foreground source: Gündüz et al., <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a>; details in <a href="/results/r58/">R58</a>.</p><p><a href="protocol.json">Frozen protocol and source hashes</a> · <a href="results.json">Full results and candidate orderings</a></p>CARDS</main></html>'''.replace('TABLE',table).replace('CARDS',''.join(cards));(OUT/'index.html').write_text(page)
if __name__=='__main__':main()
