"""Android composer reproduction; run identically with each installed commit.
Prerequisite: Pixel 9 / Android 36 / Gboard, light theme, paired app,
empty focused New thread composer. No provider turn is sent.
Run: python3 reproduce.py SESSION OUTPUT_DIRECTORY
"""
import pathlib, subprocess, sys, time
session, out = sys.argv[1:]
out = pathlib.Path(out) / time.strftime('%Y%m%d-%H%M%S')
out.mkdir(parents=True)
def device(*args):
    r = subprocess.run(['agent-device', *args, '--session', session], text=True, capture_output=True)
    if r.returncode:
        print(r.stdout, r.stderr, flush=True)
        r.check_returncode()
    return r.stdout

def stable_shot(label):
    # Compare pixels in the composer text, excluding the system clock and controls.
    # Final public stills show this same text region; raw screens stay private.
    previous = None
    for i in range(8):
        path = out / f'{label}-{i}.png'
        device('screenshot', str(path))
        crop = subprocess.check_output(['convert', str(path), '-crop', '1080x330+0+1080', '+repage', 'rgba:-'])
        if crop == previous:
            print(f'{label}: identical composer captures at least 500 ms apart: {path.name}', flush=True)
            return path
        previous = crop
        time.sleep(0.5)
    raise RuntimeError('Composer did not stabilize; inspect raw screenshots')

prompt = ' '.join(f'Line {i:02d} alpha beta gamma.' for i in range(1,31)) + ' '
assert len(prompt) == 780
(out / 'prompt.txt').write_text(prompt)
print(device('type', prompt), flush=True)
print(device('snapshot', '-i'), flush=True)
# Screen recording captures the continuous gesture and insertion without another tap.
print(device('record', 'start', str(out / 'interaction.mp4')), flush=True)
print(device('screenshot', str(out / 'before-scroll.png')), flush=True)
print(device('gesture', 'pan', '545', '1170', '0', '180', '800'), flush=True)
print(device('screenshot', str(out / 'after-scroll.png')), flush=True)
print(device('type', 'ZZZ'), flush=True)
print(device('snapshot', '-i'), flush=True)
print(device('record', 'stop'), flush=True)
print('Stable result:', stable_shot('result'), flush=True)
