"""Drive the real iOS app on a fresh pool lease; backend/Metro and demo project already started.
Arguments: checkout, T3 home, backend origin, Metro URL, session, output directory.
Install first with: vp run mobile:install ios --session SESSION.
"""
import sys, subprocess, urllib.parse, pathlib, time, hashlib
checkout, home, origin, metro, session, output = sys.argv[1:]
out = pathlib.Path(output)
out.mkdir(parents=True, exist_ok=True)
def device(*args, allow_failure=False):
    p = subprocess.run(['agent-device', *args, '--session', session], capture_output=True, text=True)
    if p.returncode and not allow_failure:
        raise RuntimeError(p.stdout + p.stderr)
    return p.stdout
def open_link(path):
    device('open', 'com.t3tools.t3code.dev', path)
    device('alert', 'accept', allow_failure=True)
open_link('t3code-dev://expo-development-client/?' + urllib.parse.urlencode({
    'url': metro, 'disableOnboarding': '1', 'disableFab': '1', 'disableAutoLaunch': '1'}))
device('wait', 'text', 'Add environment', '240000')
p = subprocess.run(['node', 'apps/server/src/bin.ts', 'auth', 'pairing', 'create', '--base-dir', home,
    '--base-url', origin, '--ttl', '15m', '--label', 'evidence'], cwd=checkout,
    capture_output=True, text=True, check=True)
pairing = next(line.removeprefix('Pair URL: ') for line in p.stdout.splitlines() if line.startswith('Pair URL: '))
open_link('t3code-dev://connections/new?' + urllib.parse.urlencode({'pairingUrl': pairing, 'autoConnect':'1'}))
device('wait', 'text', 'Chats', '60000')
open_link('t3code-dev://settings/language')
device('press', 'label="Deutsch"', '--settle')
open_link('t3code-dev://settings/voice')
device('press', 'label="Scenario"', '--settle')
device('press', 'label="Umgebung verwenden"', '--settle')
device('wait', 'text', 'Kein Modell installiert', '60000')
device('press', 'label="Lokales Modell, Kein Modell installiert · Wähle eines zum Herunterladen"', '--settle')
device('wait', 'text', 'Parakeet Unified English 0.6B', '60000')
for attempt in range(3):
    a, b = out / f'benchmarks-{attempt}-a.png', out / f'benchmarks-{attempt}-b.png'
    device('screenshot', str(a))
    time.sleep(0.5)
    device('screenshot', str(b))
    if a.read_bytes() == b.read_bytes():
        print(f'Stable captures: {a.name}, {b.name}; SHA256 {hashlib.sha256(a.read_bytes()).hexdigest()}')
        break
else:
    raise RuntimeError('Captures were not stable')
print(device('snapshot'))
