#!/usr/bin/env bash
# Switch State Hub MCP/API profile between local dev and fleet tunnel.
set -euo pipefail

PROFILE="${1:-}"
CLAUDE_JSON="${CLAUDE_JSON:-$HOME/.claude.json}"
STATE_HUB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

usage() {
  cat <<'USAGE'
Usage: scripts/mcp_hub_profile.sh <dev|fleet|status>

  dev    — local dev-hub API :8000, MCP :8001
  fleet  — fleet tunnel API :18000, MCP :18001
  status — show detected profile and URLs
USAGE
}

api_healthy() {
  curl -fsS --max-time 2 "${1%/}/state/health" >/dev/null 2>&1
}

detect_profile() {
  if api_healthy "http://127.0.0.1:18000"; then
    echo fleet
  elif api_healthy "http://127.0.0.1:8000"; then
    echo dev
  else
    echo unknown
  fi
}

profile_urls() {
  case "$1" in
    dev)
      API_BASE="http://127.0.0.1:8000"
      MCP_URL="http://127.0.0.1:8001/sse"
      ;;
    fleet)
      API_BASE="http://127.0.0.1:18000"
      MCP_URL="http://127.0.0.1:18001/sse"
      ;;
    *)
      echo "ERROR: unknown profile $1" >&2
      exit 2
      ;;
  esac
}

if [[ -z "$PROFILE" || "$PROFILE" == "-h" || "$PROFILE" == "--help" ]]; then
  usage
  exit 0
fi

if [[ "$PROFILE" == "status" ]]; then
  current="$(detect_profile)"
  echo "detected_profile=${current}"
  if [[ "$current" != "unknown" ]]; then
    profile_urls "$current"
    echo "API_BASE=${API_BASE}"
    echo "MCP_URL=${MCP_URL}"
  fi
  exit 0
fi

profile_urls "$PROFILE"
echo "==> Switching to profile: ${PROFILE}"
echo "    API_BASE=${API_BASE}"
echo "    MCP_URL=${MCP_URL}"

if api_healthy "$API_BASE"; then
  echo "OK: API reachable at ${API_BASE}/state/health"
else
  echo "WARN: API not reachable at ${API_BASE}/state/health"
fi

if command -v claude >/dev/null 2>&1; then
  CONFIG="$(python3 -c "import json; print(json.dumps({'type':'sse','url':'${MCP_URL}'}))")"
  claude mcp add-json -s user dev-hub "$CONFIG" 2>/dev/null || true
  echo "OK: registered dev-hub MCP → ${MCP_URL}"
else
  echo "WARN: claude CLI not found; set MCP manually to ${MCP_URL}"
fi

profile_file="${STATE_HUB_DIR}/.hub-profile"
printf 'API_BASE=%s\nMCP_URL=%s\nPROFILE=%s\n' "$API_BASE" "$MCP_URL" "$PROFILE" >"$profile_file"
echo "OK: wrote ${profile_file}"
echo "Export: export API_BASE=${API_BASE}"