"""Verify actual Filepetal WebP/JPG pairs. Requires Pillow; does not convert images."""
from pathlib import Path
from PIL import Image, ImageChops, ImageStat
import hashlib
import json

HERE = Path(__file__).resolve().parent
manifest = json.loads((HERE / 'sample-manifest.json').read_text(encoding='utf-8'))
inputs = {item['name']: item for item in manifest['samples']}
for name, item in inputs.items():
    data = (HERE / name).read_bytes()
    assert len(data) == item['bytes']
    assert hashlib.sha256(data).hexdigest() == item['sha256']

outputs = []
for stem in ['alpha-bands', 'odd-detail', 'two-frame', 'side-4096']:
    path = HERE / (stem + '.jpg')
    original = inputs[stem + '.webp']
    data = path.read_bytes()
    with Image.open(path) as decoded:
        decoded.load()
        assert decoded.format == 'JPEG'
        assert decoded.size == (original['width'], original['height'])
        rgb = decoded.convert('RGB')
    row = dict(input=stem+'.webp', output=path.name, format='JPEG',
               width=rgb.width, height=rgb.height, bytes=len(data),
               sha256=hashlib.sha256(data).hexdigest(),
               input_bytes=original['bytes'], larger_than_input=len(data)>original['bytes'])
    if stem == 'alpha-bands':
        positions = [(32, 64), (96, 64), (160, 64), (224, 64)]
        expected = [(255,255,255), (255,127,127), (0,0,255), (191,255,191)]
        measured = [rgb.getpixel(point) for point in positions]
        assert all(max(abs(a-b) for a,b in zip(got,want)) <= 3
                   for got,want in zip(measured,expected))
        row['alpha_probe_positions'] = positions
        row['alpha_probe_rgb'] = measured
        row['expected_white_composite_rgb'] = expected
        row['maximum_allowed_channel_error'] = 3
    if stem == 'two-frame':
        center = rgb.getpixel((48,32))
        assert center[0] > 220 and center[1] < 30 and center[2] < 30
        row['center_rgb'] = center
        row['observation'] = 'Single JPEG matches the red first frame, not the blue second frame.'
    if stem == 'odd-detail':
        with Image.open(HERE / (stem+'.webp')) as source:
            difference = ImageChops.difference(source.convert('RGB'),rgb)
            row['mean_absolute_rgb_difference_from_decoded_webp'] = ImageStat.Stat(difference).mean
            row['interpretation'] = 'Pixel differences after another lossy encoding; not a perceptual quality score.'
    outputs.append(row)

browser = json.loads((HERE / 'browser-checks.json').read_text(encoding='utf-8'))
rejections = [row for row in browser['checks'] if row.get('no_download')]
assert {row['sample'] for row in rejections} == {'side-4097.webp','truncated.webp','renamed.webp'}
result = dict(date=browser['date'], environment=browser['environment'],
              extraction=browser['extraction'], browser_download_receipt=False,
              input_hashes_verified=len(inputs), outputs=outputs, rejections=rejections,
              scope='These synthetic fixtures only. Browser JPEG encoders can change exact bytes and hashes. Negative UI records are saved observations, not re-executed by this Python script.')
(HERE / 'output-verification.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8')
print(json.dumps(result,indent=2))
