import subprocess, sys, pathlib, time
session, phase, out = 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], capture_output=True, text=True, timeout=120)
    print(p.stdout, p.stderr, flush=True)
    if p.returncode: raise RuntimeError(args)
def tap(label): run('press', 'label="'+label+'"', '--settle')
def text(value): run('press', 'text="'+value+'"', '--settle')
if phase == 'create':
    tap('Terminal'); text('Open new terminal')
    run('type', "export PS1='demo> '; clear; printf 'Terminal 1 ready\\n'; sleep 3600")
    run('keyboard', 'enter')
    run('back', '--settle')
elif phase in ('head', 'base'):
    run('record', 'start', str(out/(phase+'.mp4')), '--hide-touches')
    tap('Navigate up'); tap('Terminal'); text('sleep')
    if phase == 'head':
        tap('Close terminal'); text('Cancel'); tap('Close terminal')
    run('screenshot', str(out/(phase+'-1.png')))
    time.sleep(.5)
    run('screenshot', str(out/(phase+'-2.png')))
    if phase == 'head': text('Confirm')
    run('record', 'stop')
elif phase == 'multi':
    run('record', 'start', str(out/'head-multi.mp4'), '--hide-touches')
    tap('Terminal options')
    run('screenshot', str(out/'two-live.png'))
    run('back', '--settle')
    tap('Close terminal'); text('Confirm')
    run('screenshot', str(out/'remaining-1.png'))
    time.sleep(.5)
    run('screenshot', str(out/'remaining-2.png'))
    tap('Terminal options')
    run('screenshot', str(out/'one-live.png'))
    run('back', '--settle')
    run('record', 'stop')
elif phase == 'second':
    tap('Terminal options'); text('Open new terminal')
    run('type', "export PS1='demo> '; clear; printf 'Terminal 2 ready\\n'; sleep 3600")
    run('keyboard', 'enter'); run('back', '--settle')
elif phase == 'base-multi':
    run('record', 'start', str(out/'base-multi.mp4'), '--hide-touches')
    tap('Terminal options')
    run('screenshot', str(out/'base-two-1.png'))
    time.sleep(.5)
    run('screenshot', str(out/'base-two-2.png'))
    run('back', '--settle')
    run('record', 'stop')
