import subprocess,sys,time,pathlib
from PIL import Image,ImageChops
root=pathlib.Path(__file__).parent
label=sys.argv[1]
for n in range(5):
    a=root/f'{label}-{n}-a.png'; b=root/f'{label}-{n}-b.png'
    subprocess.run(['agent-device','screenshot',str(a),'--session','video-access-proof'],check=True,capture_output=True)
    time.sleep(.5)
    subprocess.run(['agent-device','screenshot',str(b),'--session','video-access-proof'],check=True,capture_output=True)
    if ImageChops.difference(Image.open(a).convert('RGB'),Image.open(b).convert('RGB')).getbbox() is None:
        out=root/f'{label}.png'; out.write_bytes(b.read_bytes()); print('Stable capture:',out); break
else: raise RuntimeError('Screen did not stabilize')
