import json
from pathlib import Path
import numpy as np
from PIL import Image, ImageChops

S = Path('/tmp/lead-33554-r1/evidence-capture-2')
results = []
for width in (1440, 390):
    for theme in ('light', 'dark'):
        arrays = []
        for side in ('before', 'after'):
            stem = f'F21-{side}-{width}-{theme}'
            still = Image.open(S / f'{stem}.png').convert('RGB')
            first = Image.open(S / f'{stem}-settle-a.png').convert('RGB')
            assert still.size == (width, 900), (stem, still.size)
            assert ImageChops.difference(first, still).getbbox() is None, f'{stem} moved'
            arrays.append(np.asarray(still).astype(np.int16))
        delta = np.abs(arrays[0] - arrays[1])
        maximum = delta.max(axis=2)
        # Zero threshold, amplified 8x. A difference of one channel value stays visible.
        amplified = np.clip(delta * 8, 0, 255).astype(np.uint8)
        Image.fromarray(amplified).save(S / f'F21-{width}-{theme}-Diff0.png')
        # DiffT uses max absolute RGB channel delta > 16 on the 0..255 scale.
        mask = maximum > 16
        threshold = np.zeros_like(amplified)
        threshold[mask] = (255, 0, 255)
        Image.fromarray(threshold).save(S / f'F21-{width}-{theme}-DiffT.png')
        points = np.argwhere(maximum > 0)
        y0, x0 = points.min(axis=0)
        y1, x1 = points.max(axis=0) + 1
        result = {'viewport': f'{width}x900', 'theme': theme,
                  'settled500ms': True, 'diff0Pixels': int((maximum > 0).sum()),
                  'diffTPixels': int(mask.sum()), 'threshold': 16,
                  'bbox': [int(x0), int(y0), int(x1), int(y1)]}
        results.append(result)
        print(json.dumps(result))
        control_path = S / f'F21-control-after-before-text-{width}-{theme}.png'
        if control_path.exists():
            control = Image.open(control_path).convert('RGB')
            control_first = Image.open(S / f'F21-control-after-before-text-{width}-{theme}-settle-a.png').convert('RGB')
            assert ImageChops.difference(control, control_first).getbbox() is None
            before = Image.open(S / f'F21-before-{width}-{theme}.png').convert('RGB')
            control_difference = ImageChops.difference(before, control)
            result['sameTextControlDiffPixels'] = int((np.asarray(control_difference).max(axis=2) > 0).sum())
            assert control_difference.getbbox() is None, f'{width} {theme}: same-text control differs'
(S / 'diff-metrics.json').write_text(json.dumps(results, indent=2) + '\n')
