import argparse, subprocess, time, pathlib, json
from PIL import Image, ImageChops
p=argparse.ArgumentParser()
p.add_argument('--session',required=True);p.add_argument('--config',required=True);p.add_argument('--out',required=True);p.add_argument('--side',required=True)
a=p.parse_args(); out=pathlib.Path(a.out)/f'{a.side}-{time.strftime("%Y%m%d-%H%M%S",time.gmtime())}';out.mkdir(parents=True)
log=[]
def call(*args):
    r=subprocess.run(['agent-device',*map(str,args),'--session',a.session,'--config',a.config],capture_output=True,text=True,check=True)
    log.append({'action':list(map(str,args)),'output':r.stdout});(out/'actions.json').write_text(json.dumps(log,indent=2));return r.stdout

def still(label):
    for n in range(8):
        first=out/f'{label}-settle-{n}.png';last=out/f'{label}.png'
        call('screenshot',first);time.sleep(.5);call('screenshot',last)
        if ImageChops.difference(Image.open(first).convert('RGB'),Image.open(last).convert('RGB')).getbbox() is None:
            print(f'STABLE {label}',flush=True);return
    raise RuntimeError(f'{label} did not settle')
def press(label): call('press',f'role=button label="{label}"','--settle')
for theme in ('light','dark'):
    call('settings','appearance',theme)
    call('record','start',out/f'{theme}-interaction.mp4','--hide-touches')
    try:
        still(f'{theme}-idle')
        press('ctrl');still(f'{theme}-ctrl-latched')
        call('type','c');still(f'{theme}-ctrl-consumed')
        press('ctrl');press('ctrl');still(f'{theme}-ctrl-toggled-off')
        press('alt');still(f'{theme}-alt-latched')
        press('ctrl');still(f'{theme}-latch-moves-to-ctrl')
        call('type','c');still(f'{theme}-final-consumed')
    finally: call('record','stop')
print(out,flush=True)
