import subprocess,time,pathlib,datetime,sys
from PIL import Image,ImageChops
root=pathlib.Path(__file__).parent
out=root/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%d-%H%M%S')
out.mkdir()
label=sys.argv[1]
for n in range(5):
 a=out/f'{label}-{n}-a.png'; b=out/f'{label}-{n}-b.png'
 subprocess.run(['agent-device','screenshot',str(a),'--session','usage42837'],check=True)
 time.sleep(.5)
 subprocess.run(['agent-device','screenshot',str(b),'--session','usage42837'],check=True)
 if ImageChops.difference(Image.open(a).convert('RGB'),Image.open(b).convert('RGB')).getbbox() is None:
  print('STABLE',b);break
else: raise SystemExit('Screenshots did not settle')
