#!/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]

Check Metro (/status) and reload connected simulators/devices (/reload).
Does not restart Docker.

  --clear      Also wipe Metro/Expo disk caches inside mobile-client, then reload
  -h, --help   Show this help
EOF
}

clear=false
case "${1:-}" in
  "" ) ;;
  --clear) clear=true ;;
  -h|--help|help) usage; exit 0 ;;
  *)
    echo "unknown option: $1" >&2
    usage >&2
    exit 1
    ;;
esac

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

port="${MOBILE_CLIENT_PORT:-8081}"
base="http://localhost:${port}"
app="${MOBILE_APP:-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 mobile-client" >&2
  exit 1
fi
echo "  ok · ${status}"

if [ "${clear}" = true ]; then
  require_docker
  echo "Clearing Metro/Expo disk caches in mobile-client ..."
  # Same paths as the dashboard Clear cache button; running Metro may keep
  # some transforms in memory — use restart mobile-client if still stale.
  dc exec -T mobile-client 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 mobile-client (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 mobile-client"
