"""Publish a browseable, source-name grouped gallery of the extension."""
import collections
import html
import json
import statistics
from pathlib import Path

R = Path(__file__).resolve().parents[1]
O = R / 'results/r112/species-breadth-extension'
esc = html.escape


def main():
    selection = json.loads((O / 'selection.json').read_text())
    assets = json.loads((O / 'assets.json').read_text())
    verify = json.loads((O / 'verify.json').read_text())
    assert verify['assets_checked_pixel_for_pixel'] == len(assets['records'])
    groups = collections.defaultdict(list)
    for r in assets['records']:
        groups[r['source_species']].append(r)
    before, after = selection['before_by_name'], selection['after_by_name']
    cards = []
    for name in sorted(groups):
        items = []
        for row in groups[name]:
            label = esc(row['annotation_id'])
            items.append('<figure><a href="' + esc(row['source_crop'], quote=True) + '"><img loading="lazy" src="' + esc(row['source_crop'], quote=True) + '" alt="Source crop ' + label + '"></a><figcaption>' + label + ' · ' + esc(row['source_slide_group']) + '</figcaption></figure>')
        cards.append('<details><summary><i>' + esc(name) + '</i>: ' + str(before[name]) + ' → ' + str(after[name]) + ' training-location crops (' + str(len(items)) + ' added)</summary><div class="grid">' + ''.join(items) + '</div></details>')
    page = '''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Additional species source crops</title><style>body{font:16px/1.5 system-ui;color:#193b37;background:#f2f6f2;margin:0}main{max-width:1200px;margin:auto;padding:24px}a{color:#076c59}.notice{background:#fff4d7;border-left:5px solid #b88418;padding:15px}details{background:white;border:1px solid #cbd8d1;margin:10px 0;padding:12px}summary{cursor:pointer}.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:10px}figure{margin:8px 0;overflow-wrap:anywhere}img{width:100%;height:160px;object-fit:contain;background:#e7ece7}figcaption{font-size:.75rem}</style><main><nav><a href="/results/r112/">Synthetic training</a> · <a href="/results/r112/species-breadth/">Earlier breadth library</a></nav><h1>Additional species source crops</h1><p class="notice"><strong>Development candidates, not approved training labels.</strong> Source names have not been independently reconciled; images may include other diatoms and have no verified instance masks. Filename-derived location groups do not prove specimens are independent. This gallery is not a real-slide species performance test.</p><p>These ''' + str(len(assets['records'])) + ''' additional grayscale UDE crops extend ''' + str(len(groups)) + ''' of the 137 earlier source-name strings, using only the earlier training-location components. Including the 784 prior eligible crops, those 137 names now have ''' + str(sum(after.values())) + ''' crops; the median per name changed from ''' + str(statistics.median(before.values())) + ' to ' + str(statistics.median(after.values())) + '''. Some names remain very sparse. Candidates are selected by metadata with per-location and per-slide caps; nominal UDE scale is 0.09 µm/pixel.</p><p><a href="selection.json">Frozen selection</a> · <a href="assets.json">Image provenance</a> · <a href="verify.json">Pixel and partition checks</a> · <a href="mask-hypotheses/">Inspect candidate mask proposals</a>. Expand any source name to inspect its new crops.</p>''' + ''.join(cards) + '</main></html>'
    (O / 'index.html').write_text(page)
    print('published', len(assets['records']), 'crops across', len(groups), 'names')


if __name__ == '__main__':
    main()
