"""Publish paired overlap diagnostics, source outlines and classifier crops."""
import html
import json
from pathlib import Path

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

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


def main():
    result = json.loads((O / 'results.json').read_text())
    check = json.loads((O / 'verify.json').read_text())
    for folder in ('overlays', 'strips'):
        (O / folder).mkdir(exist_ok=True)
    cards = []
    for pair in result['records']:
        with np.load(O / pair['supports'], allow_pickle=False) as z:
            shape = tuple(z['support_shape'])
            masks = np.unpackbits(z['support_bits'], count=int(np.prod(shape))).reshape(shape).astype('uint8')
        overlay = Image.open(O / pair['frames']['bounded']['file']).convert('RGB')
        draw = ImageDraw.Draw(overlay)
        for j, mask in enumerate(masks):
            color = ('#ff5757', '#59d1ff')[j]
            contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
            for contour in contours:
                pts = [tuple(int(a) for a in point[0]) for point in contour]
                if len(pts) > 1:
                    draw.line(pts + [pts[0]], fill=color, width=2)
            ys, xs = np.nonzero(mask)
            draw.text((int(np.median(xs)), int(np.median(ys))), str(j + 1), fill=color, stroke_width=1, stroke_fill='black')
        overlay_path = O / 'overlays' / (pair['id'] + '.png')
        overlay.save(overlay_path)
        target_blocks = []
        for j, target in enumerate(pair['targets']):
            strip = Image.new('RGB', (1000, 270), 'white')
            draw = ImageDraw.Draw(strip)
            fields = [('baseline_single', 'Original · alone'), ('baseline_overlap', 'Original · overlap'),
                      ('bounded_single', 'Bounded · alone'), ('bounded_overlap', 'Bounded · overlap')]
            text = []
            for k, (key, title) in enumerate(fields):
                item = target['conditions'][key]
                patch = ImageOps.contain(Image.open(O / item['path']).convert('RGB'), (250, 200))
                draw.text((k*250+4, 2), title, fill='black')
                strip.paste(patch, (k*250+(250-patch.width)//2, 24))
                draw.text((k*250+4, 230), item['top5'][0]['source_name'][:32], fill='black')
                text.append('<li>' + esc(title) + ': ' + esc(item['top5'][0]['source_name']) + '</li>')
            path = O / 'strips' / (pair['id'] + '-' + str(j) + '.png')
            strip.save(path)
            target_blocks.append('<h4>Target ' + str(j + 1) + ': <i>' + esc(target['source']['source_name']) + '</i></h4><p>Exact name in vocabulary: ' + ('yes' if target['source_name_in_model_vocabulary_exact'] else 'no') + ' · projected support intersection: ' + f"{target['intersection_fraction']*100:.1f}%" + '</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 and overlapping under two rendering variants"></a><details><summary>Top predictions</summary><ul>' + ''.join(text) + '</ul></details>')
        cards.append('<article><h3>' + esc(pair['id']) + '</h3><p>Two inserted supports intersect in ' + str(pair['intersection_px']) + ' pixels. The original Academy background can contain additional organisms.</p><div class="views"><figure><a href="/' + esc(pair['background']['path'], quote=True) + '"><img loading="lazy" src="/' + esc(pair['background']['path'], quote=True) + '" alt="Original background"></a><figcaption>Original Academy background</figcaption></figure><figure><a href="' + esc(pair['frames']['bounded']['file'], quote=True) + '"><img loading="lazy" src="' + esc(pair['frames']['bounded']['file'], quote=True) + '" alt="Bounded factor pair"></a><figcaption>Bounded-factor overlap</figcaption></figure><figure><a href="' + esc(str(overlay_path.relative_to(O)), quote=True) + '"><img loading="lazy" src="' + esc(str(overlay_path.relative_to(O)), quote=True) + '" alt="Outlined inserted supports"></a><figcaption>Support 1 and 2 outlines</figcaption></figure></div>' + ''.join(target_blocks) + '</article>')
    baseline, bounded = check['prediction_summary']['baseline'], check['prediction_summary']['bounded']
    px0, px1 = check['overlap_pixel_response_proxy']['baseline'], check['overlap_pixel_response_proxy']['bounded']
    page = '''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Paired synthetic overlaps</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-bounded-transmission/">Prior bounded-factor test</a></nav><h1>Can a classifier identify both members of a synthetic overlap?</h1><p class="notice"><strong>Exploratory development diagnostic, not Academy accuracy.</strong> Source names and mask links are not independently adjudicated; specimens, backgrounds and model were previously used; physical source scale is unknown. Each target crop is supplied by an oracle support rather than detected. The model is forced to pick a class, and failure to match names does not prove biological details are invisible.</p><p>Formed 25 fixed source pairs from 50 previously used components and deliberately placed their projected supports to intersect over reused Academy backgrounds. Median intersection is ''' + f"{100*check['median_target_support_intersection_fraction']:.1f}%" + ''' of target support. Each target has the same crop when alone and when overlapping. Compared the original factor and the prior exploratory bounded exponent-3 factor; both use a multiplicative grayscale approximation and arbitrary source resizing.</p><table><tr><th>Renderer</th><th>Exact top-one species: alone → overlapping (50 targets)</th><th>Exact top-one genus: alone → overlapping (50 targets)</th><th>Both source species matched: alone → overlapping (25 pairs)</th></tr>''' + ''.join('<tr><th>' + label + '</th><td>' + str(v['single_species_top1']) + ' → ' + str(v['overlap_species_top1']) + '</td><td>' + str(v['single_genus_top1']) + ' → ' + str(v['overlap_genus_top1']) + '</td><td>' + str(v['single_both_species_top1']) + ' → ' + str(v['overlap_both_species_top1']) + '</td></tr>' for label, v in [('Original factor', baseline), ('Bounded exponent 3', bounded)]) + '''</table><p>Neither renderer matched both source names in any overlap pair. Only ''' + str(check['pairs_with_both_names_in_vocabulary_exact']) + ''' pairs have both names exactly in the model vocabulary; no overlap pair in that subset matched both either. This result concerns one forced-choice classifier on deliberately hard synthetic crops and is not an estimate of biological species-identification accuracy.</p><p>In the overlap intersection, the fixed-factor +4-level background-response proxy was below half the input perturbation for ''' + str(px0['response_below_half_px']) + ' / ' + str(px0['response_eligible_px']) + ' pixels with the original factor and ' + str(px1['response_below_half_px']) + ' / ' + str(px1['response_eligible_px']) + ''' with the bounded factor. This is a pooled, post-clipping but pre-rounding numerical probe, not a test of whether a background diatom is recognizable. Two individually bounded factors can multiply to 0.25; bounding each layer alone does not guarantee retained response when layers overlap.</p><p><a href="protocol.json">Frozen pairing and method</a> · <a href="results.json">All predictions and source provenance</a> · <a href="verify.json">Reconstruction and counts</a> · <a href="replay.json">16 inference replays</a>. Source content is CC BY-NC-SA 4.0; the DIAMORPH checkpoint identifies AGPL-3.0 and DIATLAS is CC BY 4.0.</p><h2>All pairs</h2><p>Outlines show projected source components, not expert-verified anatomy or visible-only boundaries. Each strip uses an identical target crop for alone and overlap.</p>''' + ''.join(cards) + '</main></html>'
    (O / 'index.html').write_text(page)
    print('published', len(cards), 'paired overlaps and', 2 * len(cards), 'target comparisons')


if __name__ == '__main__':
    main()
