from pathlib import Path
from PIL import Image, ImageChops, ImageDraw
import json

root = Path(__file__).parent
results = []
for row in ('V1', 'V3', 'V4'):
    for width in (1440, 390):
        for theme in ('light', 'dark'):
            stem = f'{row}-web-{width}-{theme}'
            before = Image.open(root / f'{row}-before-web-{width}-{theme}.png').convert('RGB')
            after = Image.open(root / f'{row}-after-web-{width}-{theme}.png').convert('RGB')
            diff = ImageChops.difference(before, after)
            channels = diff.split()
            maximum = ImageChops.lighter(ImageChops.lighter(channels[0], channels[1]), channels[2])
            zero = maximum.point(lambda x: 255 if x > 0 else 0)
            threshold = maximum.point(lambda x: 255 if x > 16 else 0)
            diff.point(lambda x: min(x * 4, 255)).save(root / f'{stem}-diff0-amplified4.png')
            marked = Image.new('RGB', before.size, 'black')
            marked.paste((255, 0, 255), mask=threshold)
            marked.save(root / f'{stem}-diff-threshold16.png')
            roi = ((350, 75, 960, 300) if width == 1440 else (24, 170, 765, 760)) if row == 'V4' else ((320, 270, 960, 360) if width == 1440 else (60, 630, 720, 750))
            outside_zero = zero.copy(); outside_zero.paste(0, roi)
            outside_threshold = threshold.copy(); outside_threshold.paste(0, roi)
            results.append({'pair': stem, 'size': before.size, 'changedPixelsZero': zero.histogram()[255], 'changedPixelsThreshold16': threshold.histogram()[255], 'bboxZero': zero.getbbox(), 'bboxThreshold16': threshold.getbbox(), 'regionOfInterest': roi, 'outsideRoiZero': outside_zero.histogram()[255], 'outsideRoiThreshold16': outside_threshold.histogram()[255], 'masks': []})
stability = []
for p in sorted(root.glob('V*-settle.png')):
    first = p.with_name(p.name.replace('-settle', ''))
    diff = ImageChops.difference(Image.open(first), Image.open(p))
    stability.append({'capture': first.name, 'identicalAfter500ms': diff.getbbox() is None})
(root / 'comparison-results.json').write_text(json.dumps({'threshold': 'maximum absolute RGB channel difference > 16/255', 'zeroAmplification': 4, 'comparisons': results, 'stability': stability}, indent=2))
for group in ('V1', 'V3', 'V4'):
    ps = sorted(root.glob(group + '-web-*-diff*.png'))
    out = Image.new('RGB', (1280, 1000), '#888')
    draw = ImageDraw.Draw(out)
    for i, p in enumerate(ps):
        im = Image.open(p); im.thumbnail((310, 460))
        x, y = i % 4 * 320, i // 4 * 500
        out.paste(im, (x, y + 25)); draw.text((x + 3, y + 3), p.stem, fill='white')
    out.save(root / f'contact-diffs-{group}.png')
print(json.dumps(results, indent=2))
