import subprocess,sys,time,pathlib,hashlib
out=pathlib.Path(sys.argv[1]); session=sys.argv[2]
last=None
for i in range(8):
 p=out.with_name(out.stem+f'-stable-{i}.png')
 subprocess.run(['agent-device','screenshot',str(p),'--session',session],check=True,stdout=subprocess.DEVNULL)
 data=p.read_bytes()
 if data==last:
  out.write_bytes(data)
  print(f'Stable capture: {out.name}')
  break
 last=data
 time.sleep(.5)
else: raise RuntimeError('Screen never stabilized')
