"""Visualize every fixed edge-contact candidate and both alternative masks."""
import html,json
from pathlib import Path
import numpy as np
from PIL import Image,ImageDraw
R=Path(__file__).resolve().parents[1];O=R/'results/r111';p=json.loads((O/'protocol.json').read_text());r=json.loads((O/'results.json').read_text());sections=[]
def unpack(z,k,shape):return np.unpackbits(z[k])[:int(np.prod(z[shape]))].reshape(z[shape]).astype(bool)
def overlay(img,mask,crop):
 o=img.convert('RGBA');layer=Image.new('RGBA',o.size,(0,145,117,0));layer.putalpha(Image.fromarray(mask.astype('uint8')*110));o=Image.alpha_composite(o,layer).convert('RGB');d=ImageDraw.Draw(o);d.rectangle(crop,outline='#ff9c17',width=3);return o
for f,row in zip(p['fields'],r['records']):
 n=f['index'];z=np.load(O/row['archive']);prior=np.load(R/'results/r110'/f['archive']);allraw=unpack(prior,'tile_bits','tile_shape');pm=unpack(z,'point_bits','shape');bm=unpack(z,'box_bits','shape');img=Image.open(R/f['image']).convert('RGB');cards=[]
 for i,c in enumerate(row['cases']):
  out=Image.new('RGB',(1040,305),'white');d=ImageDraw.Draw(out)
  for k,(title,mask) in enumerate([('Source + tile boundary',None),('Original tiled mask',allraw[c['raw_index']]),('Whole-field point prompt',pm[i]),('Whole-field expanded box',bm[i])]):
   pic=img.copy() if mask is None else overlay(img,mask,c['crop'])
   if mask is None:ImageDraw.Draw(pic).rectangle(c['crop'],outline='#ff9c17',width=3)
   out.paste(pic.resize((250,250),Image.Resampling.LANCZOS),(k*260,32));d.text((k*260+3,8),title,fill='#173c36')
  name=f'field-{n}-case-{i:02}.jpg';out.save(O/name,quality=90)
  def metrics(k):
   v=c['variants'][k];return f"{100*v['original_retained_fraction']:.0f}% of original area retained; {v['new_to_original_area_ratio']:.2f}× original area; {'extends' if v['extends_any_contact_side'] else 'does not extend'} across a contacted edge"
  cards.append(f'<article><h3>Tile rank {c["rank"]} · {html.escape(c["id"])}</h3><p>Contact: {html.escape(", ".join(c["contact_sides"]))}; orange rectangle marks its tile. <a href="{name}">Open full-size comparison</a></p><img src="{name}" alt="Original crop, tiled mask and two whole-image prompted masks"><p>Point: {metrics("point")}. Box: {metrics("box")}.</p></article>')
 sections.append(f'<section><h2>Field {n+1}</h2><p>Source image <a href="/{f["image"]}">original middle plane</a>; contextual inference took {row["seconds"]:.2f} seconds on two CPU threads, including one image encoding and {2*len(row["cases"])} queries. Initialization and timing are not benchmarked consistently against R110.</p>{"".join(cards)}</section>')
(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>Tile boundary context experiment</title><style>body{font:16px/1.55 system-ui;color:#1a3b37;background:#f4f6f0;margin:0}main{max-width:1100px;margin:auto;padding:28px}h1,h2,h3{font-family:Georgia,serif}a{color:#146c59}section{margin-top:30px;border-top:1px solid #cddbd2}article,.notice{background:white;border:1px solid #cddbd2;padding:16px;margin:15px 0}.notice{border-left:5px solid #bb861e}img{width:100%;height:auto}</style><body><main><nav><a href="/results/r110/">Previous comparison</a> · <a href="/results/assessment/">Assessment</a> · <a href="/results/board.html">Board</a></nav><h1>Can whole-field context extend tile-edge masks?</h1><p class="notice"><strong>Development diagnostic, not accuracy.</strong> These are 17 unverified model candidates on four previously viewed Academy fields. Extending beyond a tile or retaining its original pixels can also mean including debris, background, or another overlapping object.</p><p>Each orange box shows the tile that produced the original mask. The teal tint shows a single candidate, not a confirmed organism. For each candidate, the same original point and a separately expanded candidate box prompted MobileSAM on the entire middle-plane crop. All 17 cases and both alternatives are shown in original rank order; nothing was selected by a successful outcome. Other original candidates and source planes remain in the <a href="/results/r110/">previous comparison</a>.</p><p>Point prompts extended beyond a contacted edge for 14/17 candidates; expanded boxes for 16/17. “Extended” means at least one pixel past any contacted internal edge. Point masks retained at least 80% of the original mask for 13/17, box masks for 15/17. These geometric counts do not show whether either mask is biologically correct, or how they perform within a fixed review budget.</p><p><a href="/research/R111.md">Research note</a> · <a href="protocol.json">Pre-inference selection and protocol</a> · <a href="results.json">Every prompt and metric</a> · <a href="verify.log">Verification</a></p>'''+''.join(sections)+'''</main></body></html>''')
print('Generated panels:',sum(len(f['cases']) for f in r['records']))
