#!/usr/bin/env python3
"""Capture the same review-row expansion in either checked-out mobile build.

Prerequisites: run that checkout's backend and Metro, load its dev-client URL,
pair the client, then Pulls -> search 34380 -> All states -> open the PR.
The review row must be expanded before starting this capture driver.
"""
import argparse
import hashlib
import pathlib
import subprocess
import time

p = argparse.ArgumentParser()
p.add_argument('--session', required=True)
p.add_argument('--output', required=True)
p.add_argument('--side', choices=['base', 'head'], required=True)
a = p.parse_args()
out = pathlib.Path(a.output) / (a.side + '-' + time.strftime('%Y%m%d-%H%M%S'))
out.mkdir(parents=True)

def run(*args):
    return subprocess.run(['agent-device', *args, '--session', a.session],
                          check=True, capture_output=True, text=True).stdout

row = 'label="Approved by Yash-Singh1, 1 approved"'
run('press', row, '--settle')
run('record', 'start', str(out / 'expand.mp4'), '--hide-touches')
run('press', row, '--settle')
time.sleep(1)
for attempt in range(5):
    first = out / ('stable-' + str(attempt) + '-a.png')
    second = out / ('stable-' + str(attempt) + '-b.png')
    run('screenshot', str(first))
    time.sleep(.5)
    run('screenshot', str(second))
    if hashlib.sha256(first.read_bytes()).digest() == hashlib.sha256(second.read_bytes()).digest():
        (out / 'expanded.png').write_bytes(second.read_bytes())
        break
else:
    raise RuntimeError('No identical screenshots; inspect before publishing')
run('record', 'stop')
(out / 'snapshot.txt').write_text(run('snapshot', '-i'))
print(out)
