"""Display all matched signal-gain crop alternatives and results."""
import html,json
from pathlib import Path
from PIL import Image,ImageDraw
R=Path(__file__).resolve().parents[1];O=R/'results/r112/design/species-gain-study';p=json.loads((O/'results.json').read_text());cards=[];matches={g:sum(x['variants'][g]['matches_source_name'] for x in p['records']) for g in ('1','2','4')};orig=sum(x['original_source_match'] for x 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'])]+[(f'Gain {k}x',r['variants'][k]['image']) for k in ('1','2','4')]
 for j,(title,f) in enumerate(files):
  image=Image.open(O/f).convert('L');image.thumbnail((240,235),Image.Resampling.LANCZOS);panel.paste(image,(j*250+(245-image.width)//2,30+(235-image.height)//2));d.text((j*250+4,5),title,fill=20)
 fn=f'{r["annotation_id"]}-comparison.jpg';panel.save(O/fn,quality=90);pred=' · '.join(f'{k}×: {html.escape(r["variants"][k]["prediction"])}' for k in ('1','2','4'));ext=' · '.join(f'{k}×: {r["variants"][k]["new_boundary_pixels_within_target_support"]:,}' for k in ('1','2','4'));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}. Newly boundary-valued target-support pixels: {ext}.</p><a href="{fn}"><img loading="lazy" src="{fn}" alt="Original crop and three synthetic signal gains"></a><p><a href="{html.escape(r["source_original_crop"])}">Original source</a> · '+ ' · '.join(f'<a href="{html.escape(r["variants"][k]["image"])}">{k}× crop</a>' for k in ('1','2','4'))+'</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>Species-signal gain 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-retention-corrected/">Previous comparison</a></nav><h1>Can stronger signal preserve species predictions?</h1><p class="notice"><strong>Exploratory development diagnostic, not accuracy or physical validation.</strong> The same 59 previously viewed source cutouts and synthetic placements are compared. Labels are source metadata, masks are unverified, and a frozen classifier is forced to pick one of four species. The crop location is known from the renderer rather than discovered by a detector.</p><p>Each full synthetic field is regenerated with the same positions, weak masks and opacity, multiplying the additive residual by 1, 2 or 4. The source-name matches are: original '''+str(orig)+'''/59; synthetic 1× '''+str(matches['1'])+'''/59; 2× '''+str(matches['2'])+'''/59; 4× '''+str(matches['4'])+'''/59. This comparison was designed after inspecting the previous outcomes, and these counts cannot show transfer to real Academy slides or establish which renderer is most realistic.</p><p>For each target support, we count final pixels at 0 or 255 that were not already at either boundary in the background. This is a numerical boundary-value proxy; neighboring objects may contribute, and shared pixels may be counted more than once. It does not measure species-identifying structure or biological correctness.</p><p><a href="protocol.json">Fixed comparison</a> · <a href="results.json">Predictions and scene 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),'paired source images; original',orig,'gains',matches)
