#!/usr/bin/env python3
"""Capture a real, already-paired iOS app at the idle provider screen.
Run from the checkout being tested: python driver.py SESSION OUTPUT_DIRECTORY.
Both providers must be the real old npm-global installs; the server database is fresh.
No provider process or server response is mocked.
"""
import pathlib,subprocess,sys,time,re,json
session,out=sys.argv[1:];out=pathlib.Path(out);out.mkdir(parents=True,exist_ok=True)
log=[]
def call(*args):
 p=subprocess.run(['agent-device',*args,'--session',session],capture_output=True,text=True)
 log.append({'elapsed':round(time.monotonic()-start,3),'args':args,'code':p.returncode,'output':p.stdout+p.stderr})
 (out/'steps-private.json').write_text(json.dumps(log,indent=2))
 if p.returncode:raise RuntimeError(p.stdout+p.stderr)
 return p.stdout

def ref(tree,label):
 m=re.search(r'(@e\d+) \[button\] "'+re.escape(label)+'"',tree)
 if not m:raise RuntimeError('Missing button '+label+'\n'+tree)
 return m[1]
start=time.monotonic()
tree=call('snapshot','-i')
if 'Provider updated.' in tree or 'Provider status refreshed.' in tree:raise RuntimeError('Starting state is not idle')
call('screenshot',str(out/'idle-1.png'));time.sleep(.5);call('screenshot',str(out/'idle-2.png'))
call('record','start',str(out/'raw.mp4'),'--hide-touches')
time.sleep(2)
call('press',ref(tree,'Update Codex'))
tree=call('snapshot','-i')
call('press',ref(tree,'Update Claude'))
call('screenshot',str(out/'second-update.png'))
# Keep the real UI visible until Codex completes, and until any accepted Claude update completes.
for i in range(45):
 tree=call('snapshot','-i')
 if 'Provider updated.' in tree and not re.search(r'Checking for the latest|Running npm|Update queued|Waiting for|Verifying the installed',tree):break
 time.sleep(1)
call('screenshot',str(out/'complete-1.png'));time.sleep(.5);call('screenshot',str(out/'complete-2.png'))
time.sleep(2)
call('record','stop')
print(tree)
