"""Run on a paired, empty mobile app with a synthetic 'demo' project.
Usage: python3 drive.py SESSION OUTPUT_DIRECTORY SIDE
Keep stable.py alongside this driver. Recordings begin after selecting demo.
"""
import subprocess,sys,pathlib,re,time
session,out,side=sys.argv[1:]; out=pathlib.Path(out);out.mkdir(parents=True,exist_ok=True)
def run(*args):
    p=subprocess.run(['agent-device',*args,'--session',session],text=True,capture_output=True)
    print(p.stdout,flush=True)
    if p.returncode: raise RuntimeError(p.stderr)
    return p.stdout
def stable(name):
    subprocess.run([sys.executable,str(pathlib.Path(__file__).with_name('stable.py')),str(out/f'{side}-{name}.png'),session],check=True)
run('press','label="New chat"','--settle')
run('wait','label="demo"', '30000')
run('press','label="demo"','--settle')
run('wait','label="Ask anything"','30000')
run('record','start',str(out/f'{side}-flow.mp4'),'--fps','10','--hide-touches')
run('fill','label="Ask anything"','a'*68+'😀 and the rest of the prompt','--settle')
stable('composer')
run('press','label="Back"','--settle')
run('wait','text="Unsent"','30000')
snapshot=run('snapshot','-i');(out/f'{side}-draft-ax.txt').write_text(snapshot)
row=re.search(r'(@e\d+(?:~\w+)?) \[cell\] "a{68}',snapshot)
if not row: raise RuntimeError('Draft row not found')
run('longpress',row[1],'1000','--settle')
run('press','label="Discard"','--settle')
run('wait','text="Discard draft?"','30000')
stable('confirmation')
(out/f'{side}-confirmation-ax.txt').write_text(run('snapshot','-i'))
run('press','label="Cancel"','--settle')
run('record','stop')
