import subprocess,sys,time,json,pathlib
session,mode,out=sys.argv[1:]
out=pathlib.Path(out); out.mkdir(parents=True,exist_ok=True)
def run(*args):
 p=subprocess.run(['agent-device',*map(str,args),'--session',session],text=True,capture_output=True)
 print(p.stdout,p.stderr,flush=True)
 if p.returncode: raise RuntimeError(args)
 return p.stdout
def wait(seconds=2): time.sleep(seconds)
def shot(name):
 from PIL import Image, ImageChops
 for attempt in range(8):
  run('screenshot',out/(name+'-stable-check.png')); time.sleep(0.5)
  run('screenshot',out/(name+'.png'))
  if ImageChops.difference(Image.open(out/(name+'-stable-check.png')),Image.open(out/(name+'.png'))).getbbox() is None:
   return
 raise RuntimeError('Screen did not settle: '+name)
if mode=='taps':
 wait(); run('press',540,1200); wait(); shot('single-tap'); wait(); run('press',540,1200); wait(); shot('restored'); wait()
elif mode=='gestures':
 run('gesture','pan',540,1200,120,0,500); wait(); shot('drag-1x')
 run('press',540,1200,'--double-tap'); wait(); shot('double-zoom')
 run('gesture','pan',540,1200,180,100,600); wait(); shot('pan-zoomed')
 run('press',540,1200,'--double-tap'); wait(); shot('double-back')
 run('gesture','pinch',1.7,540,1200); wait(); shot('pinch-out')
 run('gesture','pinch',0.5,540,1200); wait(); shot('pinch-back'); wait(4)
 run('longpress',540,1200,1100); wait(); shot('longpress'); wait(4)
elif mode=='race':
 run('replay', pathlib.Path(__file__).with_name('race-proof.ad')); shot('race-back')
elif mode=='repeated':
 run('replay',pathlib.Path(__file__).with_name('repeated-pinches.ad')); shot('repeated-final')
elif mode=='race1x':
 run('replay',pathlib.Path(__file__).with_name('race-to-1x.ad')); shot('race-back')
elif mode=='racefit':
 run('replay',pathlib.Path(__file__).with_name('race-to-fit.ad')); shot('race-back')
