"""Run from native Settings > General with app language Deutsch.

The capture sessions used the equivalent commands with refs from each fresh
snapshot. This wrapper resolves those refs again so they are not hard-coded.
Pass the already connected agent-device session as the sole argument.
"""
import re
import subprocess
import sys

session = sys.argv[1]

def run(*args):
    return subprocess.check_output(
        ['agent-device', *args, '--session', session], text=True
    )

def click(role, matches):
    snapshot = run('snapshot', '-i')
    for line in snapshot.splitlines():
        item = re.match(r'(@\S+) \[' + re.escape(role) + r'\] "(.*)"', line)
        if item and matches(item[2]):
            run('click', item[1], '--settle')
            return
    raise RuntimeError('Required control not found')

click('button', lambda text: text == 'Sprache, Deutsch')
click('radiobutton', lambda text: text == '日本語')
run('back', '--settle')
run('back', '--settle')
click('button', lambda text: text.startswith('T3 アカウント,'))
click('button', lambda text: text == 'T3 Connect')
