import sys,pathlib,subprocess,time,hashlib,shutil
out=pathlib.Path(sys.argv[1]);session=sys.argv[2]
out.parent.mkdir(parents=True,exist_ok=True)
for attempt in range(1,6):
 samples=[]
 for sample in [1,2]:
  p=out.with_name(f'{out.stem}-check-{attempt}-{sample}.png')
  subprocess.run(['agent-device','screenshot',str(p),'--session',session],check=True,stdout=subprocess.DEVNULL)
  samples.append(p)
  if sample==1: time.sleep(.5)
 if samples[0].read_bytes()==samples[1].read_bytes():
  shutil.copyfile(samples[1],out)
  print('Stable capture:',out.name)
  break
else: raise SystemExit('UI did not settle to identical screenshots')
