"""Join online viewport screenshots without resizing; verify each region."""
from pathlib import Path
import hashlib
import json
from PIL import Image, ImageChops

root = Path(__file__).resolve().parent
folder = root / 'qa/online-capture-v3'
meta = json.loads((folder / 'capture.json').read_text())
scale = meta['scale']
width, height = round(meta['width'] * scale), round(meta['height'] * scale)
canvas = Image.new('RGB', (width, height), 'white')
pieces = []
for tile in meta['tiles']:
    image = Image.open(folder / tile['filename']).convert('RGB')
    x = round(meta['x'] * scale)
    y = round((tile['targetY'] - tile['scrollY']) * scale)
    part_height = round(tile['height'] * scale)
    assert 0 <= y and y + part_height <= image.height
    piece = image.crop((x, y, x + width, y + part_height))
    destination = round(tile['targetY'] * scale)
    canvas.paste(piece, (0, destination))
    pieces.append((destination, piece))
output = root / '订餐取餐流程-排版优化版.png'
canvas.save(output)
saved = Image.open(output)
for y, piece in pieces:
    region = saved.crop((0, y, width, y + piece.height))
    assert ImageChops.difference(piece, region).getbbox() is None
meta['output'] = {
    'filename': output.name, 'width': width, 'height': height,
    'bytes': output.stat().st_size,
    'sha256': hashlib.sha256(output.read_bytes()).hexdigest(),
    'tile_pixel_mismatches': 0, 'resampled': False,
}
(folder / 'capture.json').write_text(json.dumps(meta, ensure_ascii=False, indent=2))
print(json.dumps(meta['output'], ensure_ascii=False))
