#!/bin/bash
# Wrapper script for MCP server that ensures dependencies are installed
# This runs before the MCP server starts

# Determine plugin root directory
if [ -n "$CLAUDE_PLUGIN_ROOT" ]; then
  PLUGIN_ROOT="$CLAUDE_PLUGIN_ROOT"
else
  # Fall back to script directory
  SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
  PLUGIN_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
fi

# Check if node_modules exists
if [ ! -d "$PLUGIN_ROOT/node_modules" ]; then
  echo "Installing episodic-memory dependencies (first run only)..." >&2
  echo "This may take 30-60 seconds..." >&2

  # Remove package-lock.json if it exists to ensure platform-specific optional deps are installed
  # See: https://github.com/npm/cli/issues/4828
  rm -f "$PLUGIN_ROOT/package-lock.json"

  # Install dependencies - npm will auto-install optionalDependencies for current platform
  (cd "$PLUGIN_ROOT" && npm install --prefer-offline --no-audit --no-fund) >&2

  if [ $? -ne 0 ]; then
    echo "ERROR: Failed to install dependencies." >&2
    echo "Please run manually: cd \"$PLUGIN_ROOT\" && npm install" >&2
    exit 1
  fi

  echo "Dependencies installed successfully." >&2
fi

# Start the MCP server
exec node "$PLUGIN_ROOT/dist/mcp-server.js"
