"""Drive the real iOS app; capture its screen and native accessibility tree.
Usage: python3 language-proof.py SESSION OUTPUT_DIRECTORY
The matching native client must already be installed and connected to Metro.
"""
import pathlib, subprocess, sys, time
from PIL import Image, ImageChops
session, destination = sys.argv[1:]
out = pathlib.Path(destination) / time.strftime('%Y%m%d-%H%M%S')
out.mkdir(parents=True)

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

def snapshot(name):
    tree = device('snapshot', '-i')
    (out / (name + '.txt')).write_text(tree)
    return tree

def press(label):
    device('press', 'label="' + label + '"')

def capture(name):
    snapshot(name)
    previous = out / (name + '-check.png')
    target = out / (name + '.png')
    device('screenshot', str(previous))
    for _ in range(6):
        time.sleep(0.5)
        device('screenshot', str(target))
        if ImageChops.difference(Image.open(previous).convert('RGB'), Image.open(target).convert('RGB')).getbbox() is None:
            return
        previous.write_bytes(target.read_bytes())
    raise RuntimeError('Screen did not settle: ' + name)

# Begin at the English Chats root with no environments connected.
device('wait', 'text', 'No environments connected')
device('record', 'start', str(out / 'language-switch.mp4'))
capture('01-english-chats')
press('Settings')
press('General')
press('Language, English')
press('Deutsch')
snapshot('02-german-language')
press('Back')
press('Back')
capture('03-german-settings')
press('Chats')
capture('04-german-chats')
tree = snapshot('german-chat-tree')
press('Einstellungen' if '[button] "Einstellungen"' in tree else 'Settings')
press('Tableiste')
capture('05-german-tab-settings')
press('Back')
device('open', 'com.t3tools.t3code.dev', '--relaunch')
device('wait', 'text', 'Keine Umgebungen verbunden', '120000')
capture('06-german-cold-relaunch')
# Verify the reverse language change on both sides as well.
tree = snapshot('cold-chat-tree')
press('Einstellungen' if '[button] "Einstellungen"' in tree else 'Settings')
press('Allgemein')
press('Sprache, Deutsch')
press('English')
press('Back')
press('Back')
capture('07-english-restored')
device('record', 'stop')
print(out)
