#!/usr/bin/env python3
"""Build lossless visual diffs, labelled sheets, and video inspection strips."""
import json
import subprocess
from pathlib import Path
from PIL import Image, ImageChops, ImageDraw, ImageFont

ROOT = Path(__file__).parent
RUN = ROOT / 'run-2026-10-30T0757'
THRESHOLD = 16
FONT = '/usr/share/fonts/opentype/urw-base35/NimbusSans-Regular.otf'
font = ImageFont.truetype(FONT, 22)
small = ImageFont.truetype(FONT, 16)
metrics = {}

def panel(image, title, subtitle):
    result = Image.new('RGB', (1280, 864), '#151515')
    draw = ImageDraw.Draw(result)
    draw.text((16, 8), title, font=font, fill='white')
    draw.text((16, 38), subtitle, font=small, fill='#b5b5b5')
    result.paste(image, (0, 64))
    return result

for pair in ['R1-final', 'R2-dialog', 'R2-final', 'R3-final', 'R4-final']:
    before = Image.open(RUN / f'before-{pair}.png').convert('RGB')
    after = Image.open(RUN / f'after-{pair}.png').convert('RGB')
    assert before.size == after.size == (1280, 800)
    delta = ImageChops.difference(before, after)
    maximum = ImageChops.lighter(ImageChops.lighter(*delta.split()[:2]), delta.split()[2])
    diff0 = maximum.point(lambda value: min(255, value * 255)).convert('RGB')
    mask = maximum.point(lambda value: 255 if value > THRESHOLD else 0)
    difft = Image.composite(Image.new('RGB', before.size, '#ff00aa'), before.point(lambda value: value // 3), mask)
    diff0.save(RUN / f'{pair}-diff0.png')
    difft.save(RUN / f'{pair}-diff16.png')
    pixels = list(maximum.getdata())
    metrics[pair] = {
        'pixels': len(pixels),
        'changed_at_zero': sum(value > 0 for value in pixels),
        'changed_above_16': sum(value > THRESHOLD for value in pixels),
        'bbox_at_zero': maximum.getbbox(),
        'threshold': THRESHOLD,
        'amplification': 'max RGB channel difference multiplied by 255, clipped to 255',
    }
    kind = ' REAL APP' if pair.startswith(('R1', 'R2')) else ' HARNESS'
    title = f'{pair}{kind} | 1440 x 900 CSS | dark'
    sheet = Image.new('RGB', (2560, 1728))
    for position, item in zip([(0, 0), (1280, 0), (0, 864), (1280, 864)], [
        panel(before, title + ' - Before', '1cf14a498f'),
        panel(after, title + ' - After', '8f66a27e8d'),
        panel(diff0, 'Diff0: zero threshold', 'Every nonzero RGB difference amplified to white'),
        panel(difft, 'DiffT: threshold 16/255', 'Magenta where maximum RGB channel difference > 16'),
    ]):
        sheet.paste(item, position)
    sheet.save(RUN / f'{pair}-sheet.png')

(RUN / 'diff-metrics.json').write_text(json.dumps(metrics, indent=2))

work = RUN / 'filmstrip-work'
work.mkdir(exist_ok=True)
for side in ['before', 'after']:
    for row in ['R1', 'R2', 'R3', 'R4']:
        video = RUN / f'{side}-{row}.mp4'
        probe = json.loads(subprocess.check_output(['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'json', str(video)]))
        duration = float(probe['format']['duration'])
        sheet = Image.new('RGB', (1920, 672), '#151515')
        for index in range(8):
            seconds = max(0, duration - .25) * index / 7
            output = work / f'{side}-{row}-{index}.png'
            subprocess.run(['ffmpeg', '-hide_banner', '-loglevel', 'error', '-y', '-ss', str(seconds), '-i', str(video), '-frames:v', '1', '-vf', 'scale=480:300', str(output)], check=True)
            x, y = (index % 4) * 480, (index // 4) * 336
            draw = ImageDraw.Draw(sheet)
            draw.text((x + 10, y + 8), f'{side} {row} @ {seconds:.2f}s', font=small, fill='white')
            sheet.paste(Image.open(output).convert('RGB'), (x, y + 36))
        sheet.save(RUN / f'{side}-{row}-filmstrip.png')

print(json.dumps(metrics, indent=2))
