#!/usr/bin/env python3
"""Drive T3 Code's real Android photo picker from an open, empty composer.
Requires: agent-device, Pillow; an already paired Pixel 9 dev-client session.
Usage: picker-driver.py SESSION OUTPUT_PARENT LABEL [--thread]
The same photo must already exist in the device library for both revisions.
"""
import sys, subprocess, pathlib, re, datetime, time
from PIL import Image, ImageChops
session, parent, label = sys.argv[1:4]
out = pathlib.Path(parent) / (label + '-' + datetime.datetime.now().strftime('%Y%m%dT%H%M%S'))
out.mkdir(parents=True)
def run(*args):
    p = subprocess.run(['agent-device', *args, '--session', session], text=True, capture_output=True)
    if p.returncode:
        raise RuntimeError(p.stdout + p.stderr)
    return p.stdout
run('record', 'start', str(out / 'interaction.mp4'), '--hide-touches')
try:
    run('press', 'label="Add attachment"', '--settle')
    run('press', 'text="Photo Library"', '--settle')
    snap = run('snapshot', '-i')
    photo = re.search(r'(@e\d+) \[group\] "Photo taken[^"\n]+"', snap)
    if not photo: raise RuntimeError('No photo in real system picker')
    run('press', photo[1], '--settle')
    snap = run('snapshot', '-i')
    done = re.search(r'(@e\d+) \[button\] "Done"', snap)
    if not done: raise RuntimeError('Picker Done control missing')
    run('press', done[1], '--settle')
    if '--thread' in sys.argv:
        run('press', 'label="Done" role="group"', '--settle')
    snap = run('snapshot', '-i')
    (out / 'composer.txt').write_text(snap)
    previous = None
    def capture_image(path):
        im = Image.open(path)
        return im.crop((0, 2100, 1080, 2424)) if '--thread' in sys.argv else im
    for index in range(8):
        target = out / f'stability-{index}.png'
        run('screenshot', str(target))
        if previous and ImageChops.difference(capture_image(previous), capture_image(target)).getbbox() is None:
            capture_image(target).save(out / 'composer.png')
            print('Stable screenshot:', out / 'composer.png')
            break
        previous = target
        time.sleep(0.5)
    else:
        raise RuntimeError('No pixel-identical screenshot pair')
finally:
    run('record', 'stop')
print('Run:', out)
