import json
import shutil
import sys
from PIL import Image, ImageChops

first, second, output, metadata = sys.argv[1:]
a, b = Image.open(first).convert('RGB'), Image.open(second).convert('RGB')
environment = json.loads(metadata)
expected = (environment['viewport']['width'] * environment['dpr'], environment['viewport']['height'] * environment['dpr'])
assert a.size == b.size == expected, (a.size, b.size, expected)
shutil.copyfile(first, output + '-settle-a.png')
shutil.copyfile(second, output + '-settle-b.png')
difference = ImageChops.difference(a, b)
assert difference.getbbox() is None, 'Unsettled screenshots differ: ' + str(difference.getbbox())
shutil.copyfile(second, output + '.png')
with open(output + '.json', 'w') as handle:
    json.dump(dict(environment, pixelIdentical500ms=True, pixels=a.size), handle, indent=2)
print(output + '.png: pixel-identical at 500 ms')
