"""Publish uncalibrated source-component scenes with outlined supports."""
import html
import json
from pathlib import Path

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

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


def main():
    manifest = json.loads((O / 'manifest.json').read_text())
    check = json.loads((O / 'verify.json').read_text())
    (O / 'overlays').mkdir(exist_ok=True)
    cards = []
    palette = ['#ff5757', '#57cfff', '#e0e75b', '#e579f0', '#71ef95', '#ffa844',
               '#f2a9cc', '#b1a1ff', '#ffffff', '#ff9595', '#67ceba', '#faedac']
    for row in manifest['records']:
        n = len(row['instances'])
        with np.load(O / row['mask_archive'], allow_pickle=False) as z:
            masks = np.unpackbits(z['support_bits'], count=n * 768 * 768).reshape(n, 768, 768).astype('uint8')
        image = Image.open(O / row['image']).convert('RGB')
        draw = ImageDraw.Draw(image)
        for j, mask in enumerate(masks):
            contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
            for contour in contours:
                points = [tuple(int(v) for v in pt[0]) for pt in contour]
                if len(points) > 1:
                    draw.line(points + [points[0]], fill=palette[j], width=2)
            ys, xs = np.nonzero(mask)
            if len(xs):
                draw.text((int(np.median(xs)), int(np.median(ys))), str(j + 1), fill=palette[j], stroke_width=1, stroke_fill='black')
        overlay = 'overlays/' + row['id'] + '.png'
        image.save(O / overlay)
        items = []
        for i, (x, c) in enumerate(zip(row['instances'], row['omission_contributions'])):
            pool = 'gunduz-species-assets' if x['pool'] == 'existing' else 'gunduz-expansion-assets'
            label = esc(x['source_name']) + ' · ' + esc(x['id'])
            items.append('<li><a href="/results/r112/' + pool + '/overlays/' + esc(x['id']) + '.png">' + label + '</a> · arbitrary pixel scale ' + str(x['image_scale']) + ' · support in frame ' + f"{100 * x['in_frame_fraction']:.1f}%" + ' · pixels changed when omitted ' + str(c['changed_pixels']) + '</li>')
        cards.append('<article><h3>' + esc(row['id']) + '</h3><p>' + str(n) + ' inserted sources · ' + str(row['support_overlap_pairs']) + ' overlapping support pairs</p><div class="views"><figure><a href="/' + esc(row['background']['path']) + '"><img loading="lazy" src="/' + esc(row['background']['path']) + '" alt="Original Academy background"></a><figcaption>Original Academy background</figcaption></figure><figure><a href="' + esc(row['image']) + '"><img loading="lazy" src="' + esc(row['image']) + '" alt="Synthetic scene"></a><figcaption>Composite</figcaption></figure><figure><a href="' + esc(overlay) + '"><img loading="lazy" src="' + esc(overlay) + '" alt="Composite with outlined supports"></a><figcaption>Projected source supports</figcaption></figure></div><details><summary>Source specimens and renderer diagnostics</summary><ol>' + ''.join(items) + '</ol><p><a href="' + esc(row['mask_archive']) + '">Projected support archive</a></p></details></article>')
    c = check['counts']
    page = '''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Uncalibrated source-component scenes</title><style>body{font:16px/1.5 system-ui;color:#193b37;background:#f2f6f2;margin:0}main{max-width:1400px;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}.views{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px}figure{margin:0}.views img{width:100%;height:auto}figcaption{font-size:.85rem}@media(max-width:700px){.views{grid-template-columns:1fr}}</style><main><nav><a href="/results/r112/">Synthetic training</a> · <a href="/results/r112/gunduz-species-assets/">Source components</a></nav><h1>Uncalibrated source-component scenes</h1><p class="notice"><strong>Development diagnostics, not a training-ready set.</strong> The Gündüz source pixel scale is unknown: the 0.4–0.8 image-space resize factors are arbitrary and do not correspond to Academy physical calibration. Source mask-to-name associations, specimen identity and optical realism require review. All Academy background pixels are unknown, including under insertions.</p><p>Nine previously used 768×768 Academy backgrounds contain all 51 available source components once, across 29 literal source-name strings. Each insertion uses a separate component support, arbitrary scale, rotation, opacity and contrast. Different instances may overlap; separate projected supports are not true visibility masks. The multiplicative blending is an approximate image transform, not a verified physical microscope model. Source crops may themselves contain other organisms.</p><p>Checks found ''' + str(c['overlap_pairs']) + ''' intersecting support pairs in ''' + str(c['scenes_with_overlap']) + ''' fields and ''' + str(c['partial_supports']) + ''' partially clipped supports. All ''' + str(c['instances']) + ''' insertions changed at least one 8-bit pixel when omitted. Pixel change does not establish biological visibility or diagnostic detail. These are reused development sources and not an independent benchmark.</p><p>Source: Hüseyin Gündüz's Diatom Dataset, CC BY-NC-SA 4.0; attribution, noncommercial and share-alike requirements apply. <a href="protocol.json">Recipe</a> · <a href="manifest.json">Provenance and contributions</a> · <a href="verify.json">Reconstruction</a> · <a href="/diatom_pilot/gunduz_uncalibrated_scene_dataset.py">Diagnostic reader</a>.</p>''' + ''.join(cards) + '</main></html>'
    (O / 'index.html').write_text(page)
    print('published', len(cards), 'fields with outlined supports')


if __name__ == '__main__':
    main()
