import subprocess,json,pathlib,sys,time,datetime
side=sys.argv[1]; session=sys.argv[2]; out=pathlib.Path(sys.argv[3])/f'{side}-{datetime.datetime.now().strftime("%Y%m%dT%H%M%S")}';out.mkdir()
def device(*args,json_out=False):
 p=subprocess.run(['agent-device',*map(str,args),'--session',session,*(['--json'] if json_out else [])],capture_output=True,text=True,check=True)
 return json.loads(p.stdout) if json_out else p.stdout
def nodes(v):
 if isinstance(v,dict):
  yield v
  for x in v.values():yield from nodes(x)
 elif isinstance(v,list):
  for x in v:yield from nodes(x)
def snap():
 v=device('snapshot','-i',json_out=True)
 return list(nodes(v))
def row(ns):return next(n for n in ns if n.get('label')=='Sample thread 9, Done')['rect']
results=[]
for dy in [0,20,30,45,60]:
 for trial in range(1,4):
  ns=snap(); y0=row(ns)['y']; sy=y0+76
  tag=f'd{dy}_{trial}'
  if dy==60 and trial==1:
   device('record','start',out/'diagonal.mp4','--fps','30')
   time.sleep(1)
  device('gesture','pan',850,sy,-400,-dy,400)
  time.sleep(.8)
  ns=snap();y1=row(ns)['y'];opened=any('Settle Sample thread' in n.get('label','') for n in ns)
  result=dict(tag=tag,dx=-400,dy=-dy,durationMs=400,rowYBefore=y0,rowYAfter=y1,scrollPx=y1-y0,rowOpen=opened)
  results.append(result);print(json.dumps(result),flush=True)
  if dy==60 and trial==1:
   device('screenshot',out/'diagonal-a.png');time.sleep(.5);device('screenshot',out/'diagonal-b.png')
   device('record','stop')
  if opened:
   device('gesture','pan',300,y1+76,500,0,300);time.sleep(.6)
(out/'trials.json').write_text(json.dumps(results,indent=2))
print('OUTPUT',out,flush=True)
