#!/usr/bin/env bash
set -e

# vibing.nvim build script
# Automatically builds the MCP server on plugin installation

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MCP_DIR="${SCRIPT_DIR}/mcp-server"

# Use VIBING_NODE_EXECUTABLE env var if set, otherwise default to "node"
NODE_EXECUTABLE="${VIBING_NODE_EXECUTABLE:-node}"

echo "[vibing.nvim] Building MCP server..."

# Check if Node.js is installed
# Handle both absolute paths and PATH lookups
if [[ "$NODE_EXECUTABLE" = /* ]]; then
    # Absolute path - check if file exists and is executable
    if [ ! -x "$NODE_EXECUTABLE" ]; then
        echo "[vibing.nvim] Error: Node.js not found at '$NODE_EXECUTABLE'. Please install Node.js 18+ from https://nodejs.org/"
        exit 1
    fi
else
    # Relative or command name - check PATH
    if ! command -v "$NODE_EXECUTABLE" &> /dev/null; then
        echo "[vibing.nvim] Error: Node.js not found at '$NODE_EXECUTABLE'. Please install Node.js 18+ from https://nodejs.org/"
        exit 1
    fi
fi

# Check Node.js version
NODE_VERSION=$("$NODE_EXECUTABLE" -v | cut -d'v' -f2 | cut -d'.' -f1)
if [ "$NODE_VERSION" -lt 18 ]; then
    echo "[vibing.nvim] Warning: Node.js version 18+ recommended (found: $("$NODE_EXECUTABLE" -v))"
fi

# Check if npm is installed
if ! command -v npm &> /dev/null; then
    echo "[vibing.nvim] Error: npm not found. Please install npm"
    exit 1
fi

# Check if MCP directory exists
if [ ! -d "$MCP_DIR" ]; then
    echo "[vibing.nvim] Error: MCP server directory not found: $MCP_DIR"
    exit 1
fi

# Install root dependencies (Agent SDK, etc.)
echo "[vibing.nvim] Installing root dependencies..."
cd "$SCRIPT_DIR"
npm install --silent

# Build bin/ files (bundle and minify .mjs/.ts files)
echo "[vibing.nvim] Building bin/ files..."
npm run build

# Clean up old mote binaries (version mismatch prevention)
echo "[vibing.nvim] Cleaning up old mote binaries..."
rm -f bin/mote-darwin-arm64 bin/mote-darwin-x64 bin/mote-linux-arm64 bin/mote-linux-x64

# Download mote binaries for all platforms
echo "[vibing.nvim] Downloading mote binaries..."
if ! "$NODE_EXECUTABLE" scripts/download-mote.mjs; then
    echo "[vibing.nvim] ⚠ Warning: mote binary download failed"
    echo "[vibing.nvim] mote integration will not be available"
    echo "[vibing.nvim] You can manually download by running: $NODE_EXECUTABLE scripts/download-mote.mjs"
fi

# Build MCP server
cd "$MCP_DIR"

echo "[vibing.nvim] Installing MCP server dependencies..."
npm install --silent

echo "[vibing.nvim] Building TypeScript..."
npm run build --silent

# Verify build succeeded
if [ -f "dist/index.js" ]; then
    echo "[vibing.nvim] ✓ MCP server built successfully"

    # Register vibing-nvim with Claude Code: prefer installing it as a proper
    # Claude Code plugin (user scope) — this registers the MCP server *and*
    # the bundled skills/agents in one step. Fall back to a raw ~/.claude.json
    # mcpServers edit (MCP server only) if the `claude` CLI or its plugin
    # subcommand isn't available.
    cd "$SCRIPT_DIR"
    register_mcp_json_fallback() {
        echo "[vibing.nvim] Registering MCP server in ~/.claude.json..."
        if "$NODE_EXECUTABLE" dist/bin/register-mcp.js; then
            echo "[vibing.nvim] ✓ Registered vibing-nvim MCP server in ~/.claude.json"
        else
            echo "[vibing.nvim] ⚠ Warning: MCP server is built but registration failed"
            echo "[vibing.nvim] You can manually register by running: $NODE_EXECUTABLE dist/bin/register-mcp.js"
        fi
    }

    if command -v claude &> /dev/null; then
        echo "[vibing.nvim] Installing vibing-nvim as a Claude Code plugin (user scope)..."
        # Capture output instead of streaming it directly so it can be printed
        # below only on failure, keeping successful (repeat) runs quiet.
        MARKETPLACE_ADD_OUTPUT="$(claude plugin marketplace add "$SCRIPT_DIR" 2>&1)"
        MARKETPLACE_ADD_STATUS=$?
        if [ $MARKETPLACE_ADD_STATUS -eq 0 ] && claude plugin install vibing-nvim@vibing-nvim --scope user; then
            echo "[vibing.nvim] ✓ Installed vibing-nvim Claude Code plugin (scope: user)"
        else
            echo "[vibing.nvim] ⚠ Warning: 'claude plugin install' failed, falling back to manual registration"
            if [ $MARKETPLACE_ADD_STATUS -ne 0 ]; then
                echo "$MARKETPLACE_ADD_OUTPUT"
            fi
            register_mcp_json_fallback
        fi
    else
        echo "[vibing.nvim] 'claude' CLI not found; falling back to manual registration"
        register_mcp_json_fallback
    fi

    # Register MCP server with codex (if available)
    MCP_SERVER_PATH="${MCP_DIR}/dist/index.js"
    if command -v codex &> /dev/null; then
        echo "[vibing.nvim] Registering MCP server with codex..."
        if VIBING_RPC_PORT="${VIBING_RPC_PORT:-9876}" codex mcp add vibing-nvim -- "$NODE_EXECUTABLE" "$MCP_SERVER_PATH" 2>/dev/null; then
            echo "[vibing.nvim] ✓ Registered vibing-nvim MCP server with codex"
        else
            echo "[vibing.nvim] ⚠ Warning: codex MCP registration failed"
            echo "[vibing.nvim] You can manually register by running: codex mcp add vibing-nvim -- $NODE_EXECUTABLE $MCP_SERVER_PATH"
        fi
    fi

    exit 0
else
    echo "[vibing.nvim] ✗ Build failed: dist/index.js not found"
    exit 1
fi
