#!/usr/bin/env python3
"""Run from a filtered Pulls list. Usage: drive-proof.py SESSION OUTPUT_DIR SIDE METHOD"""
import re, subprocess, sys, time
from pathlib import Path
from PIL import Image, ImageChops
session, output, side, method = sys.argv[1:]
out = Path(output) / (side + "-" + time.strftime("%Y%m%d-%H%M%S"))
out.mkdir(parents=True)
def run(*args):
    result = subprocess.run(["agent-device", *args, "--session", session], check=True, text=True, capture_output=True)
    print(result.stdout, flush=True)
    return result.stdout
def ref(pattern):
    snap = run("snapshot", "-i")
    for line in snap.splitlines():
        if re.search(pattern, line):
            return line.split()[0]
    raise RuntimeError("Missing target: " + pattern)
run("wait", 'text="Project merge method proof"')
pr = ref(r'\[button\] "Pull request 319,')
run("record", "start", str(out / "interaction.mp4"))
run("press", pr, "--settle")
run("wait", 'label="Merge options"')
run("scroll", "down", "550", "--settle")
run("press", 'label="Merge options"', "--settle")
run("wait", 'text="Create a merge commit"')
run("back", "--settle")
primary = 'role=group label="' + method + '"'
run("press", primary, "--settle")
run("wait", 'label="Cancel"')
# Exclude Android's animated connectivity icons and gesture bar from pixel stability.
for attempt in range(5):
    run("screenshot", str(out / "first.png"))
    time.sleep(0.5)
    run("screenshot", str(out / "second.png"))
    a = Image.open(out / "first.png").crop((0,70,1080,2350))
    b = Image.open(out / "second.png").crop((0,70,1080,2350))
    if ImageChops.difference(a,b).getbbox() is None:
        a.save(out / "confirmation.png")
        print("App viewport stable across captures", flush=True)
        break
else:
    raise RuntimeError("App viewport did not become stable")
run("press", 'label="Cancel"', "--settle")
run("record", "stop")
print("OUTPUT", out)
