"""Show matched additive and translucent-blend source crops."""
import html,json
from pathlib import Path
from PIL import Image,ImageDraw
R=Path(__file__).resolve().parents[1];O=R/'results/r112/design/species-blend-study';p=json.loads((O/'results.json').read_text());modes=('additive_v1','direct_alpha','local_matched_alpha');display={'additive_v1':'Additive v1','direct_alpha':'Direct alpha','local_matched_alpha':'Local matched alpha'};cards=[];counts={m:sum(r['variants'][m]['matches_source_name'] for r in p['records']) for m in modes};original=sum(r['original_source_match'] for r in p['records'])
for r in p['records']:
 panel=Image.new('L',(1000,275),'white');d=ImageDraw.Draw(panel);files=[('Original source',r['source_original_crop'])]+[(display[k],r['variants'][k]['image']) for k in modes]
 for j,(title,fn) in enumerate(files):
  im=Image.open(O/fn).convert('L');im.thumbnail((240,235),Image.Resampling.LANCZOS);panel.paste(im,(j*250+(245-im.width)//2,30+(235-im.height)//2));d.text((j*250+4,5),title,fill=20)
 name=r['annotation_id']+'-comparison.jpg';panel.save(O/name,quality=90);pred=' · '.join(f'{display[k]}: {html.escape(r["variants"][k]["prediction"])}' for k in modes);cards.append(f'<article><h3>{html.escape(r["source_species"])} · {html.escape(r["annotation_id"])}</h3><p>Frozen classifier: original {html.escape(r["original_source_prediction"])} · {pred}.</p><a href="{name}"><img loading="lazy" src="{name}" alt="Original crop and three synthetic blending methods"></a><p><a href="{html.escape(r["source_original_crop"])}">Original source</a> · '+ ' · '.join(f'<a href="{html.escape(r["variants"][k]["image"])}">{display[k]}</a>' for k in modes)+'</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>Translucent blending comparison</title><style>body{font:16px/1.55 system-ui;background:#f3f6f0;color:#193b37;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 #bc851b}img{max-width:100%;height:auto}</style><body><main><nav><a href="/results/r112/">Synthetic training</a> · <a href="/results/r112/design/species-gain-study/">Gain study</a></nav><h1>Can translucent blending preserve species signal?</h1><p class="notice"><strong>Exploratory development diagnostic, not accuracy or optical validation.</strong> These 59 crops and scenes were previously viewed. Source names and masks are unverified, the classifier is forced to choose among four species, and target crop positions are supplied by the generator.</p><p>The compared methods hold source objects, positions, weak masks and per-object opacity fixed. The original additive renderer adds a source intensity residual. Direct alpha blends source pixels with the current background; local-matched alpha first shifts the source relative to the median in a ring around the weak support. Neither alpha technique is an optical microscope simulation. The ring may contain real or synthetic organisms.</p><p>Frozen-classifier exact matches to source names: original '''+str(original)+'''/59; additive '''+str(counts['additive_v1'])+'''/59; direct alpha '''+str(counts['direct_alpha'])+'''/59; local-matched alpha '''+str(counts['local_matched_alpha'])+'''/59. These differences do not establish species accuracy, realistic optics or real-slide transfer.</p><p><a href="protocol.json">Comparison protocol</a> · <a href="results.json">Predictions, scene and ring provenance</a> · <a href="verify.log">Verification</a> · <a href="/research/R112_DESIGN.md">Research interpretation</a></p>'''+''.join(cards)+'''</main></body></html>''')
print('Rendered',len(cards),'cases; source',original,'modes',counts)
