"""Render all fixed-layout contrast variants and clipping diagnostics."""
import html,json,statistics
from pathlib import Path
import cv2,numpy as np
from PIL import Image,ImageDraw
R=Path(__file__).resolve().parents[1];S=R/'results/r112/weak-development-v1';O=R/'results/r112/design/contrast-study';p=json.loads((O/'results.json').read_text());sections=[];totals={}
for gain in ('1','2','4'):
 vals=[v for r in p['records'] for v in r['variants'][gain]['placements'] if v['support_pixels']];totals[gain]={'placements':len(vals),'median':statistics.median(v['mean_absolute_change'] for v in vals),'under5':sum(v['mean_absolute_change']<5 for v in vals),'new_boundary_pixels':sum(v['new_boundary_pixels'] for v in vals),'support_pixels':sum(v['support_pixels'] for v in vals)}
for row in p['records']:
 imgs=[np.asarray(Image.open(O/row['variants'][str(g)]['image']).convert('L')) for g in (1,2,4)];z=np.load(S/row['baseline_mask_archive']);shape=tuple(z['support_shape']);ms=np.unpackbits(z['support_bits'])[:np.prod(shape)].reshape(shape).astype(bool);annotated=imgs[0].copy()
 for m in ms:
  contours,_=cv2.findContours(m.astype('uint8'),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE);cv2.drawContours(annotated,contours,-1,0,4);cv2.drawContours(annotated,contours,-1,255,2)
 panel=Image.new('L',(1000,275),'white');draw=ImageDraw.Draw(panel)
 for j,(title,arr) in enumerate([('Original gain 1×',imgs[0]),('Gain 2×',imgs[1]),('Gain 4×',imgs[2]),('Weak supports',annotated)]):panel.paste(Image.fromarray(arr).resize((240,240)),(j*250+5,26));draw.text((j*250+6,5),title,fill=30)
 name=row['scene']+'-comparison.jpg';panel.save(O/name,quality=90);sections.append(f'<article><h3>{html.escape(row["scene"])}</h3><a href="{name}"><img loading="lazy" src="{name}" alt="Three synthetic contrast gains and unverified outlines"></a><p><a href="{row["variants"]["1"]["image"]}">Gain 1 image</a> · <a href="{row["variants"]["2"]["image"]}">Gain 2 image</a> · <a href="{row["variants"]["4"]["image"]}">Gain 4 image</a></p></article>')
rows=''.join(f'<tr><td>{g}×</td><td>{v["placements"]}</td><td>{v["median"]:.2f}</td><td>{v["under5"]}</td><td>{v["new_boundary_pixels"]:,} / {v["support_pixels"]:,}</td></tr>' for g,v in totals.items())
(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>Synthetic contrast study</title><style>body{font:16px/1.55 system-ui;color:#193b37;background:#f4f6f0;margin:0}main{max-width:1100px;margin:auto;padding:24px}h1,h2,h3{font-family:Georgia,serif}a{color:#096c58}article,.notice{background:white;border:1px solid #cddbd2;padding:16px;margin:14px 0}.notice{border-left:5px solid #bc851b}img{max-width:100%;height:auto}table{border-collapse:collapse;width:100%;background:white}td,th{padding:8px;border:1px solid #cddbd2;text-align:left}.scroll{overflow-x:auto}</style><body><main><nav><a href="/results/r112/weak-development-v1/">Original scenes</a> · <a href="/results/r112/">Synthetic training</a></nav><h1>Are added structures too faint?</h1><p class="notice"><strong>Renderer diagnostic, not a realism or accuracy test.</strong> These are 32 already viewed scenes and three fixed intensity gains; outlines are unverified source-mask hypotheses. More contrast can also saturate pixels or erase real overlapping details. Original background objects remain unannotated.</p><p>The scene layout, object supports, backgrounds and opacity settings are identical. Gain multiplies the inserted source residual; it is not a physically calibrated microscope parameter. Signal is measured as mean absolute 8-bit change within each support at the moment of insertion, before later overlaps. “New boundary pixels” were changed to 0 or 255 when they were not previously at either limit; repeated support pixels can be counted more than once. It is a saturation proxy, not a count of wrong pixels.</p><div class="scroll"><table><thead><tr><th>Gain</th><th>Placements</th><th>Median mean change</th><th>Mean change &lt;5</th><th>New boundary / support pixels</th></tr></thead><tbody>'''+rows+'''</tbody></table></div><p>All alternatives remain exploratory. A larger numerical change does not establish that the synthetic image looks like a real specimen or preserves species-identifying structure.</p><p><a href="protocol.json">Frozen protocol</a> · <a href="results.json">Per-placement data</a> · <a href="verify.log">Verification</a> · <a href="/research/R112_DESIGN.md">Research note</a></p>'''+''.join(sections)+'''</main></body></html>''')
print('Rendered',len(sections),'paired scenes')
