"""Publish cumulative overlap bound and per-target omission diagnostics."""
import html
import json
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw, ImageOps

R = Path(__file__).resolve().parents[1]
P = R / 'results/r112/gunduz-overlap-pair-pilot'
O = R / 'results/r112/gunduz-cumulative-overlap-pilot'
esc = html.escape


def main():
    results = json.loads((O / 'results.json').read_text())
    check = json.loads((O / 'verify.json').read_text())
    previous = {x['id']: x for x in json.loads((P / 'results.json').read_text())['records']}
    for folder in ('differences', 'strips'):
        (O / folder).mkdir(exist_ok=True)
    cards = []
    for row in results['records']:
        old = previous[row['id']]
        base = np.asarray(Image.open(P / old['frames']['bounded']['file']).convert('L'))
        new = np.asarray(Image.open(O / row['frame']).convert('L'))
        diff = np.abs(base.astype(np.int16) - new.astype(np.int16))
        diff_path = O / 'differences' / (row['id'] + '.png')
        Image.fromarray(np.clip(diff * 5, 0, 255).astype('uint8')).save(diff_path)
        blocks = []
        for i, (target, original) in enumerate(zip(row['targets'], old['targets'])):
            frames = [('Alone', P / original['conditions']['bounded_single']['path'], target['single_top5'][0]['source_name']),
                      ('Previous overlap', P / original['conditions']['bounded_overlap']['path'], target['previous_overlap_top5'][0]['source_name']),
                      ('Cumulative bound', O / target['patch'], target['cumulative_top5'][0]['source_name'])]
            plate = Image.new('RGB', (900, 285), 'white')
            draw = ImageDraw.Draw(plate)
            for j, (label, path, predicted) in enumerate(frames):
                img = ImageOps.contain(Image.open(path).convert('RGB'), (300, 225))
                draw.text((j*300+5, 3), label, fill='black')
                plate.paste(img, (j*300+(300-img.width)//2, 24))
                draw.text((j*300+5, 255), predicted[:39], fill='black')
            path = O / 'strips' / (row['id'] + '-' + str(i) + '.png')
            plate.save(path)
            old_count = row['previous_bounded_metrics']['per_target_marginal'][i]['intersection_unchanged_px']
            new_count = row['cumulative_metrics']['per_target_marginal'][i]['intersection_unchanged_px']
            blocks.append('<h4>Target ' + str(i+1) + ': <i>' + esc(target['source']['source_name']) + '</i></h4><p>Intersection pixels unchanged when this target is removed: ' + str(old_count) + ' → ' + str(new_count) + ' of ' + str(row['cumulative_metrics']['intersection_px']) + '.</p><a href="' + esc(str(path.relative_to(O)), quote=True) + '"><img loading="lazy" src="' + esc(str(path.relative_to(O)), quote=True) + '" alt="Target alone, previous overlap, and cumulative bound crops"></a>')
        cards.append('<article><h3>' + esc(row['id']) + '</h3><p>Factor floor active in ' + str(row['cumulative_metrics']['floor_limited_px']) + ' intersection pixels; factor ceiling active in ' + str(row['cumulative_metrics']['ceiling_limited_px']) + '.</p><div class="views"><figure><a href="/' + esc(str((P / old['frames']['bounded']['file']).relative_to(R)), quote=True) + '"><img loading="lazy" src="/' + esc(str((P / old['frames']['bounded']['file']).relative_to(R)), quote=True) + '" alt="Previous bounded overlap"></a><figcaption>Previous bounded overlap</figcaption></figure><figure><a href="' + esc(row['frame'], quote=True) + '"><img loading="lazy" src="' + esc(row['frame'], quote=True) + '" alt="Cumulative bounded overlap"></a><figcaption>Cumulative bound</figcaption></figure><figure><a href="' + esc(str(diff_path.relative_to(O)), quote=True) + '"><img loading="lazy" src="' + esc(str(diff_path.relative_to(O)), quote=True) + '" alt="Amplified image difference"></a><figcaption>Absolute difference ×5, saturated</figcaption></figure></div>' + ''.join(blocks) + '</article>')
    c = check['all']['states']
    old, new = check['pixel_diagnostics']['previous_bounded'], check['pixel_diagnostics']['cumulative']
    page = '''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Cumulative overlap bound</title><style>body{font:16px/1.5 system-ui;color:#193b37;background:#f2f6f2;margin:0}main{max-width:1300px;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}.views{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px}figure{margin:0}.views img{width:100%}figcaption{font-size:.85rem}table{border-collapse:collapse;background:white;display:block;overflow:auto}td,th{padding:8px;border:1px solid #cbd8d1;text-align:left}@media(max-width:700px){.views{grid-template-columns:1fr}}</style><main><nav><a href="/results/r112/">Synthetic training</a> · <a href="/results/r112/gunduz-overlap-pair-pilot/">Prior overlap comparison</a></nav><h1>Cumulative bound on overlap</h1><p class="notice"><strong>Exploratory follow-up on the same 25 pairs, not validation.</strong> This bound was proposed after seeing the prior test. The source scale, source names, mask associations and optical realism are uncertain; background organisms are not labeled. The numerical probes and forced classifier predictions do not establish biological visibility or Academy accuracy.</p><p>Retained each prior bounded factor and clamped the product to [0.5, 1.5] only where the two supports intersect. Outside that intersection, all output pixels match the previous bounded pair exactly. Source and overlap geometry, background and oracle target crop are unchanged. The bounds are an arbitrary engineering intervention and may flatten or hide specimen structure.</p><table><tr><th>Measure</th><th>Previous bounded layers</th><th>Cumulative bound</th></tr><tr><th>Species-name top 1 (50 targets)</th><td>''' + str(c['previous_overlap']['species_top1']) + '</td><td>' + str(c['cumulative']['species_top1']) + '''</td></tr><tr><th>Both names top 1 (25 pairs)</th><td>''' + str(c['previous_overlap']['both_species_top1']) + '</td><td>' + str(c['cumulative']['both_species_top1']) + '''</td></tr><tr><th>Eligible intersection pixels with less than half response to a +4 background-level probe</th><td>''' + str(old['response_below_half_px']) + ' / ' + str(old['response_eligible_px']) + '</td><td>' + str(new['response_below_half_px']) + ' / ' + str(new['response_eligible_px']) + '''</td></tr><tr><th>Target-role intersection pixels unchanged when that target is removed</th><td>''' + str(old['target_intersection_unchanged_px']) + ' / ' + str(old['target_intersection_pixels']) + '</td><td>' + str(new['target_intersection_unchanged_px']) + ' / ' + str(new['target_intersection_pixels']) + '''</td></tr></table><p>The response probe adds four levels to the background with source factors fixed, clips, then measures the output before rounding; it is not a test of recognizing a background organism. The omission probe removes one generated target, renders the other alone, then counts equal 8-bit pixels in their original intersection. Each intersection is counted once per target role; unchanged pixels can arise for multiple reasons and do not prove anatomical invisibility. The cumulative bound improves one numerical proxy while increasing zero-difference target contributions.</p><p><a href="protocol.json">Frozen follow-up method</a> · <a href="results.json">All crops, scores and measurements</a> · <a href="verify.json">Reconstruction</a> · <a href="replay.json">Four inference replays</a>. Gündüz source data is CC BY-NC-SA 4.0; DIAMORPH identifies AGPL-3.0 and DIATLAS is CC BY 4.0.</p><h2>All 25 pairs</h2><p>Difference images are amplified fivefold and saturated; they are not original specimen contrast.</p>''' + ''.join(cards) + '</main></html>'
    (O / 'index.html').write_text(page)
    print('published', len(cards), 'pair comparisons')


if __name__ == '__main__':
    main()
