"""Publish contrast-gain predictions and pre-round clipping diagnostics."""
import html
import json
from pathlib import Path

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


def main():
    result = json.loads((O / 'results.json').read_text())
    check = json.loads((O / 'verify.json').read_text())
    stats = check['summary']['all']['conditions']
    clipping = check['clipping']
    rows = []
    for key, label in [('source', 'Transformed source'), ('gain-1', 'Gain 1 (baseline)'),
                       ('gain-1p5', 'Gain 1.5'), ('gain-2', 'Gain 2'), ('gain-3', 'Gain 3')]:
        c = stats[key]
        info = clipping.get(key)
        clipped = '—' if info is None else str(info['cases_with_new_clipping']) + ' / ' + str(info['cases_new_clipping_gt_5pct_support'])
        rows.append('<tr><th>' + label + '</th><td>' + str(c.get('species_top1', 0)) + '</td><td>' + str(c.get('species_top5', 0)) + '</td><td>' + str(c.get('genus_top1', 0)) + '</td><td>' + clipped + '</td></tr>')
    cards = []
    for x in result['records']:
        info = []
        for key in ('gain-1p5', 'gain-2', 'gain-3'):
            g = x['gains'][key]
            frac = 100 * g['newly_out_of_range_vs_gain1_px'] / x['baseline_metrics']['support_px']
            info.append('<li>' + esc(key) + ': ' + esc(g['top5'][0]['source_name']) + '; newly out of range ' + f'{frac:.1f}%' + ' of support</li>')
        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 vocabulary match: ' + ('yes' if x['name_in_model_vocabulary_exact'] else 'no') + '</p><a href="' + esc(x['comparison'], quote=True) + '"><img loading="lazy" src="' + esc(x['comparison'], quote=True) + '" alt="Source and four target-only contrast gain variants"></a><details><summary>Predictions and clipping</summary><p>Gain 1 top prediction: ' + esc(x['baseline_top5'][0]['source_name']) + '</p><ul>' + ''.join(info) + '</ul></details></article>')
    page = '''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Target contrast gain 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-scene-factor-pilot/">Background factor comparison</a></nav><h1>Target contrast gain comparison</h1><p class="notice"><strong>Promising model sensitivity, not a validated renderer.</strong> Higher gain amplifies noise and can obscure real background organisms or clip structures. Source physical scale, optical realism, names, component associations and species accuracy remain unverified. The cases are previously used development examples, and the classifier is forced to choose a class.</p><p>For each of the same 51 target-only crops over its Academy background, kept the object, position, crop, opacity and contrast exponent fixed while multiplying the existing intensity-factor residual by 1, 1.5, 2 or 3. Gain 1 reproduces the prior target-only result exactly. Outside the target support, Academy background pixels stay unchanged; they remain unlabelled inside and outside the support. All comparisons use the same frozen DIAMORPH classifier.</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><th>Cases with any new out-of-range pixels / cases with &gt;5% support newly out of range</th></tr>''' + ''.join(rows) + '''</table><p>At gain 3, exact top-one matches rose from 3 to 9, while 21/51 cases had newly out-of-range values in more than 5% of their support before clipping to 8-bit. A correct-looking forced prediction or a stronger image does not prove species detail was preserved; 16 source names are not exact matches to the model vocabulary. At gain 3, 29 crops contain negative pre-round intensities inside the support; these values are clipped and do not form a physically valid transparency model. No gain has been approved for training.</p><p><a href="protocol.json">Fixed comparison</a> · <a href="results.json">All crops and predictions</a> · <a href="verify.json">Reconstruction, counts and clipping</a> · <a href="replay.json">Nine inference replays</a>. Source content is CC BY-NC-SA 4.0; DIAMORPH identifies AGPL-3.0 and DIATLAS is CC BY 4.0. Preserve applicable terms.</p><h2>All paired crops</h2>''' + ''.join(cards) + '</main></html>'
    (O / 'index.html').write_text(page)
    print('published', len(cards), 'five-condition comparisons')


if __name__ == '__main__':
    main()
