#!/usr/bin/env python3
"""Run from the checkout whose agent-device session is connected.
Usage: python3 capture-pairing.py SESSION SIDE OUTPUT_ROOT
Start on Settings > Environments, with zero connections.
"""
import datetime, os, pathlib, subprocess, sys, time
session, side, root = sys.argv[1:]
out = pathlib.Path(root) / (side + '-' + datetime.datetime.now().strftime('%Y%m%d-%H%M%S'))
out.mkdir(parents=True)
def ad(*args):
    return subprocess.run(['agent-device', *args, '--session', session], check=True, text=True, capture_output=True).stdout
# Record the same interaction on both commits, without development-client chrome.
ad('record', 'start', str(out / 'interaction.mp4'))
ad('press', 'role=button label="Add environment"', '--settle')
ad('fill', 'label="Address"', 'https://studio-workstation.example-tailnet.ts.net:8443', '--settle')
ad('press', 'label="Code"', '--settle')
# Require two identical screenshots, separated by at least 500 ms.
# Set NORMALIZE_STATUS_BAR=1 for the base recording; leave unset for head.
# Normalization animated the charging indicator on head.
flags = ["--normalize-status-bar"] if os.environ.get("NORMALIZE_STATUS_BAR") == "1" else []
for attempt in range(12):
    first, second = out / f'stability-{attempt}-a.png', out / f'stability-{attempt}-b.png'
    ad('screenshot', str(first), *flags)
    time.sleep(.5)
    ad('screenshot', str(second), *flags)
    if first.read_bytes() == second.read_bytes():
        (out / 'unfocused-address.png').write_bytes(second.read_bytes())
        break
else:
    raise RuntimeError('No identical screenshot pair; inspect raw captures')
ad('press', 'label="Address"', '--settle')
ad('screenshot', str(out / 'focused-address.png'))
ad('record', 'stop')
print(out)
