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

root = Path(__file__).parent / 'run-20261030-0902'
stats = {}
for row in ('R3', 'R4'):
    before = np.asarray(Image.open(root / f'before-{row}-final.png').convert('RGB')).astype(np.int16)
    after = np.asarray(Image.open(root / f'after-{row}-final.png').convert('RGB')).astype(np.int16)
    assert before.shape == after.shape
    delta = np.abs(before - after)
    maximum = delta.max(axis=2)
    diff0 = np.where((maximum > 0)[..., None], np.minimum(delta * 32, 255), 0).astype(np.uint8)
    difft = np.zeros_like(diff0)
    difft[maximum > 16] = (255, 0, 255)
    Image.fromarray(diff0).save(root / f'{row}-diff0-x32.png')
    Image.fromarray(difft).save(root / f'{row}-diffT16.png')
    coords = np.argwhere(maximum > 0)
    stats[row] = {'raster': [before.shape[1], before.shape[0]], 'threshold0Pixels': int((maximum > 0).sum()), 'threshold16Pixels': int((maximum > 16).sum()), 'bboxXYXY': [int(coords[:,1].min()), int(coords[:,0].min()), int(coords[:,1].max()+1), int(coords[:,0].max()+1)], 'zeroThresholdAmplification': 32, 'thresholdRule': 'max absolute 8-bit RGB channel difference > 16; magenta mask'}
(root / 'diff-stats.json').write_text(json.dumps(stats, indent=2)+'\n')
print(json.dumps(stats, indent=2))
