import subprocess,sys,time,pathlib,hashlib,re,os
side,fixture,out=sys.argv[1:]
out=pathlib.Path(out);out.mkdir(parents=True,exist_ok=True)
def cmd(*args):
 p=subprocess.run(['agent-device',*args,'--session',os.environ.get('DEVICE_SESSION','pr47756-evidence')],check=True,capture_output=True,text=True)
 return p.stdout
tree=cmd("snapshot", "-i")
label=re.search(r'\[button\] "(branch '+fixture+r', [^"]+)"',tree).group(1)
print(cmd("press",f'label="{label}"',"--settle"))
time.sleep(2)
print(cmd('press','label="Git controls"','--settle'))
snapshot=cmd('snapshot');(out/f'{side}-{fixture}.txt').write_text(snapshot);print(snapshot)
for n in range(5):
 a=out/f'{side}-{fixture}-{n}-a.png';b=out/f'{side}-{fixture}-{n}-b.png'
 cmd('screenshot',str(a));time.sleep(.5);cmd('screenshot',str(b))
 if a.read_bytes()==b.read_bytes():
  (out/f'{side}-{fixture}.png').write_bytes(b.read_bytes());print('Stable pair:',a.name,b.name);break
else:raise RuntimeError('No stable screenshot pair')
