#!/usr/bin/env python3
"""Record an actual iPad app cold start. Run from the checkout under test."""
import argparse, pathlib, subprocess, time, json
p=argparse.ArgumentParser()
p.add_argument('--session',required=True);p.add_argument('--out',required=True)
p.add_argument('--title',required=True);p.add_argument('--expect',required=True)
a=p.parse_args();out=pathlib.Path(a.out)/time.strftime('%Y%m%d-%H%M%S');out.mkdir(parents=True)
log=open(out/'driver.log','w')
def run(*args):
 cmd=['agent-device',*args,'--session',a.session]
 r=subprocess.run(cmd,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
 log.write(json.dumps({'command':list(args),'output':r.stdout,'code':r.returncode})+'\n');log.flush()
 if r.returncode and 'Remote daemon is unavailable' in r.stdout:
  time.sleep(60)
  r=subprocess.run(cmd,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
  log.write(json.dumps({'retry':list(args),'output':r.stdout,'code':r.returncode})+'\n');log.flush()
 if r.returncode: raise RuntimeError(r.stdout)
 return r.stdout
run('record','start',str(out/'restart.mp4'),'--scope','device','--hide-touches')
try:
 run('press',f'label="{a.title}"','--settle')
 time.sleep(2)
 run('snapshot','-i')
 run('home')
 time.sleep(1)
 run('open','com.t3tools.t3code.dev','--relaunch')
 run('wait',f'label="{a.expect}"','60000')
 run('snapshot','-i')
 time.sleep(4)
 run('screenshot',str(out/'end.png'))
finally:
 run('record','stop')
print(out,flush=True)
