"""Drive the real iOS app against the route-proxy; no app or provider responses are fabricated.
Run from the tested checkout, after pairing both routes. Requires agent-device session proof45919.
Usage: python3 measure.py <base|head> <artifact-dir>
"""
import subprocess, time, urllib.request, json, sys, pathlib
side, root=sys.argv[1],pathlib.Path(sys.argv[2]); out=root/(side+'-'+time.strftime('%Y%m%dT%H%M%S'));out.mkdir()
def device(*args):
 p=subprocess.run(['agent-device',*args,'--session','proof45919'],capture_output=True,text=True)
 if p.returncode: raise RuntimeError(p.stdout+p.stderr)
 return p.stdout
def control(q): urllib.request.urlopen('http://127.0.0.1:47813/?'+q).read()
control('blackhole=1&delay=600&run='+side+'-setup')
device('record','start',str(out/'reconnect.mp4'),'--hide-touches')
results=[]
try:
 for n in range(1,6):
  device('click','label="Enable Route timing demo"')
  time.sleep(5.5)
  control('run='+side+'-'+str(n))
  started=time.monotonic()
  device('click','label="Enable Route timing demo"')
  time.sleep(4)
  snap=device('snapshot','-i')
  (out/f'run-{n}.txt').write_text(snap)
  device('screenshot',str(out/f'run-{n}.png'))
  print(f'{side}: completed run {n}',flush=True)
  results.append({'run':n,'observedAfterSeconds':time.monotonic()-started,'snapshot':snap})
finally:
 print(device('record','stop'))
(out/'driver-output.json').write_text(json.dumps(results,indent=2))
print(out)
