#!/usr/bin/env bash
# Hot reload (r) or hot restart (R) the running app, then screenshot and surface
# any new errors from the run log.
#   tool/dev/app-reload.sh [r|R]   (default R — reliable on every target)
set -uo pipefail
source "$(dirname "$0")/env.sh"
key="${1:-R}"
tmux has-session -t flutter 2>/dev/null || { echo "no 'flutter' tmux session — run tool/dev/app-run.sh first"; exit 1; }
before=$(wc -l < "$PL_RUN_LOG")
tmux send-keys -t flutter "$key" ''
marker='Reloaded|Restarted application|Performing hot restart|Hot restart|Hot reload'
for _ in $(seq 1 90); do
  if tail -n +"$((before + 1))" "$PL_RUN_LOG" | grep -Eq "$marker"; then break; fi
  sleep 1
done
new="$(tail -n +"$((before + 1))" "$PL_RUN_LOG")"
echo "── run log since reload ──"; echo "$new" | tail -n 15
if echo "$new" | grep -Eiq 'exception|error|failed'; then
  echo "⚠ errors/exceptions above — fix before trusting the screenshot"
fi
[ -z "$(pl_device)" ] && sleep 2
exec "$PL_APP_DIR/tool/dev/app-shot.sh"
