#!/usr/bin/env bash
set -euo pipefail
side="$1"
kind="${2:-plugin}"
out="${PROOF_ROOT:?}/$side/final-$(date +%s)"
mkdir -p "$out"
printf '%s\n' "$out"
ad() { agent-device "$@" --session proof42191; }
capture() {
  for n in 1 2 3 4 5 6; do
    ad screenshot "$out/$1-$n-a.png"
    sleep 0.5
    ad screenshot "$out/$1-$n-b.png"
    if cmp -s "$out/$1-$n-a.png" "$out/$1-$n-b.png"; then
      cp "$out/$1-$n-b.png" "$out/$1.png"
      printf 'STABLE %s attempt %s\n' "$1" "$n"
      return
    fi
  done
  printf 'NOT STABLE %s\n' "$1"; return 1
}
ad record start "$out/$kind-flow.mp4"
if [ "$kind" = plugin ]; then
  ad fill 'role=text-field' '/bro' --settle
  capture skill-label
  ad fill 'role=text-field' '/t3-pstack' --settle
  capture plugin-search
  ad fill 'role=text-field' '/bro' --settle
  if [ "$side" = base ]; then label='skill:bro, Review the current patch'; else label='skill:t3-pstack:bro, Review the current patch'; fi
  ad click "label=\"$label\"" --settle
  ad snapshot -i
  capture invocation
else
  ad fill 'role=text-field' '/review-code' --settle
  capture codex-display-name
fi
ad record stop
