import subprocess, pathlib, sys, time
from PIL import Image, ImageChops
session, destination = sys.argv[1:]
destination = pathlib.Path(destination)
def capture(path):
 subprocess.run(['agent-device','screenshot',str(path),'--session',session], check=True, stdout=subprocess.DEVNULL)
previous = destination.with_name(destination.stem+'-settle.png')
capture(previous)
for _ in range(12):
 time.sleep(.5)
 capture(destination)
 if ImageChops.difference(Image.open(previous), Image.open(destination)).getbbox() is None:
  print('Stable:', destination.name)
  break
 previous.write_bytes(destination.read_bytes())
else: raise RuntimeError('Screen did not stabilize')
