"""Drive an already paired, empty no-model fallback composer using the real keyboard."""
import argparse, json, subprocess, time
from pathlib import Path
from PIL import Image
p=argparse.ArgumentParser();p.add_argument('platform',choices=['ios','android']);p.add_argument('session');p.add_argument('output_root');a=p.parse_args()
out=Path(a.output_root)/time.strftime('%Y%m%d-%H%M%S');out.mkdir(parents=True)
text='First line of the saved draft\nSecond line stays visible\nThird line and caret'
def run(*args, capture=False):
    r=subprocess.run(['agent-device',*args,'--session',a.session],check=True,text=True,stdout=subprocess.PIPE if capture else None)
    return r.stdout if capture else None
def stable(label):
    previous=None
    for n in range(16):
        path=out/f'{label}-{n}.png'
        run('screenshot',str(path),*(['--normalize-status-bar'] if a.platform=='android' else []))
        pixels=Image.open(path).convert('RGBA').tobytes()
        if pixels==previous:
            (out/f'{label}.png').write_bytes(path.read_bytes());print(f'{label}: identical captures >=500ms apart',flush=True);return
        previous=pixels;time.sleep(.5)
    raise RuntimeError('No stable capture pair; use the recording')
editor='role=text-view' if a.platform=='ios' else 'role=text-field'
back='label="Back"' if a.platform=='ios' else 'label="Navigate up"'
run('record','start',str(out/'flow.mp4'))
try:
    run('press','label="Ask anything"','--settle');run('type',text);stable('multiline-keyboard')
    if a.platform=='android':
        run('back','--settle');run('press',editor,'--settle');stable('keyboard-reopened')
    run('press',back,'--settle')
    raw=json.loads(run('snapshot','--json',capture=True))['data']
    saved=[n for n in raw['nodes'] if n.get('label','').startswith('First line of the saved draft Second line') and n.get('kind') in ('cell','button')]
    if not saved:
        saved=[n for n in raw['nodes'] if n.get('label','').startswith('First line of the saved draft Second line')]
    if not saved: raise RuntimeError('Saved draft row is missing')
    run('press','@'+saved[0]['ref'],'--settle');run('press',editor,'--settle');stable('saved-draft-reopened');run('press',back,'--settle')
finally:
    run('record','stop')
print(out,flush=True)
