import subprocess,sys,re,pathlib,time,json
root=pathlib.Path('/tmp/navigation-proof')
session=sys.argv[1]; name=sys.argv[2]
log=open(root/(name+'-driver.log'),'w')
def run(*args):
 p=subprocess.run(['agent-device',*args,'--session',session],text=True,capture_output=True)
 log.write(' '.join(args)+'\n'+p.stdout+p.stderr+'\n');log.flush()
 if p.returncode: raise RuntimeError(p.stderr)
 return p.stdout
def tap(label):
 snap=run('snapshot','-i')
 lines=[l for l in snap.splitlines() if '"'+label+'"' in l and '[disabled]' not in l]
 if not lines:
  run('wait','text',label)
  snap=run('snapshot','-i');lines=[l for l in snap.splitlines() if '"'+label+'"' in l and '[disabled]' not in l]
 if not lines:raise RuntimeError('Missing '+label+'\n'+snap)
 run('press',lines[0].split()[0],'--settle')
 run('snapshot','-i')
def back():run('back','--settle');run('snapshot','-i')
def shot(label):
 a=root/(name+'-'+label+'-check.png'); b=root/(name+'-'+label+'.png')
 run('screenshot',str(a));time.sleep(.5);run('screenshot',str(b))
 result=subprocess.run(['compare','-metric','AE',str(a),str(b),'null:'],capture_output=True,text=True)
 print(label,'stable=',result.returncode==0,flush=True)
def record():run('record','start',str(root/(name+'.mp4')),'--hide-touches')
flow=sys.argv[3]
record()
if flow=='chat':
 tap('Search navigation');tap('search PR');run('wait','text="Improve search navigation"','120000');back();shot('back-1');back();shot('back-2')
elif flow=='reverse':
 tap('Pull request 101, Improve search navigation, Open, by demo, stack 1 of 2, 4 additions, 1 deletions');tap('Continue thread');run('wait','text="search PR"','120000');run('screenshot',str(root/(name+'-chat.png')));back();shot('back-1');back();shot('back-2')
elif flow=='stack':
 tap('Pull request 101, Improve search navigation, Open, by demo, stack 1 of 2, 4 additions, 1 deletions');tap('Stack, 1 of 2, showing saved stack');tap('Add search filters, #102 · 2 of 2, Open');run('wait','text','Add search filters');back();shot('back-1');back();shot('back-2')
run('record','stop')
print('DONE',name)
