import subprocess,sys,time,shutil
from pathlib import Path
from PIL import Image,ImageChops
out=Path(sys.argv[1]); session=sys.argv[2]
for n in range(8):
 a=out.with_name(out.stem+f'-sample{n}a.png'); b=out.with_name(out.stem+f'-sample{n}b.png')
 subprocess.run(['agent-device','screenshot',str(a),'--session',session],check=True,stdout=subprocess.DEVNULL)
 time.sleep(.5)
 subprocess.run(['agent-device','screenshot',str(b),'--session',session],check=True,stdout=subprocess.DEVNULL)
 if ImageChops.difference(Image.open(a).convert('RGB'),Image.open(b).convert('RGB')).getbbox() is None:
  shutil.copy(b,out); print(out); break
else: raise RuntimeError('Screenshots did not stabilize')
