import sys,subprocess,time,pathlib
from PIL import Image,ImageChops
session,label=sys.argv[1:]
p=pathlib.Path(label)
for n in range(10):
 a=p.with_name(p.stem+f'-settle-{n}-a.png');b=p.with_name(p.stem+f'-settle-{n}-b.png')
 for i,d in enumerate((a,b)):
  if i:time.sleep(.5)
  subprocess.run(['agent-device','screenshot',str(d),'--session',session],check=True,capture_output=True)
 if ImageChops.difference(Image.open(a).convert('RGB'),Image.open(b).convert('RGB')).getbbox() is None:
  p.write_bytes(b.read_bytes());print(p);break
else:raise RuntimeError('The screen never settled')
