import pathlib,sys,subprocess,time,hashlib
binary,session,output=sys.argv[1:]
path=pathlib.Path(output)
prior=None
for i in range(12):
    sample=path.with_name(path.stem+f'-sample-{i}'+path.suffix)
    subprocess.run([binary,'--session',session,'screenshot',str(sample)],check=True,stdout=subprocess.DEVNULL)
    data=sample.read_bytes(); digest=hashlib.sha256(data).hexdigest()
    if digest==prior:
        path.write_bytes(data)
        print(f'Stable capture: {path.name}; identical frames 500 ms apart')
        break
    prior=digest
    time.sleep(.5)
else: raise RuntimeError('Capture did not stabilize')
