import sys, subprocess, time
from pathlib import Path
from PIL import Image, ImageChops
session, out, label=sys.argv[1:]
out=Path(out); out.mkdir(parents=True,exist_ok=True)
last=None
for i in range(12):
    shot=out/f'{label}-{i}.png'
    subprocess.run(['agent-device','screenshot',str(shot),'--session',session],check=True,stdout=subprocess.DEVNULL)
    if last and ImageChops.difference(Image.open(last).convert('RGB'),Image.open(shot).convert('RGB')).getbbox() is None:
        (out/f'{label}.png').write_bytes(shot.read_bytes()); print(out/f'{label}.png'); break
    last=shot; time.sleep(.5)
else: raise RuntimeError('Screenshots did not settle')
