import hashlib, pathlib, subprocess, sys, time
session, output = sys.argv[1:]
out = pathlib.Path(output)
previous = out.with_name(out.stem + '-settling.png')
def capture(path):
    raw = path.with_name(path.stem + '-raw.png')
    subprocess.run(['agent-device', 'screenshot', str(raw), '--normalize-status-bar', '--session', session], check=True, stdout=subprocess.DEVNULL)
    subprocess.run(['convert', str(raw), '-crop', '402x814+0+60', '+repage', str(path)], check=True)
for attempt in range(5):
    capture(previous)
    time.sleep(.5)
    capture(out)
    if subprocess.run(['compare', '-metric', 'AE', str(previous), str(out), 'null:'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0:
        print('Stable:', out.name)
        break
else:
    raise SystemExit('Screenshots did not settle')
