"""Build an all-cases visual audit of unverified mask hypotheses."""
import collections,html,json
from pathlib import Path
import numpy as np
from PIL import Image,ImageDraw
R=Path(__file__).resolve().parents[1];D=R/'results/r112/diversity-fetch';O=D/'mask-hypotheses';data=json.loads((O/'results.json').read_text());counts=collections.Counter(r['triage'] for r in data['records']);sections=[]
for r in data['records']:
 img=Image.open(D/r['source_crop']).convert('RGB');w,h=img.size;scale=min(230/w,230/h);size=(max(1,round(w*scale)),max(1,round(h*scale)));panel=Image.new('RGB',(960,270),'white');d=ImageDraw.Draw(panel)
 for j,(name,title) in enumerate((('source','Source / prompts'),('center','Center prompt'),('minus','Side prompt −'),('plus','Side prompt +'))):
  v=img.convert('RGBA')
  if name!='source':
   m=np.asarray(Image.open(O/r['masks'][name]['file']).convert('L'));layer=Image.new('RGBA',v.size,(0,140,112,0));layer.putalpha(Image.fromarray((m>0).astype('uint8')*105));v=Image.alpha_composite(v,layer)
  v=v.convert('RGB').resize(size,Image.Resampling.LANCZOS);x=j*240+(230-size[0])//2;y=28+(230-size[1])//2;panel.paste(v,(x,y));d.text((j*240+4,6),title,fill='#1a3c37')
  if name=='source':
   for px,py in r['source_points_xy']:
    x1=x+px*size[0]/w;y1=y+py*size[1]/h;d.ellipse((x1-3,y1-3,x1+3,y1+3),fill='#ed8a10')
 fn=f"{r['annotation_id']}-comparison.jpg";panel.save(O/fn,quality=90);a=', '.join(f'{v:.2f}' for v in r['pairwise_iou']);sections.append(f'<article><h3>{html.escape(r["source_species"])} · {html.escape(r["annotation_id"])}</h3><p>Status: {html.escape(r["triage"])} · pairwise mask IoUs: {a} · center mask covers {r["center_mask_crop_fraction"]:.1%} of crop. These are model diagnostics, not correctness.</p><a href="{fn}"><img loading="lazy" src="{fn}" alt="Source with prompts and three candidate masks"></a><p><a href="/{html.escape(str((D/r["source_crop"]).relative_to(R)))}">Original pixels</a> · '+ ' · '.join(f'<a href="{html.escape(r["masks"][name]["file"])}">{name} mask</a>' for name in ('center','minus','plus'))+'</p></article>')
(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>Development mask hypotheses</title><style>body{font:16px/1.55 system-ui;background:#f3f6f0;color:#183b37;margin:0}main{max-width:1100px;margin:auto;padding:25px}h1,h2,h3{font-family:Georgia,serif}a{color:#096c58}.notice,article{background:white;border:1px solid #cddbd2;padding:16px;margin:14px 0}.notice{border-left:5px solid #bb861e}img{max-width:100%;height:auto}</style><body><main><nav><a href="/results/r112/diversity-fetch/">Diverse development sources</a> · <a href="/results/r112/">Synthetic training</a></nav><h1>Development mask hypotheses</h1><p class="notice"><strong>Not ground truth and not approved training masks.</strong> The same model was prompted three times per image using positions derived from rough source annotations. High agreement can still describe the wrong specimen or background. Original taxon names remain unverified.</p><p>All '''+str(len(data['records']))+''' diverse development crops were processed; no validation or test candidates were used. Three rough polygons use an additional unvalidated principal-axis prompt heuristic. A fixed geometric rule marked '''+str(counts['consistent-unverified'])+''' as consistent-unverified and '''+str(counts['needs-inspection'])+''' as needing inspection. This is workload triage only, not a precision or accuracy estimate. Orange dots show prompts on the source image; green tint shows an individual candidate.</p><p><a href="protocol.json">Fixed prompt and triage protocol</a> · <a href="results.json">All prompts, masks and scores</a> · <a href="verify.log">Verification</a></p>'''+''.join(sections)+'''</main></body></html>''')
print('Rendered',len(sections),'cases;',dict(counts))
