import argparse, subprocess, time, hashlib
from pathlib import Path
from PIL import Image
p=argparse.ArgumentParser();p.add_argument('session');p.add_argument('output');a=p.parse_args()
out=Path(a.output); previous=None
for n in range(12):
    target=out.with_name(out.stem+f'-stability-{n}.png')
    subprocess.run(['agent-device','screenshot',str(target),*(['--normalize-status-bar'] if 'android' in a.session else []),'--session',a.session],check=True,stdout=subprocess.DEVNULL)
    digest=hashlib.sha256(Image.open(target).convert('RGBA').tobytes()).hexdigest()
    if digest==previous:
        out.write_bytes(target.read_bytes());print(f'{out.name}: two identical captures, separated by at least 500ms');break
    previous=digest;time.sleep(.5)
else:
    raise SystemExit('No identical capture pair; retain recording as evidence')
