import datetime,json,pathlib,subprocess,sys,time
side,session=sys.argv[1:3]
out=pathlib.Path(__file__).parent/(side+'-controls-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'))
out.mkdir()
def call(*args):
 r=subprocess.run(['agent-device',*args,'--session',session],capture_output=True,text=True)
 if r.returncode and 'Remote daemon is unavailable' in r.stdout+r.stderr:
  time.sleep(60)
  r=subprocess.run(['agent-device',*args,'--session',session],capture_output=True,text=True)
 with (out/'driver.log').open('a') as f:f.write(' '.join(args)+'\n'+r.stdout+r.stderr+'\n')
 if r.returncode:raise RuntimeError(r.stdout+r.stderr)
 return r.stdout
def nodes():return [x for x in json.loads(call('snapshot','--json'))['data']['nodes'] if x.get('bundleId')=='com.t3tools.t3code.dev']
def choose(label,n=0):
 matches=[x for x in nodes() if x.get('label')==label]
 if len(matches)<=n:raise RuntimeError('Missing '+label)
 return '@'+matches[n]['ref']
def tap(label,n=0):call('press',choose(label,n),'--settle')
ns=nodes()
thread=next((x for x in ns if x.get('label')=='Syntax colour sample' and x.get('kind')=='button'),None)
if thread:call('press','@'+thread['ref'],'--settle')
call('record','start',str(out/'raw.mp4'),'--hide-touches')
try:
 tap('Wrap lines',1)
 # Native and replacement blocks use different labels for the active wrap state.
 ns=nodes()
 active=[x for x in ns if x.get('label') in ['Disable line wrap','Unwrap lines','Do not wrap lines']]
 if active:call('press','@'+active[0]['ref'],'--settle')
 else:tap('Wrap lines',1)
 ns=nodes(); copies=[x for x in ns if x.get('label') in ['Copy','Copy code'] and x.get('kind')=='button']
 call('press','@'+copies[1]['ref'],'--settle')
 ns=nodes(); code=next(x for x in ns if x.get('label','').startswith('fun greet') and x.get('kind') in ['text','group'])
 call('longpress','@'+code['ref'],'800','--settle')
 tap('Copy as Markdown')
finally:call('record','stop')
print(out)
