import subprocess, sys, time
from pathlib import Path
session, side, out = sys.argv[1:4]
root = Path(out)
root.mkdir(parents=True, exist_ok=True)
def ad(*args):
    result = subprocess.run(['agent-device', *args, '--session', session], text=True, capture_output=True)
    with (root / f'{side}-driver.log').open('a') as log:
        log.write(result.stdout + result.stderr)
    if result.returncode:
        raise RuntimeError(f'agent-device {args[0]} failed; see driver log')
    return result.stdout
def press(label):
    return ad('press', f'label="{label}"', '--settle')
def stable(label):
    first = root / f'{side}-{label}-1.png'
    second = root / f'{side}-{label}.png'
    ad('wait', 'stable', '500', '10000')
    ad('screenshot', str(first))
    time.sleep(0.5)
    ad('screenshot', str(second))
    result = subprocess.run(['compare', '-metric', 'AE', str(first), str(second), 'null:'], text=True, capture_output=True)
    if result.returncode:
        raise RuntimeError(f'{label}: screenshots differ: {result.stderr}')
    print(f'{label}: identical screenshots 500 ms apart', flush=True)
def open_commit():
    press('Git controls')
    press('More, Commit, files, branches')
    press('Commit, 2 files changed')
if '--from-selected' not in sys.argv:
    ad('record', 'start', str(root / f'{side}-raw.mp4'))
    open_commit()
    press('later.txt')
    ad('fill', 'role=text-view', 'Commit the first change', '--settle')
    press('Changed files')
stable('selected')
press('Commit on a new branch')
ad('wait', 'text', 'Action failed', '30000')
ad('screenshot', str(root / f'{side}-failure-private.png'))
ad('wait', 'absent', 'label="Action failed"', '30000')
open_commit()
stable('reopened')
ad('snapshot', '-i')
ad('record', 'stop')
print('Reopened commit sheet captured. Inspect the selection in the images and recording.', flush=True)
