import subprocess, time, sys
from pathlib import Path
from PIL import Image, ImageChops
session, label, destination = sys.argv[1:]
out = Path(destination)
out.mkdir(parents=True, exist_ok=True)
for i in range(8):
    a, b = out / f'{label}-{i}-a.png', out / f'{label}-{i}-b.png'
    for image in (a, b):
        subprocess.run(['agent-device', 'screenshot', str(image), '--session', session], check=True, stdout=subprocess.DEVNULL)
        time.sleep(0.5)
    if ImageChops.difference(Image.open(a).convert('RGB'), Image.open(b).convert('RGB')).getbbox() is None:
        target = out / f'{label}.png'
        target.write_bytes(b.read_bytes())
        print(target)
        break
else:
    raise SystemExit('No pair of identical screenshots')
