"""Record a synthetic default-branch push and one Back on the paired iOS app.
Usage: python3 drive-push.py SESSION OUTPUT_DIRECTORY
Start on the existing Push demo thread, main one commit ahead of origin/main.
"""
import subprocess, sys, pathlib, time, hashlib
session, output = sys.argv[1:]
out = pathlib.Path(output)
out.mkdir(parents=True, exist_ok=False)
def run(*args):
    result = subprocess.run(['agent-device', *args, '--session', session], text=True, capture_output=True)
    with (out/'transcript.txt').open('a') as log:
        log.write(' '.join(args)+'\n'+result.stdout+result.stderr+'\n')
    print(' '.join(args), result.returncode, flush=True)
    if result.returncode: raise RuntimeError(result.stderr)
    return result.stdout
run('record','start',str(out/'push.mp4'),'--fps','15')
run('press','label="Git controls"','--settle')
run('press','label="More, Commit, files, branches"','--settle')
run('find','Push, 1 commit ahead','click','--first')
run('wait','text="Push to default branch?"','30000')
run('press','label="Push to main"','--settle')
run('wait','text="Pushed to origin/main"','30000')
run('press','label="Back"','--settle')
run('snapshot','-i')
for attempt in range(4):
    a=out/f'one-back-{attempt}-a.png'; b=out/f'one-back-{attempt}-b.png'
    run('screenshot',str(a)); time.sleep(.5); run('screenshot',str(b))
    if a.read_bytes()==b.read_bytes():
        (out/'after-one-back.png').write_bytes(b.read_bytes()); break
else: raise RuntimeError('Screenshot did not settle')
run('record','stop')
