#!/usr/bin/env python3
"""Run from the checked-out app after pairing and opening its Codex composer.
Usage: python3 capture.py SESSION OUTPUT_DIRECTORY
Requires agent-device and Pillow. Outputs a fresh timestamped run directory.
The composer must be focused with the software keyboard visible.
"""
import datetime, pathlib, subprocess, sys, time
from PIL import Image, ImageChops
session, output = sys.argv[1:]
out = pathlib.Path(output) / datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
out.mkdir(parents=True)
def device(*args):
    subprocess.run(['agent-device', *map(str,args), '--session',session],check=True)
device('fill','role=text-field','/','--settle')
device('record','start',out/'interaction.mp4','--hide-touches')
device('type','review')
device('wait','text','skill:review')
for attempt in range(8):
    a,b=out/f'stable-{attempt}-a.png',out/f'stable-{attempt}-b.png'
    device('screenshot',a)
    time.sleep(.5)
    device('screenshot',b)
    if ImageChops.difference(Image.open(a),Image.open(b)).getbbox() is None:
        (out/'menu.png').write_bytes(b.read_bytes())
        break
else:
    raise RuntimeError('No identical screenshot pair; inspect captures before using')
device('record','stop')
print(out)
