#!/usr/bin/env bash
# Start (or restart) the app for the visual loop.
#   tool/dev/app-run.sh [auto|web|android] [dev|staging|prod]
# The `flutter run` process lives in tmux session "flutter" and logs to
# $PL_RUN_LOG. Only ever ONE of these — this script kills the previous one.
set -uo pipefail
source "$(dirname "$0")/env.sh"

target="${1:-auto}"; envname="${2:-dev}"
mkdir -p "$PL_TMP"

device="$(pl_device)"
if [ "$target" = auto ]; then
  if [ -n "$device" ]; then target=android; else target=web; fi
fi
case "$target" in
  android)
    [ -n "$device" ] || { echo "No Android device/emulator online (adb devices). Use 'web'."; exit 1; }
    dev_args="-d $device"; ready='Flutter run key commands' ;;
  web)
    dev_args="-d web-server --web-port $PL_WEB_PORT"; ready='is being served at' ;;
  *) echo "unknown target '$target'"; exit 2 ;;
esac

tmux kill-session -t flutter 2>/dev/null || true
: > "$PL_RUN_LOG"
tmux new -d -s flutter -c "$PL_APP_DIR" \
  "source '$PL_APP_DIR/tool/dev/env.sh'; fvm flutter run $dev_args --dart-define=ENV=$envname 2>&1 | tee '$PL_RUN_LOG'"

echo "▶ flutter run ($target, ENV=$envname) starting in tmux 'flutter' — log: $PL_RUN_LOG"
for i in $(seq 1 300); do
  if grep -q "$ready" "$PL_RUN_LOG" 2>/dev/null; then
    echo "✓ ready after ${i}s"
    if [ "$target" = web ]; then
      pl_ensure_chrome || exit 1
      node "$PL_APP_DIR/tool/dev/browser.mjs" open "http://localhost:$PL_WEB_PORT/" || exit 1
      # give the Flutter engine a moment to attach to DWDS and paint
      sleep 4
    fi
    exec "$PL_APP_DIR/tool/dev/app-shot.sh"
  fi
  if ! tmux has-session -t flutter 2>/dev/null; then
    echo "✗ flutter run exited early. Last lines:"; tail -n 30 "$PL_RUN_LOG"; exit 1
  fi
  sleep 1
done
echo "✗ timed out waiting for '$ready'. Last lines:"; tail -n 30 "$PL_RUN_LOG"; exit 1
