#!/usr/bin/env bash
# IJFW Memory Server launcher.
# Auto-resolves server.js relative to this script's location, so it works
# regardless of how it was invoked (npm link, absolute path, symlink, PATH).
# Avoids the ${IJFW_HOME} expansion pitfall in MCP client args arrays.

# Resolve real script dir even through symlinks (POSIX-portable).
SOURCE="${BASH_SOURCE[0]:-$0}"
while [ -L "$SOURCE" ]; do
  DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
  SOURCE="$(readlink "$SOURCE")"
  case "$SOURCE" in /*) ;; *) SOURCE="$DIR/$SOURCE" ;; esac
done
SCRIPT_DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
SERVER="$SCRIPT_DIR/../src/server.js"

if [ ! -f "$SERVER" ]; then
  # Server file missing -- emit MCP-spec parse-error then exit cleanly so the
  # client gets a recoverable signal instead of hanging.
  printf '{"jsonrpc":"2.0","id":null,"error":{"code":-32000,"message":"IJFW server file not found at %s"}}\n' "$SERVER" >&2
  exit 1
fi

# Find node: command -v first, then common install locations.
# Claude Code spawns MCP servers with a stripped PATH that excludes
# /opt/homebrew/bin (macOS + Homebrew) and ~/.nvm/ (nvm users).
NODE="$(command -v node 2>/dev/null)"
if [ -z "$NODE" ]; then
  for candidate in \
    /opt/homebrew/bin/node \
    /usr/local/bin/node \
    "$HOME/.nvm/versions/node"/*/bin/node \
    "$HOME/.volta/bin/node" \
    "$HOME/.fnm/node-versions"/*/installation/bin/node \
    /usr/bin/node; do
    # shellcheck disable=SC2086
    for resolved in $candidate; do
      if [ -x "$resolved" ]; then
        NODE="$resolved"
        break 2
      fi
    done
  done
fi

if [ -z "$NODE" ]; then
  printf '{"jsonrpc":"2.0","id":null,"error":{"code":-32001,"message":"node not found in PATH or common locations (/opt/homebrew/bin, /usr/local/bin, ~/.nvm, ~/.volta). Install Node 18+ and retry."}}\n' >&2
  exit 1
fi

exec "$NODE" "$SERVER" "$@"
