import subprocess,sys,time,pathlib
from PIL import Image,ImageChops
out=pathlib.Path(sys.argv[1]); session=sys.argv[2]
for attempt in range(6):
 subprocess.run(['agent-device','screenshot',str(out.with_suffix('.check.png')),'--session',session],check=True,capture_output=True)
 time.sleep(.5)
 subprocess.run(['agent-device','screenshot',str(out),'--session',session],check=True,capture_output=True)
 if ImageChops.difference(Image.open(out.with_suffix('.check.png')).convert('RGB'),Image.open(out).convert('RGB')).getbbox() is None:
  print('Stable identical pair:',out.name);break
else: raise SystemExit('Screen did not stabilize')
