import subprocess,time,sys,os
from pathlib import Path
from PIL import Image,ImageChops
session,label=sys.argv[1:]
out=Path(os.environ['PROOF_OUTPUT'])/'captures'
out.mkdir(exist_ok=True)
last=None
for n in range(5):
 p=out/f'{label}-{n}.png'
 subprocess.run(['agent-device','screenshot',str(p),'--normalize-status-bar','--session',session],check=True,capture_output=True)
 im=Image.open(p)
 if last is not None and ImageChops.difference(im,last).getbbox() is None:
  dest=out/f'{label}.png';im.save(dest);print(dest);break
 last=im.copy();time.sleep(.5)
else: raise SystemExit('Screen did not stabilize')
