import subprocess, time, sys
from pathlib import Path
from PIL import Image, ImageChops
output, session = Path(sys.argv[1]), sys.argv[2]
for i in range(3):
    a = output.with_name(f'{output.stem}-{i}-a.png')
    b = output.with_name(f'{output.stem}-{i}-b.png')
    subprocess.run(['agent-device', 'screenshot', str(a), '--session', session], check=True, capture_output=True)
    time.sleep(.5)
    subprocess.run(['agent-device', 'screenshot', str(b), '--session', session], check=True, capture_output=True)
    if ImageChops.difference(Image.open(a).convert('RGB'), Image.open(b).convert('RGB')).getbbox() is None:
        Image.open(b).save(output)
        print('Stable capture:', output.name)
        break
else:
    raise RuntimeError('Screen did not stabilize')
