#!/usr/bin/env bash
set -euo pipefail
# Preconditions: paired with a fresh proof server; Changed files is open on the review.
# GitHub's pullRequestDiffDebug.ts Viewed mark is saved; test files are included.
session="${T3_DEVICE_SESSION:?}"
output="${T3_PROOF_OUTPUT:?}"
mkdir -p "$output"
ad() { agent-device "$@" --session "$session"; }
capture_pair() {
  for attempt in 1 2 3 4 5; do
    ad screenshot "$output/$1-$attempt-a.png" --normalize-status-bar
    sleep 0.5
    ad screenshot "$output/$1-$attempt-b.png" --normalize-status-bar
    if python3 - "$output" "$1" "$attempt" <<'PYTHON'
import sys
from PIL import Image, ImageChops
root,label,attempt=sys.argv[1:]
a=Image.open(f'{root}/{label}-{attempt}-a.png').convert('RGB').crop((0,48,402,874))
b=Image.open(f'{root}/{label}-{attempt}-b.png').convert('RGB').crop((0,48,402,874))
if ImageChops.difference(a,b).getbbox() is not None:
    sys.exit(1)
b.save(f'{root}/{label}.png')
PYTHON
    then return; fi
  done
  echo "App content has not settled" >&2
  exit 1
}
open_target() {
  ad press 'label="View diff for apps/mobile/src/features/pull-requests/pullRequestDiffDebug.test.ts, 6 additions, 0 deletions"' --settle
  ad scroll down --pixels 400 --duration-ms 800 --settle
}
if [ "${T3_PROOF_RESUME:-0}" != 1 ]; then
  ad record start "$output/interaction.mp4" --hide-touches
  open_target
fi
capture_pair saved-viewed
ad press 382 344 --settle
ad screenshot "$output/unviewed-expanded.png" --normalize-status-bar
ad press 382 344 --settle
ad screenshot "$output/viewed-folded.png" --normalize-status-bar
ad press 120 344 --settle
ad screenshot "$output/manual-expanded.png" --normalize-status-bar
ad back --settle
open_target
capture_pair reopened
ad record stop
