"""Record Settings search tab switching in an already-open, unpaired iOS app.
Usage: python3 reproduce.py SESSION OUTPUT_DIRECTORY
Start each side from Chats with empty search and the keyboard closed.
"""
import pathlib
import subprocess
import sys
import time
from datetime import datetime, timezone

session = sys.argv[1]
out = pathlib.Path(sys.argv[2]) / datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
out.mkdir(parents=True)

def run(*args):
    result = subprocess.run(['agent-device', *args, '--session', session], text=True, capture_output=True)
    print(result.stdout, flush=True)
    if result.returncode:
        raise RuntimeError(result.stderr)
    return result.stdout

def capture(label):
    first = out / f'{label}-settle.png'
    final = out / f'{label}.png'
    run('screenshot', str(first))
    time.sleep(0.5)
    run('screenshot', str(final))
    difference = subprocess.run(['compare', '-metric', 'AE', str(first), str(final), 'null:'], capture_output=True, text=True)
    if difference.returncode:
        raise RuntimeError(f'Capture did not settle: {difference.stderr}')

run('record', 'start', str(out / 'interaction.mp4'))
run('click', 'label="Settings" role=button', '--settle')
run('click', 'label="Search" role=button', '--settle')
run('fill', 'role=search', 'version', '--delay-ms', '150', '--settle')
run('keyboard', 'return')
(out / 'before-switch.txt').write_text(run('snapshot', '-i'))
capture('filtered-before-switch')
run('click', 'label="Chats" role=button', '--settle')
run('click', 'label="Settings" role=button', '--settle')
state = run('snapshot', '-i')
(out / 'after-switch.txt').write_text(state)
capture('settings-after-switch')
if '[button] "Search"' in state:
    run('click', 'label="Search" role=button', '--settle')
    (out / 'reopened.txt').write_text(run('snapshot', '-i'))
run('record', 'stop')
print(f'Evidence directory: {out}', flush=True)
