"""Drive the real iOS client. Run from the app checkout; home contains seeded alpha/beta."""
import os, pathlib, subprocess, sys, time
home, port, session, side, choice, output = sys.argv[1:]
out = pathlib.Path(output)
out.mkdir(parents=True, exist_ok=True)
text = 'Keep this draft and its image' if choice == 'alpha' else 'Keep this no-project draft'
def run(args, check=True):
    r = subprocess.run(args, capture_output=True, text=True, env={**os.environ,'T3CODE_PORT':port})
    if check and r.returncode: raise RuntimeError(r.stderr[-1000:] + r.stdout[-1000:])
    return r

def device(*args, check=True):
    return run(['agent-device',*args,'--session',session],check)
def press(selector):
    return device('press',selector,'--settle')
def cli(*args):
    return run(['node','apps/server/src/bin.ts',*args,'--base-dir',home])
def stable(name):
    p = out / (name+'.png')
    for n in range(5):
        a = out / (name+f'-check-{n}.png')
        device('screenshot',str(a))
        time.sleep(.5)
        device('screenshot',str(p))
        if run(['compare','-metric','AE',str(a),str(p),'null:'],False).returncode == 0: return
    raise RuntimeError('Screen did not stabilize')

# Returning to the home list before starting keeps every recording's starting point the same.
if not os.environ.get('RESUME_AFTER_ORIGINAL'):
    device('record','start',str(out / f'{side}-{choice}.mp4'),'--fps','15','--hide-touches')
    press('role=button label="New chat"')
    if '"Choose project"' not in device('snapshot','-i').stdout:
        press('role=button label="alpha"')
    press('role=button label="beta"')
    device('fill','role=text-view',text,'--settle')
    press('role=button label="Add attachment"')
    press('role=button label="Photo Library"')
    # The stock photo picker sometimes exposes no accessibility tree; these are its verified
    # first stock photo and Done positions on this 402x874 iPhone simulator.
    device('screenshot',str(out / f'{side}-{choice}-photo-picker.png'))
    device('press','65','402','--settle')
    device('press','364','134','--settle')
    intro=device('snapshot','-i').stdout
    if '[button] "Continue"' in intro: press('role=button label="Continue"')
    stable(f'{side}-{choice}-original')
press('role=button label="Back"')
cli('project','remove',str(pathlib.Path(home)/'workspaces/beta'),'--force')
press(f'label="{text}"')
# Cancelling the project picker must leave the orphaned draft under Unsent.
press('role=button label="Chats"')
stable(f'{side}-{choice}-cancelled')
press(f'label="{text}"')
press(f'role=button label="{choice if choice == "alpha" else "No project"}"')
stable(f'{side}-{choice}-result')
device('record','stop')
print(device('snapshot','-i').stdout)
