"""Visualize source mask and all candidate masks for every gate audit case."""
import collections,html,json
from pathlib import Path
import numpy as np
from PIL import Image,ImageDraw
R=Path(__file__).resolve().parents[1];O=R/'results/r112/design/mask-gate-audit';x=json.loads((O/'results.json').read_text());sections=[];group=collections.defaultdict(list)
for row in x['records']:
 src=Image.open(O/row['source_image']).convert('RGBA');w,h=src.size;scale=min(185/w,185/h);size=(max(1,round(w*scale)),max(1,round(h*scale)));out=Image.new('RGB',(1000,230),'white');d=ImageDraw.Draw(out)
 for i,(title,mask) in enumerate([('Source',None),('Source reference',row['reference']),('Center mask',row['masks']['center']['file']),('Side −',row['masks']['minus']['file']),('Side +',row['masks']['plus']['file'])]):
  img=src.copy()
  if mask:
   m=np.asarray(Image.open(O/mask).convert('L'))>0;layer=Image.new('RGBA',src.size,(0,140,110,0));layer.putalpha(Image.fromarray(m.astype('uint8')*105));img=Image.alpha_composite(img,layer)
  img=img.convert('RGB').resize(size,Image.Resampling.LANCZOS);out.paste(img,(i*200+(185-size[0])//2,27+(185-size[1])//2));d.text((i*200+4,5),title,fill='#163d37')
 fn=row['asset']+'-comparison.jpg';out.save(O/fn,quality=90);group[(row['family'],row['triage'])].append(row);sections.append(f'<article><h3>{html.escape(row["asset"])} · {html.escape(row["family"])}</h3><p>{html.escape(row["triage"])}; center/reference IoU {row["center_reference_iou"]:.3f}; prompt source: {html.escape(row["prompt_origin"])}. Reference is a source annotation or structural proxy, not independent scientific ground truth.</p><a href="{fn}"><img loading="lazy" src="{fn}" alt="Source, source region and three proposed masks"></a></article>')
summary=[]
for key,records in group.items():
 a=sum(r['center_reference_iou']>=.5 for r in records);b=sum(r['center_reference_iou']>=.75 for r in records);summary.append(f'<tr><td>{html.escape(key[0])}</td><td>{html.escape(key[1])}</td><td>{len(records)}</td><td>{a}/{len(records)}</td><td>{b}/{len(records)}</td></tr>')
(O/'index.html').write_text('''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Mask triage source-region audit</title><style>body{font:16px/1.55 system-ui;color:#193c37;background:#f4f6f0;margin:0}main{max-width:1100px;margin:auto;padding:24px}a{color:#096c58}h1,h2,h3{font-family:Georgia,serif}article,.notice{background:#fff;border:1px solid #cddbd2;margin:15px 0;padding:16px}.notice{border-left:5px solid #b8801c}img{max-width:100%;height:auto}table{border-collapse:collapse;width:100%;background:#fff}td,th{text-align:left;vertical-align:top;padding:9px;border:1px solid #cddbd2}.scroll{overflow-x:auto}</style><body><main><nav><a href="/results/r112/">Synthetic training</a> · <a href="/results/r112/species-depth/mask-hypotheses/">UDE mask hypotheses</a></nav><h1>Does prompt agreement imply a better mask?</h1><p class="notice"><strong>Small, previously viewed reference-proxy check.</strong> These 58 source regions are not independent expert-adjudicated masks and do not prove accuracy on the UDE or Academy data. Gündüz masks are structurally matched components; Khanom boxes are derived from reference polygons and are optimistic.</p><p>The fixed triage rule compares three point-prompt masks and their crop coverage. Counts below compare the center mask to the source reference, not confirmed diatom truth. Unknown background is not scored as false positive. All cases are shown, not just good examples.</p><div class="scroll"><table><thead><tr><th>Source reference</th><th>Triage</th><th>Cases</th><th>Center IoU ≥0.5</th><th>Center IoU ≥0.75</th></tr></thead><tbody>'''+''.join(summary)+'''</tbody></table></div><p><a href="protocol.json">Fixed protocol</a> · <a href="results.json">All results and masks</a> · <a href="verify.log">Verification</a> · <a href="/research/R112_DESIGN.md">Research interpretation</a></p>'''+''.join(sections)+'''</main></body></html>''')
print('Rendered',len(sections),'cases')
for (family,status),r in group.items():print(family,status,len(r),'at .5',sum(x['center_reference_iou']>=.5 for x in r),'at .75',sum(x['center_reference_iou']>=.75 for x in r))
