#!/usr/bin/env bash
# 启动 MCP 前确保 Hub 在 13458 运行（全局唯一）
set -eo pipefail
INSTALL="$(cd "$(dirname "$0")" && pwd)"
PORT="${PCHAT_HTTP_PORT:-13458}"
LOG="$INSTALL/logs/hub.log"
NODE="${PCHAT_NODE:-$(command -v node 2>/dev/null || true)}"
[[ -z "$NODE" ]] && NODE="/usr/local/opt/node@22/bin/node"

mkdir -p "$INSTALL/logs"

if [[ ! -x "$NODE" ]]; then
  echo "[ensure-hub] FATAL: node not found: $NODE" >&2
  exit 1
fi

hub_health() {
  curl -sf -m 2 "http://127.0.0.1:${PORT}/api/health" >/dev/null 2>&1
}

start_hub() {
  if hub_health; then return 0; fi
  echo "[ensure-hub] starting hub on :${PORT}" >> "$LOG"
  nohup "$NODE" "$INSTALL/hub.js" >> "$INSTALL/logs/hub.stdout.log" 2>&1 &
  local i=0
  while [[ $i -lt 80 ]]; do
    hub_health && return 0
    sleep 0.15
    i=$((i + 1))
  done
  return 1
}

if ! start_hub; then
  echo "[ensure-hub] FATAL: Hub not ready on 127.0.0.1:${PORT} (waited ~12s). Run: bash 卡若AI/.../Cursor持久对话/脚本/sync-runtime.sh" >&2
  exit 1
fi

# Cursor 无工作区时 ${workspaceFolder} 可能为空/none/未替换字面量 → 兜底 HOME
ARGS=()
for a in "$@"; do
  case "$a" in
    --workspace=|--workspace=none|--workspace=\$\{workspaceFolder\})
      ARGS+=("--workspace=$HOME")
      ;;
    --workspace=*)
      ARGS+=("$a")
      ;;
    *)
      ARGS+=("$a")
      ;;
  esac
done
if [[ ${#ARGS[@]} -eq 0 ]] || ! printf '%s\n' "${ARGS[@]}" | grep -q '^--workspace='; then
  ARGS+=("--workspace=${PWD:-$HOME}")
fi

exec "$NODE" "$INSTALL/server.js" "${ARGS[@]}"
