"""Publish bounded-factor classifier and background-response diagnostics."""
import html
import json
from pathlib import Path

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


def main():
    result = json.loads((O / 'results.json').read_text())
    check = json.loads((O / 'verify.json').read_text())
    stats, pixels = check['summary']['all']['conditions'], check['pixel_diagnostics']
    labels = [('source', 'Transformed source'), ('baseline', 'Original factor'),
              ('unbounded-3', 'Unbounded linear gain 3'), ('bounded-1p5', 'Bounded exponent 1.5'),
              ('bounded-2', 'Bounded exponent 2'), ('bounded-3', 'Bounded exponent 3')]
    table = []
    for key, label in labels:
        s, p = stats[key], pixels.get(key)
        clipped = '—' if p is None else f"{100 * p['pre_round_out_of_range_px'] / p['support_px']:.2f}%"
        low = '—' if p is None else f"{100 * p['response_below_half_px'] / p['response_eligible_px']:.2f}%"
        table.append('<tr><th>' + label + '</th><td>' + str(s.get('species_top1', 0)) + '</td><td>' + str(s.get('species_top5', 0)) + '</td><td>' + str(s.get('genus_top1', 0)) + '</td><td>' + clipped + '</td><td>' + low + '</td></tr>')
    cards = []
    for row in result['records']:
        details = []
        for key in ('bounded-1p5', 'bounded-2', 'bounded-3'):
            x = row['bounded'][key]
            m = x['metrics']
            details.append('<li>' + esc(key) + ': ' + esc(x['top5'][0]['source_name']) + ' · pre-round out of range ' + str(m['pre_round_out_of_range_px']) + ' pixels · limited at factor floor ' + str(m['floor_limited_px']) + ' pixels</li>')
        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> · support pixels: ' + str(row['support_px']) + '</p><a href="' + esc(row['comparison'], quote=True) + '"><img loading="lazy" src="' + esc(row['comparison'], quote=True) + '" alt="Baseline, unbounded and bounded contrast variants"></a><details><summary>Predictions and limits</summary><ul>' + ''.join(details) + '</ul></details></article>')
    page = '''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Bounded transmission 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-contrast-gain-pilot/">Unbounded gain comparison</a></nav><h1>Bounded multiplicative contrast</h1><p class="notice"><strong>Development experiment, not verified optics or species accuracy.</strong> These 51 previously used source crops have unknown physical scale, unverified source names and component links, and oracle crop locations. The background can contain real diatoms. The factor bounds are arbitrary engineering constraints and may distort specimens or background; no variant is approved for training.</p><p>Starting from the original positive insertion factor <i>f</i>, tested <i>clip(f<sup>g</sup>, 0.5, 1.5)</i> for exponents 1.5, 2 and 3 on the same target-only Academy backgrounds. This avoids negative factors and limits pre-clipping attenuation, while allowing the original background everywhere outside the support. It does not guarantee that structures under the support remain recognizable. All classifier comparisons use the same frozen DIAMORPH model and exact source-name matching.</p><table><tr><th>Condition</th><th>Species top 1 / 51</th><th>Species top 5 / 51</th><th>Genus top 1 / 51</th><th>Support pixels out of range before rounding</th><th>Eligible support pixels with &lt; half response to +4 background levels</th></tr>''' + ''.join(table) + '''</table><p>The last column is a controlled mathematical proxy: with the source factor fixed, add four intensity levels to a background pixel and measure the output change after clipping but before rounding, excluding original backgrounds above 251. It is not a measurement of visibility or recognition of a real overlapping diatom. The percentages pool pixels across specimens; large supports carry more weight. Bounding can reduce the proxy's suppression while also flattening source contrast. Clipping and 8-bit rounding can still erase differences.</p><p>For bounded exponent 3, ''' + str(pixels['bounded-3']['floor_limited_px']) + ''' support pixels hit the lower factor bound and ''' + str(pixels['bounded-3']['pre_round_out_of_range_px']) + ''' were out of the 0–255 range before final clipping. The original unbounded gain 3 produced ''' + str(pixels['unbounded-3']['negative_pre_round_px']) + ''' negative pre-round pixels. The bounded variant matched 7 source names at top one, versus 3 for the original factor and 9 for unbounded gain 3; these are small, paired model outputs, not validated species identifications.</p><p><a href="protocol.json">Frozen protocol</a> · <a href="results.json">All crops and predictions</a> · <a href="verify.json">Reconstruction and pixel diagnostics</a> · <a href="replay.json">Nine inference replays</a>. Source material is CC BY-NC-SA 4.0, DIAMORPH identifies AGPL-3.0 and DIATLAS is CC BY 4.0; applicable attribution and license terms remain.</p><h2>All paired crops</h2>''' + ''.join(cards) + '</main></html>'
    (O / 'index.html').write_text(page)
    print('published', len(cards), 'bounded-factor comparisons')


if __name__ == '__main__':
    main()
