#!/usr/bin/env python3
"""Drive an installed T3 Code iOS Release app through both appearance mismatches.
Usage: python3 reproduce.py SESSION OUTPUT_PARENT SIDE
Build each commit independently with APP_VARIANT=production, simulator=true,
and buildConfiguration=Release. Disable EXUpdatesEnabled in Expo.plist on
both simulator installs so relaunch cannot replace the commit's JS bundle.
Use the same iPhone 17 Pro / iOS 27.2, default T3 Code theme, 402x874 viewport.
No server, account, model, or seed data is needed for these local settings.
"""
import datetime, pathlib, subprocess, sys, time
session, parent, side = sys.argv[1:]
out = pathlib.Path(parent) / (side + '-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'))
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 or result.stdout)
def press(label):
    device('press', label, '--settle')
def still(label):
    final = out / (label + '.png')
    for attempt in range(5):
        first = out / (label + '-stability-' + str(attempt) + '.png')
        device('screenshot', str(first))
        time.sleep(0.5)
        device('screenshot', str(final))
        if subprocess.run(['compare', '-metric', 'AE', str(first), str(final), 'null:'], capture_output=True).returncode == 0:
            return
    raise RuntimeError('Screen did not become identical in consecutive screenshots: ' + label)
device('settings', 'clear-app-state', 'com.t3tools.t3code')
for system, app in [('dark', 'Light'), ('light', 'Dark')]:
    label = app.lower()
    device('settings', 'appearance', system)
    device('open', 'com.t3tools.t3code', '--relaunch')
    press('label="Settings" role=button')
    press('label="Appearance"')
    device('record', 'start', str(out / (label + '.mp4')))
    try:
        press('label="' + app + ' appearance"')
        press('label="Back"')
        device('scroll', 'bottom', '--settle')
        press('label="About"')
        still(label + '-about')
        device('open', 'com.t3tools.t3code', '--relaunch')
        press('label="Settings" role=button')
        press('label="Chats" role=button')
        still(label + '-chats')
    finally:
        device('record', 'stop')
print(out)
