import argparse, pathlib, subprocess, time, re
from PIL import Image, ImageChops
p=argparse.ArgumentParser(); p.add_argument('--session',required=True); p.add_argument('--out',required=True); a=p.parse_args()
out=pathlib.Path(a.out)/time.strftime('%Y%m%d-%H%M%S');out.mkdir(parents=True)
def run(*args):
    r=subprocess.run(['agent-device',*args,'--session',a.session],text=True,capture_output=True); print(r.stdout,flush=True)
    if r.returncode: raise RuntimeError(r.stderr)
    return r.stdout
def press(text,role):
    snapshot=run('snapshot','-i')
    match=re.search(r'^(@\S+) \['+re.escape(role)+r'\] "'+re.escape(text)+r'"',snapshot,re.M)
    if not match: raise RuntimeError('Missing '+role+' '+text)
    run('press',match.group(1),'--settle')
def up():
    s=run('snapshot','-i');press('向上导航' if '向上导航' in s else 'Navigate up','button')
def capture(name):
    last=None
    for i in range(8):
        raw=out/f'{name}-raw-{i}.png';run('screenshot',str(raw));im=Image.open(raw).crop((0,65,1080,2424))
        if last is not None and ImageChops.difference(last,im).getbbox() is None:
            im.save(out/f'{name}.png');return
        last=im;time.sleep(.5)
    raise RuntimeError('App viewport did not settle')
# Start with English selected and a fully relaunched application on its thread list.
press('Settings','group');press('General','button')
run('record','start',str(out/'language-switch.mp4'),'--hide-touches')
press('Language, English','button');press('中文（简体）','radiobutton')
capture('chinese-selected');up();capture('general-after-switch')
# Reverse the change without restarting.
press('语言, 中文（简体）' if '语言,' in run('snapshot','-i') else 'Language, 中文（简体）','button')
press('English','radiobutton');up();capture('english-restored')
run('record','stop');print('OUTPUT',out)
