"""Render R98 with corrected historical-panel labels and per-target first matches."""
import hashlib,html,json
from pathlib import Path
import numpy as np
from PIL import Image,ImageDraw
R=Path(__file__).resolve().parents[1];O=R/'results/r98';d=json.loads((O/'results.json').read_text());rows=d['records'];methods=('confidence','sam_quality','history_grid256');total=sum(x['references'] for x in rows);tables=[]
for t in ('0.5','0.75'):
 for n in ('5','10','20','30'):
  vals=[sum(x['scores'][m][n][t]['matched'] for x in rows) for m in methods];tables.append(f'<tr><td>{t}</td><td>{n}</td>'+''.join(f'<td>{v}/{total}</td>' for v in vals)+'</tr>')
cards=[];rankrecords=[];derived=[]
for r in rows:
 z=np.load(O/r['archive']);shape=tuple(z['sam_shape']);sm=np.unpackbits(z['sam_bits'])[:np.prod(shape)].reshape(shape).astype(bool);ranks={'confidence':list(range(len(sm))),'sam_quality':z['quality_order'].tolist()};first={}
 for name,order in ranks.items():
  first[name]=[]
  for ref in z['refs']:
   best=None
   for pos,j in enumerate(order,1):
    inter=np.count_nonzero(ref&sm[j]);union=np.count_nonzero(ref|sm[j]);iou=inter/union if union else 0
    if iou>=.5:best=pos;break
   first[name].append(best)
 rankrecords.append({'index':r['index'],'reference_ids':z['ids'].tolist(),'first_rank_iou_0.5':first,'note':'Per-reference first hit may reuse a candidate and is not one-to-one recovery.'})
 img=Image.open(O/r['image']).convert('RGB');draw=ImageDraw.Draw(img);draw.rectangle((900,0,1199,27),fill='white');draw.text((905,8),'R87 point-grid SAM top 30',fill='#203a38');new=f"field-{r['index']:02d}-labeled.png";img.save(O/new);derived.append({'source':r['image'],'source_sha256':r['image_sha256'],'derived':new,'derived_sha256':hashlib.sha256((O/new).read_bytes()).hexdigest(),'edit':'Replace incorrect last-panel text with R87 point-grid SAM top 30; image pixels below label unchanged.'});counts=[r['scores'][m]['10']['0.5']['matched'] for m in methods];cards.append(f'<section><h2>Field {r["index"]:02d}</h2><p>Top 10 matches at 0.5: confidence / SAM quality / point-grid {" / ".join(map(str,counts))} of {r["references"]}. First-hit ranks in the two paired-mask orderings: {html.escape(str(first))}; separate targets can share one candidate.</p><a href="{new}"><img loading="lazy" src="{new}" alt="Source regions, YOLO masks, paired SAM masks and point-grid masks"></a><p><a href="/{html.escape(r["source"])}">Original RGB</a> · <a href="{r["archive"]}">Saved masks and boxes</a></p></section>')
(O/'first-hit-ranks.json').write_text(json.dumps({'records':rankrecords,'warning':'Reference-assisted individual first-hit ranks; candidates may be reused, not simultaneous matches.'},indent=2)+'\n');(O/'figure-provenance.json').write_text(json.dumps(derived,indent=2)+'\n')
(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>R98 quality-ranking replay</title><style>body{font:16px/1.5 system-ui;color:#18342f;max-width:1200px;margin:2em auto;padding:0 1em}a{color:#006b59}img{width:100%}table{border-collapse:collapse}td,th{border:1px solid #bbc;padding:.4em}.warn{background:#fff2d6;padding:1em}section{border-top:1px solid #ccd}</style><a href="/results/board.html">Research board</a> · <a href="/results/l85/">Prior ranking study</a><h1>R98: Frozen candidate ranking on additional files</h1><p class="warn">These 13 fields were previously viewed and come from an archive also used for some training; distinct files are not established distinct slides or specimens. Known source polygons in this selection do not represent severe overlaps. This is not a test of real severe-overlap or human-level segmentation.</p><p>From 16 R87 fields chosen before this run, three were quarantined under the frozen visual-similarity rule. Remaining fields have 24 annotated polygons. Same per-box SAM masks are ordered by original YOLO box confidence or SAM predicted mask quality, with no reference-guided selection. An earlier 256-point grid SAM stream is shown as a separately computed baseline; the methods use different proposals and compute.</p><table><tr><th>IoU ≥</th><th>Mask budget per field</th><th>YOLO confidence</th><th>SAM quality</th><th>256-point SAM</th></tr>'''+''.join(tables)+'''</table><p>At top 10 and IoU 0.5, the quality ranking did not repeat its earlier advantage. Top 30 has the same paired-mask pool under both orderings. The grid baseline matched more regions in this group, but its 256 prompts and different proposal procedure are not an equal-compute comparison.</p><p>YOLO reached its 100-output cap in four fields and produced 388 SAM box prompts. The labels may omit organisms, so candidate counts are not false-positive counts; NMS and the cap can hide proposals. There are no established complete real severe-overlap groups here. Screening compares known annotated crops against training and earlier source regions, but cannot prove biological independence or exclude unannotated background similarity.</p><p>Screening reran byte-identically; all retained archive hashes, selection, ranks and scores were reconstructed using a shared matcher. Neural inference was not repeated. The per-target first-hit ranks below are reference-assisted and can reuse a candidate; they do not represent simultaneous one-to-one recovery. Original image overlays had the wrong historical-panel title; these derived images correct only that text, and both original and derived hashes are documented.</p><p><a href="protocol.json">Protocol</a> · <a href="source-screen.json">Source screen</a> · <a href="results.json">Scores and rankings</a> · <a href="first-hit-ranks.json">First-hit ranks</a> · <a href="verify.log">Verification</a> · <a href="figure-provenance.json">Figure label corrections</a> · <a href="/research/R98.md">Research note</a></p>'''+''.join(cards)+'</html>')
