"""Create a static, lossless example of inspecting all alternatives in each bundle."""
import json,hashlib,html
from pathlib import Path
import numpy as np,cv2
from PIL import Image
from l80_deferral import candidates
R=Path(__file__).resolve().parents[1];O=R/'results/r93';V=O/'viewer';V.mkdir(exist_ok=True)
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
row=json.loads((R/'results/r92/khanom/results.json').read_text())['records'][0];old={'r84':json.loads((R/'results/r84/results.json').read_text())['records']};refs,ids,mix,rgb,src,arch,category,pairids,previous=candidates(row,'khanom',old);rec=next(x for x in json.loads((O/'results.json').read_text())['records'] if x['name']=='khanom-r84-00');groups=rec['policies']['08']['groups'];lookup={x['id']:x for x in mix};index={x['id']:i for i,x in enumerate(mix)};manifest=[];sections=[]
for n,g in enumerate(groups):
 cards=[]
 for id in g:
  x=lookup[id];path=V/f'candidate-{index[id]:03d}.png';layer=Image.new('RGBA',(512,512),'#008a70');layer.putalpha(Image.fromarray(x['mask'].astype('uint8')*100));pic=Image.alpha_composite(Image.fromarray(rgb).convert('RGBA'),layer).convert('RGB');out=np.array(pic);contours,_=cv2.findContours(x['mask'].astype('uint8'),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE);cv2.drawContours(out,contours,-1,(8,77,58),2);Image.fromarray(out).save(path);manifest.append({'candidate_id':id,'original_rank':index[id]+1,'model':x['source'],'group_rank':n+1,'image':path.name,'sha256':sha(path)});cards.append(f'<figure><img src="{path.name}" alt="Candidate mask over the source image"><figcaption>{html.escape(x["source"])} · original rank {index[id]+1}<br><code>{html.escape(id)}</code></figcaption></figure>')
 sections.append(f'<details {"open" if n==0 else ""}><summary>Group {n+1} · {len(g)} alternative mask(s)</summary><div class="candidates">{"".join(cards)}</div></details>')
assert len(manifest)==len(mix) and len({x['candidate_id'] for x in manifest})==len(mix);(V/'manifest.json').write_text(json.dumps({'source':src,'source_sha256':sha(R/src),'source_inference_archive':arch,'source_inference_archive_sha256':sha(R/arch),'grouping':'L69 0.8 direct-anchor bundles; no identity inference; all individual candidate masks visualized','records':manifest},indent=2)+'\n')
(V/'index.html').write_text('''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Inspect proposal alternatives</title><style>body{font:16px/1.5 system-ui;max-width:1100px;margin:2em auto;padding:0 1em;color:#18342f}a{color:#006b59}.box{background:#fff2d6;padding:1em}details{border:1px solid #cdded3;border-radius:5px;margin:.7em 0;padding:.7em}summary{cursor:pointer;font-weight:600}.candidates{display:flex;gap:1em;flex-wrap:wrap}figure{margin:.7em 0;width:min(280px,100%)}img{max-width:100%}figcaption{font-size:.9em}code{overflow-wrap:anywhere}</style><a href="/results/r93/">Experiment report</a><h1>Inspecting mask alternatives</h1><p class="box">These groups are a display aid based on mask overlap. A group does not establish whether its masks depict the same diatom; two distinct overlapping specimens can be grouped together. Open a group to see every member separately. This page records no decisions and sends no data.</p><p>Example: one previously viewed Khanom field. Green areas are individual candidate masks at the model's 512-pixel inference scale, not expert judgments. The <a href="/'''+html.escape(src)+'''">original full-resolution image</a> and <a href="manifest.json">candidate provenance</a> remain available. The number of groups is not an organism count.</p>'''+''.join(sections)+'</html>')
print('viewer groups',len(groups),'candidates',len(manifest),'preserved',len(mix))
