from pathlib import Path
from PIL import Image,ImageChops
import subprocess,sys,time
out=Path(sys.argv[1]);session=sys.argv[2]
for attempt in range(3):
 a=out.with_name(out.stem+f'-check-{attempt}.png')
 subprocess.run(['agent-device','screenshot',str(a),'--session',session],check=True,stdout=subprocess.DEVNULL)
 time.sleep(.5)
 subprocess.run(['agent-device','screenshot',str(out),'--session',session],check=True,stdout=subprocess.DEVNULL)
 if ImageChops.difference(Image.open(a).convert('RGB'),Image.open(out).convert('RGB')).getbbox() is None:
  print(f'Stable capture: {out.name} (two identical images 500 ms apart)');break
else: raise SystemExit('The screen did not stabilize in three pairs')
