"""Publish the GrabCut versus MobileSAM source-proxy development comparison."""
import html
import json
from pathlib import Path

R = Path(__file__).resolve().parents[1]
O = R / 'results/r112/grabcut-source-pilot'
esc = html.escape


def main():
    results = json.loads((O / 'results.json').read_text())
    summary = json.loads((O / 'verify.json').read_text())['summary']
    sections = []
    for group, title in [('ude', 'UDE crops: no instance reference'),
                         ('khanom', 'Khanom published polygon proxies'),
                         ('gunduz', 'Gündüz source-component proxies')]:
        cards = []
        for row in results['records']:
            if row['group'] != group:
                continue
            score = '' if group == 'ude' else ' · source-reference IoU: MobileSAM ' + f"{row['center_reference_iou']:.3f}" + ', GrabCut ' + f"{row['grabcut_reference_iou']:.3f}"
            cards.append('<article><h3>' + esc(row['id']) + ' ' + esc(row['source_name']) + '</h3><p>MobileSAM area ' + str(row['center_area_px']) + ' pixels · GrabCut ' + str(row['candidate_area_px']) + ' pixels' + score + '</p><a href="' + esc(row['comparison'], quote=True) + '"><img loading="lazy" src="' + esc(row['comparison'], quote=True) + '" alt="Source, original and GrabCut overlays with source reference when available"></a></article>')
        sections.append('<h2>' + title + '</h2>' + ''.join(cards))
    a, b, c = (summary[x] for x in ('ude', 'khanom', 'gunduz'))
    page = '''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>GrabCut source boundary pilot</title><style>body{font:16px/1.5 system-ui;color:#193b37;background:#f2f6f2;margin:0}main{max-width:1250px;margin:auto;padding:24px}a{color:#076c59}.notice{background:#fff4d7;border-left:5px solid #b88418;padding:15px}article{background:white;border:1px solid #cbd8d1;padding:12px;margin:14px 0}img{width:100%;height:auto}table{border-collapse:collapse;background:white}td,th{padding:8px;border:1px solid #cbd8d1}</style><main><nav><a href="/results/r112/">Synthetic training</a> · <a href="/results/r112/local-decoder-source-pilot/">Adapted decoder comparison</a></nav><h1>Rough-region GrabCut pilot</h1><p class="notice"><strong>Not a validated extraction policy.</strong> GrabCut collapses to a very small region in many UDE crops, including a known failure. The reference comparisons use previously viewed data, annotation-derived crops and points, and tight reference-derived boxes. Reference masks are not confirmed expert boundaries. No result is promoted to a label.</p><p>GrabCut was initialized with a rough region and a small definite-foreground seed at the existing point. Outside the region was treated as background for this experiment, even though it can contain real diatoms. UDE regions are rough rotated source rectangles; proxy regions are tight boxes derived from the source reference masks. The proxy boxes give GrabCut privileged information.</p><p>On the 36 UDE crops, ''' + str(a['candidate_area_le_1pct_crop']) + ''' GrabCut masks cover at most 1% of the crop; this is a size statistic, not an error rate. On the 29 Khanom references, MobileSAM and GrabCut match ''' + str(b['center_iou_ge_05']) + '/29 and ' + str(b['grabcut_iou_ge_05']) + '''/29 at IoU ≥0.5. On the 20 Gündüz component proxies, they match ''' + str(c['center_iou_ge_05']) + '/20 and ' + str(c['grabcut_iou_ge_05']) + '''/20. These are small source-dependent proxy comparisons, not independent Academy performance; source-reference correctness and sample independence are unknown.</p><p><a href="protocol.json">Frozen protocol</a> · <a href="results.json">All records and masks</a> · <a href="verify.json">File and geometry checks</a></p><p>Pink crosses show the positive seed; blue indicates support and orange its edge. Source panels are resized for display. Gündüz source data is CC BY-NC-SA 4.0; source derivatives retain applicable noncommercial and share-alike terms.</p>''' + ''.join(sections) + '</main></html>'
    (O / 'index.html').write_text(page)
    print('published', len(results['records']), 'comparisons')


if __name__ == '__main__':
    main()
