"""Run from each checkout, with the app paired to that checkout's fresh server.
Usage: python3 reproduce.py SESSION OUTPUT_DIR
Device: iPad Pro 11-inch (M5), iPadOS 27.2, landscape-left, 1210x834, light.
Start at Settings > Environments. Uses the real software keyboard.
"""
import pathlib, re, subprocess, sys, time
from PIL import Image, ImageChops
session, root = sys.argv[1:]
out = pathlib.Path(root) / time.strftime("%Y%m%d-%H%M%S")
out.mkdir(parents=True)
def run(*args):
    result = subprocess.run(["agent-device", *args, "--session", session], capture_output=True, text=True)
    if result.returncode: raise RuntimeError(result.stdout + result.stderr)
    return result.stdout
def still(label):
    previous = out / (label + "-previous.png")
    current = out / (label + ".png")
    run("screenshot", str(previous))
    for _ in range(8):
        time.sleep(0.5)
        run("screenshot", str(current))
        if ImageChops.difference(Image.open(previous).convert("RGB"), Image.open(current).convert("RGB")).getbbox() is None:
            return
        previous.write_bytes(current.read_bytes())
    raise RuntimeError("Screen never settled: " + label)
run("press", 'label="Add environment"', "--settle")
still("before-focus")
run("record", "start", str(out / "flow.mp4"))
try:
    tree = run("snapshot", "-i")
    address = re.search(r"(@e\d+) \[text-field\]", tree).group(1)
    run("press", address, "--settle")
    run("type", "https://host.tailnet.ts.net")
    still("address-focused")
    run("gesture", "pan", "850", "320", "0", "-200", "500")
    still("after-scroll")
finally:
    run("record", "stop")
print(out)
