import subprocess, sys, time, pathlib, json
from PIL import Image, ImageChops
side, output, session = sys.argv[1:]
out = pathlib.Path(output) / (side + '-' + time.strftime('%Y%m%d-%H%M%S'))
out.mkdir(parents=True)
log=[]
def run(*args):
    command=['agent-device',*map(str,args),'--session',session]
    p=subprocess.run(command,capture_output=True,text=True)
    if p.returncode and args[0]=='screenshot':
        time.sleep(1)
        p=subprocess.run(command,capture_output=True,text=True)
    p.check_returncode()
    return p.stdout

def tap(x,y):
    run('click',x,y)
    time.sleep(3)
def keyboard(label):
    text=run('keyboard','status')
    visible='Keyboard visible: yes' in text
    log.append({'step':label,'keyboardVisible':visible})
    print(label, visible, flush=True)
    return visible

def still(label):
    prev=None
    for i in range(12):
        raw=out/(label+'-raw.png')
        run('screenshot',raw)
        im=Image.open(raw).crop((0,220,1080,2424)).convert('RGB')
        if prev is not None and ImageChops.difference(prev,im).getbbox() is None:
            im.save(out/(label+'.png'))
            return
        prev=im.copy()
        time.sleep(.5)
    raise RuntimeError('Capture did not settle: '+label)
run('record','start',out/'interaction-raw.mp4')
try:
    keyboard('initial')
    tap(300,2170)
    keyboard('composer tapped')
    run('back'); time.sleep(3)
    keyboard('composer keyboard dismissed')
    for attempt in range(3):
        tap(235,2260)
        probe=out/'open-probe.png'
        run('screenshot',probe)
        pixels=Image.open(probe).convert('RGB').crop((160,300,185,1500))
        if sum(r<100 and g<150 and b>180 for r,g,b in pixels.getdata()) > 20:
            break
    else:
        raise RuntimeError('Model picker did not open')
    keyboard('picker opened')
    still('picker-opened')
    if keyboard('before dismissing picker keyboard'):
        run('back'); time.sleep(3)
    keyboard('picker keyboard dismissed')
    tap(133,1120)
    keyboard('Claude provider selected')
    still('provider-selected')
    # The keyboard must remain available on an explicit search tap.
    if keyboard('before explicit search tap'):
        run('back'); time.sleep(3)
    tap(400,895)
    keyboard('search explicitly tapped')
    still('search-tapped')
finally:
    run('record','stop')
    (out/'observations.json').write_text(json.dumps(log,indent=2))
print(out)
