#!/usr/bin/env bash
# Check Metro is up and tell connected apps to reload — no container restart.
# Usage: run-stack reload [--clear]
source "$(dirname "${BASH_SOURCE[0]}")/common.sh"

usage() {
  cat <<EOF
Usage: ${RUN_CMD:-run-stack} reload [--clear] [app]

Check Metro (/status) and reload connected simulators/devices (/reload).
Does not restart Docker. Without an app name, the built-in mobile app.

  --clear      Also wipe that app's Metro/Expo disk caches, then reload
  -h, --help   Show this help
EOF
}

clear=false
target=""
while [ $# -gt 0 ]; do
  case "$1" in
    --clear) clear=true ;;
    -h|--help|help) usage; exit 0 ;;
    -*)
      echo "unknown option: $1" >&2
      usage >&2
      exit 1
      ;;
    *) target="$1" ;;
  esac
  shift
done

ensure_env
if ! mobile_enabled; then
  echo "error: mobile is disabled (RUN_MOBILE=false)" >&2
  exit 1
fi
use_mobile_app "${target}" || exit 1

port="${MOBILE_CLIENT_PORT:-8081}"
base="http://localhost:${port}"
app="${MOBILE_APP:-mobile-client}"
service="${MOBILE_SERVICE:-mobile-client}"

echo "Metro check:  curl -s \"${base}/status\""
if ! status="$(curl -fsS --max-time 3 "${base}/status" 2>/dev/null)"; then
  echo "error: Metro is not reachable on ${base}" >&2
  echo "       start it with: ${RUN_CMD:-run-stack} up ${service}" >&2
  exit 1
fi
echo "  ok · ${status}"

if [ "${clear}" = true ]; then
  require_docker
  echo "Clearing Metro/Expo disk caches in ${service} ..."
  # Same paths as the dashboard Clear cache button; running Metro may keep
  # some transforms in memory — use restart ${service} if still stale.
  dc exec -T "${service}" sh -lc \
    "rm -rf \
       \"/app/apps/${app}/.expo\" \"/app/apps/${app}/node_modules/.cache\" \
       /app/.expo /app/node_modules/.cache \
       /tmp/metro-* /tmp/haste-* /tmp/react-* /root/.expo \
       2>/dev/null; true" \
    || echo "  ! could not exec into ${service} (is it up?)" >&2
fi

echo "Reload:       curl -s \"${base}/reload\""
if ! curl -fsS --max-time 3 "${base}/reload" >/dev/null 2>&1; then
  # Some Metro builds return empty/non-2xx but still broadcast; try GET anyway.
  curl -sS --max-time 3 "${base}/reload" >/dev/null 2>&1 || true
fi
echo "  reload signal sent — check the simulator/device"
echo
echo "If the UI is still stale: ${RUN_CMD:-run-stack} restart ${service}"
