"""Publish paired species-classifier diagnostic results and examples."""
import html
import json
from pathlib import Path

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


def main():
    results = json.loads((O / 'results.json').read_text())
    summary = json.loads((O / 'verify.json').read_text())['summary']
    rows = []
    for key, title in [('all', 'All insertions'), ('exact_vocabulary', 'Exact name in model vocabulary'),
                       ('support_in_frame_ge_095', 'At least 95% support in frame'),
                       ('overlap', 'Inserted supports overlap'), ('no_inserted_support_overlap', 'No inserted-support overlap')]:
        x = summary[key]
        rows.append('<tr><th>' + title + '</th><td>' + str(x['cases']) + '</td><td>' + str(x['source_top1']) + ' → ' + str(x['composite_top1']) + '</td><td>' + str(x['source_top5']) + ' → ' + str(x['composite_top5']) + '</td><td>' + str(x['source_genus_top1']) + ' → ' + str(x['composite_genus_top1']) + '</td><td>' + str(x['same_top1_code']) + '</td></tr>')
    cards = []
    for x in results['records']:
        original, composite = x['source_top5'][0], x['composite_top5'][0]
        details = []
        for label, key in [('Source', 'source_top5'), ('Composite', 'composite_top5')]:
            names = ', '.join(esc(v['source_name']) + ' (' + f"{v['score']:.3f}" + ')' for v in x[key])
            details.append('<p><strong>' + label + ' top five:</strong> ' + names + '</p>')
        cards.append('<article><h3>' + esc(x['scene_id']) + ' · instance ' + str(x['instance_index'] + 1) + ' · ' + esc(x['source_id']) + '</h3><p>Source name: <i>' + esc(x['source_name']) + '</i> · exact name in model vocabulary: ' + ('yes' if x['name_in_model_vocabulary_exact'] else 'no') + ' · projected overlaps: ' + str(x['overlap_other_projected_supports']) + ' · support in frame: ' + f"{100*x['in_frame_fraction']:.1f}%" + '</p><p>Top prediction: ' + esc(original['source_name']) + ' → ' + esc(composite['source_name']) + '</p><a href="' + esc(x['comparison'], quote=True) + '"><img loading="lazy" src="' + esc(x['comparison'], quote=True) + '" alt="Transformed source and synthetic composite crop"></a><details><summary>Show top five and native crops</summary>' + ''.join(details) + '<p><a href="' + esc(x['source_patch'], quote=True) + '">Source patch</a> · <a href="' + esc(x['composite_patch'], quote=True) + '">Composite patch</a></p></details></article>')
    page = '''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Species prediction changes in synthetic scenes</title><style>body{font:16px/1.5 system-ui;color:#193b37;background:#f2f6f2;margin:0}main{max-width:1100px;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{max-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/r112/gunduz-uncalibrated-scenes/">Nine source-component fields</a></nav><h1>Species prediction changes after compositing</h1><p class="notice"><strong>Development diagnostic, not species accuracy.</strong> These 51 previously used specimens have unverified source names and component associations; the model is forced to pick from its vocabulary, the source scale is unknown, and location is supplied by the projected support. Composites can contain real background diatoms and other insertions. These counts do not measure Academy or end-to-end performance, and a prediction change does not prove loss of biological information.</p><p>For each of the 51 insertions, the source patch and composite patch have the same oracle support-derived rectangle after resizing and rotation. Both were passed to the same frozen DIAMORPH classifier using identical digital preprocessing. The inserted source's physical scale is unknown, so using the Academy background grid in preprocessing does not establish a correctly calibrated source specimen. The two patches differ in background, blending and possible overlap, not solely in a single image feature.</p><table><tr><th>Subset</th><th>Cases</th><th>Exact species top 1: source → composite</th><th>Exact species top 5: source → composite</th><th>Exact genus top 1: source → composite</th><th>Same top code</th></tr>''' + ''.join(rows) + '''</table><p>Exact-name matching does not reconcile synonyms or taxonomic concepts. Of 51 source patches, 14 top predictions matched the recorded source name; two matched after compositing. Twelve source matches changed to nonmatches, while two stayed matched. Only 35 source names had an exact model-vocabulary match. The classifier's prior data overlap and the biological independence of specimens are unknown; source and composite counts are paired development observations, not a generalization estimate.</p><p><a href="protocol.json">Frozen comparison</a> · <a href="results.json">All predictions and crops</a> · <a href="verify.json">Patch and summary checks</a> · <a href="replay.json">Six inference replays</a>. Source data: Gündüz Diatom Dataset, CC BY-NC-SA 4.0; the DIAMORPH checkpoint identifies AGPL-3.0 and its DIATLAS source is CC BY 4.0. Review terms for any downstream reuse.</p><h2>All paired crops</h2>''' + ''.join(cards) + '</main></html>'
    (O / 'index.html').write_text(page)
    print('published', len(cards), 'paired comparisons')


if __name__ == '__main__':
    main()
