"""Publish cross-source comparison and neighboring-polygon diagnostics."""
import html
import json
from pathlib import Path

R = Path(__file__).resolve().parents[1]
O = R / 'results/r118'
esc = html.escape


def main():
    result = json.loads((O / 'results.json').read_text())
    stats = json.loads((O / 'verify.json').read_text())['summary']
    audit = json.loads((O / 'other-polygon-audit.json').read_text())
    neighbors = {x['id']: x for x in audit['records']}
    sections = []
    for group, title in [('khanom', 'Previously used Khanom polygon crops'), ('ude', 'Previously used difficult UDE crops')]:
        cards = []
        for x in result['records']:
            if x['group'] != group:
                continue
            a, b = x['outputs']['original'], x['outputs']['adapted']
            if group == 'khanom':
                metric = 'Source polygon IoU: ' + f"{a['reference_iou']:.3f}" + ' → ' + f"{b['reference_iou']:.3f}"
                extra = neighbors[x['id']]['other_polygons']
                details = ''.join('<li>Other source polygon ' + str(y['source_annotation_id']) + ': ' + str(y['other_exclusive_pixels_in_crop']) + ' pixels in crop; original/adapted hit ' + str(y['original_hit_pixels']) + ' / ' + str(y['adapted_hit_pixels']) + '</li>' for y in extra)
                details = '<details><summary>Other published polygons in crop</summary><ul>' + (details or '<li>None recorded in crop.</li>') + '</ul></details>'
            else:
                metric = 'Crop fraction covered: ' + f"{100*a['crop_fraction']:.1f}%" + ' → ' + f"{100*b['crop_fraction']:.1f}%" + ' (no reference mask)'
                details = ''
            cards.append('<article><h3>' + esc(x['id']) + ' · ' + esc(x['source_name']) + '</h3><p>' + metric + '</p><a href="' + esc(x['comparison'], quote=True) + '"><img loading="lazy" src="' + esc(x['comparison'], quote=True) + '" alt="Source, reference when available, original and adapted masks"></a>' + details + '</article>')
        sections.append('<h2>' + title + '</h2>' + ''.join(cards))
    kh, ude, n = stats['khanom'], stats['ude'], audit['summary']
    page = '''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Adapted decoder source transfer</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;display:block;overflow:auto}td,th{padding:8px;border:1px solid #cbd8d1;text-align:left}</style><main><nav><a href="/results/r112/">Synthetic training</a> · <a href="/results/r117/">Decoder adaptation</a> · <a href="/research/R118.md">Research note</a></nav><h1>Adapted decoder on other source crops</h1><p class="notice"><strong>Do not promote the adapted decoder.</strong> This is a previously viewed, non-independent development comparison. Khanom crops and clicks come from the published polygons, which are not established biological ground truth. UDE has no verified instance reference. Neither set measures automatic detection or Academy overlap accuracy.</p><p>Re-ran original MobileSAM and the R117 adapted decoder on the same fixed center points and grayscale crops: 29 Khanom source polygons and 36 selected UDE crops. The original rerun exactly reproduced the saved center masks for all 65. On Khanom, the adapted decoder's stricter agreement with the source polygons fell:</p><table><tr><th>Measure against published polygon</th><th>Original</th><th>R117 adapted</th></tr><tr><th>IoU ≥0.50</th><td>''' + str(kh['original_iou_ge_05']) + ''' / 29</td><td>''' + str(kh['adapted_iou_ge_05']) + ''' / 29</td></tr><tr><th>IoU ≥0.75</th><td>''' + str(kh['original_iou_ge_075']) + ''' / 29</td><td>''' + str(kh['adapted_iou_ge_075']) + ''' / 29</td></tr><tr><th>Mean IoU</th><td>''' + f"{kh['original_mean_iou']:.3f}" + '</td><td>' + f"{kh['adapted_mean_iou']:.3f}" + '''</td></tr></table><p>In ''' + str(n['cases_with_other_polygons_in_crop']) + ''' crops with another published polygon portion, the original covered at least half of a portion of at least 50 pixels in ''' + str(n['original_cases_cover_half_other_portion_ge_50']) + ''' case; the adapted decoder did so in ''' + str(n['adapted_cases_cover_half_other_portion_ge_50']) + '''. This is an arbitrary post-hoc geometry diagnostic, not an expert merge rate: polygons can be truncated and unannotated organisms are unknown. <a href="comparisons/khanom-f06-a51.png">One visible example</a> shows the adapted mask extending onto a neighboring source-labeled object. The source polygons in this selection do not establish real overlapping valves.</p><p>In the UDE sample, the same ''' + str(ude['original_coverage_gt_075']) + ''' / 36 crops had both original and adapted masks covering more than 75% of the crop. Coverage alone is not an error label; the known failure examples still require inspection. The pink mark is the supplied center prompt.</p><p><a href="protocol.json">Fixed comparison</a> · <a href="results.json">All masks and measurements</a> · <a href="other-polygon-audit.json">Neighbor-polygon audit</a> · <a href="verify.json">Checks</a> · <a href="replay.json">Eight inference replays</a>. Gündüz source-derived adaptation has CC BY-NC-SA 4.0 obligations; Khanom source is CC BY 4.0. Review model and dependency terms for reuse.</p>''' + ''.join(sections) + '</main></html>'
    (O / 'index.html').write_text(page)
    print('published', len(result['records']), 'cross-source comparisons')


if __name__ == '__main__':
    main()
