import subprocess,sys,json,time,urllib.request,pathlib
side,root,port,metro,session,device,form=sys.argv[1:]
base=pathlib.Path('/tmp/lead-24651-r1b/capture');out=base/(side+'-'+form+'-'+time.strftime('%Y%m%dT%H%M%SZ',time.gmtime()));out.mkdir()
start=time.monotonic();events=[]
def run(args):
 r=subprocess.run(args,cwd=root,text=True,capture_output=True);events.append({'seconds':round(time.monotonic()-start,2),'command':args,'code':r.returncode,'stdout':r.stdout,'stderr':r.stderr});(out/'driver.json').write_text(json.dumps(events,indent=2));print(args[0:4],r.returncode,flush=True)
 if r.returncode:raise RuntimeError(r.stdout+r.stderr)
 return r.stdout
def ad(*args):return run(['agent-device',*args,'--session',session])
def cdp(expr):return run(['node',str(base/'cdp.mjs'),metro,device,expr])
def rpc(action,*args):return run(['node','apps/server/scripts/capture-driver.ts',action,'http://127.0.0.1:'+port,str(base/(side+'-token.secret')),str(out/(action+'.json')),*args])
env=json.load(urllib.request.urlopen('http://127.0.0.1:'+port+'/.well-known/t3/environment'))['environmentId']
lookup=lambda path:'__r([...__r.getModules()].find(([id,m])=>m.verboseName?.endsWith('+json.dumps(path)+'))[0])'
registry=lookup('src/state/atom-registry.ts')+'.appAtomRegistry'
prefs=lookup('src/state/preferences.ts')+'.updateMobilePreferencesAtom'
link=lookup('/Libraries/Linking/Linking.js')+'.default'
recording=False
try:
 rpc('stop');rpc('rename','A · Garden streaming');rpc('stream')
 cdp(registry+'.set('+prefs+',{workingShelfEnabled:false});true')
 if form=='android-sidebar':cdp(link+'.openURL('+json.dumps('t3code-dev://threads/'+env+'/capture-garden-b')+');true')
 else:cdp(link+'.openURL("t3code-dev://");true')
 time.sleep(2)
 ad('record','start',str(out/'flow.mp4'),'--hide-touches');recording=True
 run(['node',str(base/'measure-pure.mjs'),metro,device,env,str(out/'renders.json')])
 cdp('__captureClear('+json.dumps(env)+')')
 if form=='android-sidebar':
  ad('swipe','450','1350','450','350');ad('swipe','450','350','450','1350')
 else:
  ad('scroll','down','400');ad('scroll','up','400')
 rpc('rename','A · Garden renamed live')
 if form=='android-sidebar':
  ad('swipe','450','1350','450','350');ad('swipe','450','1350','450','350')
 ad('snapshot','-i')
 ad('press','text="A · Garden renamed live"')
 time.sleep(15)
 ad('snapshot','-i')
 if form=='android-sidebar':ad('press','text="B · Idle notebook"')
 else:ad('back')
 rpc('stop');time.sleep(2)
 ad('snapshot','-i')
finally:
 if recording:
  try:ad('record','stop')
  except Exception:
   ad('record','stop')
print(str(out))
