"""Publish the paired background and insertion-factor diagnostics."""
import html
import json
from pathlib import Path

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


def preds(row):
    return [('Source', row['source_top5']), ('Actual + all', row['actual_full_top5']),
            ('Actual + target', row['conditions']['actual_target_only']['top5']),
            ('Flat + all', row['conditions']['flat_full']['top5']),
            ('Flat + target', row['conditions']['flat_target_only']['top5'])]


def main():
    result = json.loads((O / 'results.json').read_text())
    verify = json.loads((O / 'verify.json').read_text())
    table = []
    names = [('source', 'Source patch'), ('actual_full', 'Academy background + all insertions'),
             ('actual_target_only', 'Academy background + target only'),
             ('flat_full', 'Flat background + all insertions'),
             ('flat_target_only', 'Flat background + target only')]
    for key, title in names:
        x = verify['summary']['all']['conditions'][key]
        table.append('<tr><th>' + title + '</th><td>' + str(x.get('species_top1', 0)) + '</td><td>' + str(x.get('species_top5', 0)) + '</td><td>' + str(x.get('genus_top1', 0)) + '</td></tr>')
    cards = []
    for row in result['records']:
        tops = ''.join('<li>' + esc(title) + ': <i>' + esc(values[0]['source_name']) + '</i></li>' for title, values in preds(row))
        cards.append('<article><h3>' + esc(row['scene_id']) + ' · instance ' + str(row['instance_index'] + 1) + ' · ' + esc(row['source_id']) + '</h3><p>Source name: <i>' + esc(row['source_name']) + '</i> · exact name in model vocabulary: ' + ('yes' if row['name_in_model_vocabulary_exact'] else 'no') + ' · other inserted-support overlaps: ' + str(row['overlap_other_projected_supports']) + ' · support in frame: ' + f"{row['in_frame_fraction']*100:.1f}%" + '</p><a href="' + esc(row['comparison'], quote=True) + '"><img loading="lazy" src="' + esc(row['comparison'], quote=True) + '" alt="Five paired source, background and overlap comparisons"></a><details><summary>Top model predictions</summary><ul>' + tops + '</ul></details></article>')
    changed = verify['crop_difference_counts']
    page = '''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Synthetic scene factor comparison</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/r112/gunduz-species-retention/">Previous paired comparison</a></nav><h1>Background and overlap factor comparison</h1><p class="notice"><strong>Small, reused development diagnostic; not an accuracy or biological visibility test.</strong> Source names and masks are not independently adjudicated, the source physical scale is unknown, crops use known synthetic supports, and the frozen model must choose a class. Real background organisms remain unlabeled. These results do not establish Academy performance or physically realistic microscopy.</p><p>For all 51 prior insertions, kept the same source, position, transform, opacity, contrast and oracle crop. Compared the existing scene, target alone on the same Academy background, all insertions on a constant field, and target alone on that constant field. The constant value is the median gray level of the original field; the multiplicative renderer remains unchanged. Flat versus real changes texture, underlying organisms and intensity interactions together, so the comparison does not isolate one physical mechanism.</p><table><tr><th>Condition</th><th>Exact species top 1 / 51</th><th>Exact species top 5 / 51</th><th>Exact genus top 1 / 51</th></tr>''' + ''.join(table) + '''</table><p>Removing other insertions on the Academy background changed the top code for 24 cases and increased exact top-one source-name matches from 2 to 3. Replacing the Academy background with a flat field for target-only crops changed the top code for 40 cases and increased matches from 3 to 9. This indicates sensitivity of this classifier and rendering combination; it does not show that a real diatom became unreadable or that a flat synthetic background is realistic. Only 35 of the 51 recorded names occur exactly in the model vocabulary; synonym and concept differences remain unresolved.</p><p>Removing other insertions altered ''' + str(changed['actual_full_vs_target_different']) + ''' of 51 crop arrays. In ''' + str(changed['no_overlap_crops_changed_by_others']) + ''' cases, the crop changed even though projected target support did not intersect another support, because other insertions could enter the surrounding rectangle. The source crop and all rendered crops share the same dimensions and location, but source and composite backgrounds differ.</p><p><a href="protocol.json">Frozen protocol</a> · <a href="results.json">All predictions and patches</a> · <a href="verify.json">Render and summary checks</a> · <a href="replay.json">Nine inference replays</a>. Gündüz source content is CC BY-NC-SA 4.0; the DIAMORPH checkpoint identifies AGPL-3.0 and DIATLAS is CC BY 4.0; retain applicable attribution and license terms.</p><h2>All paired conditions</h2>''' + ''.join(cards) + '</main></html>'
    (O / 'index.html').write_text(page)
    print('published', len(cards), 'five-condition comparisons')


if __name__ == '__main__':
    main()
