import subprocess,sys,time,pathlib
from PIL import Image,ImageChops
out=pathlib.Path(sys.argv[1]);session=sys.argv[2];cwd=sys.argv[3]
extra=['--pixel-density','3','--normalize-status-bar'] if 'ios' in session else []
def evidence_pixels(path):
 image=Image.open(path).convert("RGB")
 if "ios" in session:
  image=image.crop((0,150,image.width,2240 if "controls" in out.stem else image.height))
 return image
for i in range(3):
 a=out.with_name(out.stem+'-stability.png')
 subprocess.run(['agent-device','screenshot',str(a),'--session',session,*extra],cwd=cwd,check=True)
 time.sleep(.5)
 subprocess.run(['agent-device','screenshot',str(out),'--session',session,*extra],cwd=cwd,check=True)
 if ImageChops.difference(evidence_pixels(a),evidence_pixels(out)).getbbox() is None:
  print('Stable identical evidence pixels:',out.name);break
else: raise SystemExit('Screen did not stabilize')
