import argparse, subprocess, time, shutil
from pathlib import Path
from PIL import Image, ImageChops
p=argparse.ArgumentParser();p.add_argument('session');p.add_argument('output');a=p.parse_args()
out=Path(a.output)
for attempt in range(5):
 first=out.with_name(out.stem+f'-stability-{attempt}-a.png'); second=out.with_name(out.stem+f'-stability-{attempt}-b.png')
 for path in [first,second]:
  subprocess.run(['agent-device','screenshot',str(path),'--session',a.session],check=True,stdout=subprocess.DEVNULL)
  time.sleep(.5)
 if ImageChops.difference(Image.open(first).convert('RGB'),Image.open(second).convert('RGB')).getbbox() is None:
  shutil.copyfile(second,out); print(f'Stable capture: {out.name}');break
else: raise SystemExit('Screen did not stabilize')
