#!/usr/bin/env bash
# =====================================================================
# bluera-knowledge MCP Wrapper Script
# =====================================================================
#
# WORKAROUND: ${CLAUDE_PLUGIN_ROOT} not expanding in plugin .mcp.json
#
# Claude Code's ${CLAUDE_PLUGIN_ROOT} environment variable is documented
# to work in plugin .mcp.json files, but doesn't expand correctly in
# some environments. This wrapper script locates the plugin installation
# directory dynamically and runs bootstrap.js.
#
# References:
# - Bug: https://github.com/anthropics/claude-code/issues/9427
#   "env variable expansion not working in plugin .mcp.json"
#   (Closed Jan 2026, but still occurs on some systems)
#
# - Docs: https://code.claude.com/docs/en/mcp
#   "Plugin MCP features: Use ${CLAUDE_PLUGIN_ROOT} for plugin-relative paths"
#
# This script reads ~/.claude/plugins/installed_plugins.json to find the
# correct plugin path, with fallbacks to cache directory scanning.
# =====================================================================

set -e

# Find plugin root from installed_plugins.json
# Claude Code stores plugin metadata here when plugins are installed
INSTALLED_PLUGINS="$HOME/.claude/plugins/installed_plugins.json"

if [ -f "$INSTALLED_PLUGINS" ]; then
    # Use jq if available (more reliable JSON parsing)
    if command -v jq &> /dev/null; then
        PLUGIN_ROOT=$(jq -r '.["bluera-knowledge"].path // empty' "$INSTALLED_PLUGINS" 2>/dev/null)
    else
        # Fallback: extract path with grep/sed (less reliable but works without jq)
        # This handles the JSON structure: {"bluera-knowledge": {"path": "/path/to/plugin"}}
        PLUGIN_ROOT=$(grep -o '"bluera-knowledge"[^}]*"path"[[:space:]]*:[[:space:]]*"[^"]*"' "$INSTALLED_PLUGINS" 2>/dev/null | sed 's/.*"path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/')
    fi
fi

# Fallback: scan cache directories for valid plugin installations
# Plugins are cached at ~/.claude/plugins/cache/<org>/<name>/<version>/
#
# CRITICAL: Sort by version number (descending) to use the LATEST version!
# Bug fixed in v0.22.7: Alphabetical sort put 0.20.0 before 0.22.x, causing
# old bootstrap.ts (without --legacy-peer-deps) to run and fail.
# The -V flag does proper version sorting: 0.22.7 > 0.22.6 > 0.21.0 > 0.20.0
#
if [ -z "$PLUGIN_ROOT" ] || [ ! -d "$PLUGIN_ROOT" ]; then
    CACHE_BASE="$HOME/.claude/plugins/cache/bluera/bluera-knowledge"
    if [ -d "$CACHE_BASE" ]; then
        # Sort versions numerically (descending) with -V flag and use the latest valid one
        for cache_dir in $(ls -d "$CACHE_BASE"/*/ 2>/dev/null | sort -V -r); do
            if [ -f "$cache_dir/dist/mcp/bootstrap.js" ]; then
                PLUGIN_ROOT="$cache_dir"
                break
            fi
        done
    fi
fi

# Verify we found a valid plugin installation
if [ -z "$PLUGIN_ROOT" ] || [ ! -f "$PLUGIN_ROOT/dist/mcp/bootstrap.js" ]; then
    echo "ERROR: Could not locate bluera-knowledge plugin" >&2
    echo "Expected bootstrap.js at: \$PLUGIN_ROOT/dist/mcp/bootstrap.js" >&2
    echo "Checked:" >&2
    echo "  - installed_plugins.json: $INSTALLED_PLUGINS" >&2
    echo "  - Cache dir: ~/.claude/plugins/cache/bluera/bluera-knowledge/" >&2
    # Exit 2 = blocking error, stderr shown to user (exit 1 is non-blocking, hidden)
    # See: https://code.claude.com/docs/en/hooks
    exit 2
fi

# Check if build tools are available for native module compilation
# Required for native modules (LanceDB) - check BEFORE attempting to run bootstrap
if ! command -v make &>/dev/null; then
    echo "ERROR: Build tools (make) not found - required for native modules." >&2
    echo "" >&2
    echo "Install build tools, then restart Claude Code:" >&2
    echo "  Debian/Ubuntu: sudo apt install build-essential" >&2
    echo "  Fedora/RHEL:   sudo dnf groupinstall 'Development Tools'" >&2
    echo "  macOS:         xcode-select --install" >&2
    # Exit 2 = blocking error, stderr shown to user (exit 1 is non-blocking, hidden)
    # See: https://code.claude.com/docs/en/hooks
    exit 2
fi

# Run bootstrap.js with all environment variables passed through
# The bootstrap script handles dependency installation and MCP server startup
exec node "$PLUGIN_ROOT/dist/mcp/bootstrap.js" "$@"
