import subprocess, pathlib, time, re, sys
from PIL import Image, ImageChops
side,out,session=sys.argv[1:]
out=pathlib.Path(out);out.mkdir(parents=True,exist_ok=True)
def run(*args):
 return subprocess.check_output(['agent-device',*args,'--session',session],text=True)
def press(title):
 snapshot=run('snapshot','-i')
 lines=[s for s in snapshot.splitlines() if '[button]' in s and ('"'+title) in s]
 if not lines: raise RuntimeError('Button missing: '+title+'\n'+snapshot)
 run('press',lines[0].split()[0])
def stable(label):
 for attempt in range(4):
  a=out/(label+'-check.png');b=out/(label+'.png')
  run('screenshot',str(a));time.sleep(.5);run('screenshot',str(b))
  if ImageChops.difference(Image.open(a).convert('RGB'),Image.open(b).convert('RGB')).getbbox() is None:return
 raise RuntimeError('Unstable screenshot: '+label)
run('record','start',str(out/(side+'-raw.mp4')),'--hide-touches')
press('Searched TODO in app.ts')
run('scroll','top')
stable('file-search')
press('Searched TODO in app.ts')
press('Searched the web')
run('scroll','top')
stable('web-search')
press('Searched the web')
print(run('record','stop'))
