#!/bin/bash
# Bluera Knowledge Plugin - Setup Script
# Runs on: SessionStart (via auto-setup.sh) or manually
#
# Installs:
#   - MCP wrapper script (bluera-knowledge-mcp)
#   - Node.js dependencies (bun install / npm ci)
#   - Playwright Chromium browser (for web crawling)
#
# Environment variables:
#   NONINTERACTIVE=1 - Skip interactive prompts (for auto-setup)

set -e

# Get the plugin root directory
PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(dirname "$(dirname "$0")")}"

# Non-interactive mode (set by auto-setup.sh)
NONINTERACTIVE="${NONINTERACTIVE:-}"

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

# Debug logging - writes JSON to same log file as bootstrap.ts
# Uses PROJECT_ROOT if available (set by Claude Code), else current dir
LOG_DIR="${PROJECT_ROOT:-.}/.bluera/bluera-knowledge/logs"
LOG_FILE="$LOG_DIR/app.log"

log_debug() {
    local msg="$1"
    mkdir -p "$LOG_DIR" 2>/dev/null || true
    # macOS date doesn't support %3N, fallback to seconds-only
    local timestamp
    timestamp=$(date -u +"%Y-%m-%dT%H:%M:%S.000Z" 2>/dev/null || date -u +"%Y-%m-%dT%H:%M:%SZ")
    echo "{\"time\":\"$timestamp\",\"level\":\"debug\",\"module\":\"setup.sh\",\"msg\":\"$msg\"}" >> "$LOG_FILE" 2>/dev/null || true
}

log_debug "Setup starting, PLUGIN_ROOT=$PLUGIN_ROOT, PROJECT_ROOT=${PROJECT_ROOT:-unset}"

echo -e "${YELLOW}[bluera-knowledge] Running setup...${NC}"

# =====================
# Node.js Dependencies
# =====================

log_debug "Checking node_modules at $PLUGIN_ROOT/node_modules"

# =====================
# Build Tools Check (required for native modules)
# =====================

log_debug "Checking build tools"

if command -v make &> /dev/null; then
    log_debug "make found"
    echo -e "${GREEN}[bluera-knowledge] Build tools available ✓${NC}"
else
    log_debug "make not found, prompting for install"
    echo -e "${YELLOW}[bluera-knowledge] Build tools (make) not found - required for native modules${NC}"

    # Detect platform and set install command
    if [ -f /etc/debian_version ]; then
        INSTALL_CMD="sudo apt update && sudo apt install -y build-essential"
        PLATFORM="Debian/Ubuntu"
    elif [ -f /etc/fedora-release ] || [ -f /etc/redhat-release ]; then
        INSTALL_CMD="sudo dnf groupinstall -y 'Development Tools'"
        PLATFORM="Fedora/RHEL"
    elif [ "$(uname)" = "Darwin" ]; then
        INSTALL_CMD="xcode-select --install"
        PLATFORM="macOS"
    else
        # Unknown platform - show manual instructions and exit
        echo -e "${RED}[bluera-knowledge] Could not detect platform for auto-install${NC}"
        echo -e "${YELLOW}Please install build tools manually:${NC}"
        echo -e "${YELLOW}  Debian/Ubuntu: sudo apt install build-essential${NC}"
        echo -e "${YELLOW}  Fedora/RHEL:   sudo dnf groupinstall 'Development Tools'${NC}"
        echo -e "${YELLOW}  macOS:         xcode-select --install${NC}"
        exit 1
    fi

    echo -e "${YELLOW}Detected platform: ${PLATFORM}${NC}"
    echo -e "${YELLOW}Install command: ${INSTALL_CMD}${NC}"
    echo ""

    # Non-interactive mode: cannot prompt for sudo, exit with instructions
    if [[ -n "$NONINTERACTIVE" ]]; then
        log_debug "Non-interactive mode, cannot prompt for build tools install"
        echo -e "${RED}[bluera-knowledge] Build tools required but running non-interactively.${NC}"
        echo -e "${YELLOW}Run manually: ${INSTALL_CMD}${NC}"
        echo -e "${YELLOW}Then restart Claude Code.${NC}"
        exit 1
    fi

    read -p "Install build tools now? [y/N] " -n 1 -r
    echo ""

    if [[ $REPLY =~ ^[Yy]$ ]]; then
        log_debug "User confirmed install, running: $INSTALL_CMD"
        echo -e "${YELLOW}[bluera-knowledge] Installing build tools...${NC}"
        if eval "$INSTALL_CMD"; then
            log_debug "Build tools installed successfully"
            echo -e "${GREEN}[bluera-knowledge] Build tools installed ✓${NC}"
        else
            log_debug "Build tools install failed"
            echo -e "${RED}[bluera-knowledge] Build tools installation failed${NC}"
            echo -e "${YELLOW}Please install manually and retry${NC}"
            exit 1
        fi
    else
        log_debug "User declined install"
        echo -e "${YELLOW}[bluera-knowledge] Skipped. Please install build tools manually:${NC}"
        echo -e "${YELLOW}  ${INSTALL_CMD}${NC}"
        exit 1
    fi
fi

# =====================
# MCP Wrapper Script
# WORKAROUND: ${CLAUDE_PLUGIN_ROOT} not expanding in plugin .mcp.json
# Claude Code's ${CLAUDE_PLUGIN_ROOT} should work per docs, but doesn't in some environments.
# See: https://github.com/anthropics/claude-code/issues/9427
# See: https://code.claude.com/docs/en/mcp (Plugin MCP configuration)
# =====================

log_debug "Installing MCP wrapper script"

WRAPPER_DIR="$HOME/.local/bin"
WRAPPER_PATH="$WRAPPER_DIR/bluera-knowledge-mcp"

mkdir -p "$WRAPPER_DIR"
cp "$PLUGIN_ROOT/scripts/mcp-wrapper.sh" "$WRAPPER_PATH"
chmod +x "$WRAPPER_PATH"

# Check if ~/.local/bin is in PATH
if [[ ":$PATH:" != *":$WRAPPER_DIR:"* ]]; then
    log_debug "Warning: $WRAPPER_DIR not in PATH"
    echo -e "${YELLOW}[bluera-knowledge] Note: Add ~/.local/bin to your PATH if MCP server doesn't start${NC}"
    echo -e "${YELLOW}  export PATH=\"\$HOME/.local/bin:\$PATH\"${NC}"
fi

echo -e "${GREEN}[bluera-knowledge] MCP wrapper installed ✓${NC}"

# =====================
# Node.js Dependencies
# =====================

if [ -d "$PLUGIN_ROOT/node_modules" ]; then
    log_debug "node_modules exists, skipping install"
    echo -e "${GREEN}[bluera-knowledge] Node.js dependencies already installed ✓${NC}"
else
    echo -e "${YELLOW}[bluera-knowledge] Installing Node.js dependencies...${NC}"

    # Skip browser downloads during npm/bun install - browsers are installed separately below
    export PUPPETEER_SKIP_DOWNLOAD=1
    export PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1

    if command -v bun &> /dev/null; then
        log_debug "Starting bun install --frozen-lockfile"
        (cd "$PLUGIN_ROOT" && bun install --frozen-lockfile) && \
            { log_debug "bun install complete"; echo -e "${GREEN}[bluera-knowledge] Node.js dependencies installed ✓${NC}"; } || \
            { log_debug "bun install FAILED"; echo -e "${RED}[bluera-knowledge] Failed to install Node.js dependencies${NC}"; exit 1; }
    elif command -v npm &> /dev/null; then
        # CRITICAL: --legacy-peer-deps required!
        # tree-sitter-go@0.25 requires tree-sitter@^0.25
        # tree-sitter-rust@0.24 requires tree-sitter@^0.22
        # These peer deps conflict - no compatible version exists.
        # Without --legacy-peer-deps, npm fails even though tree-sitter is optional.
        log_debug "Starting npm install --legacy-peer-deps"
        (cd "$PLUGIN_ROOT" && npm install --legacy-peer-deps) && \
            { log_debug "npm install complete"; echo -e "${GREEN}[bluera-knowledge] Node.js dependencies installed ✓${NC}"; } || \
            { log_debug "npm install FAILED"; echo -e "${RED}[bluera-knowledge] Failed to install Node.js dependencies${NC}"; exit 1; }
    else
        log_debug "Neither bun nor npm found"
        echo -e "${RED}[bluera-knowledge] Neither bun nor npm found${NC}"
        exit 1
    fi
fi

# =====================
# Playwright Browser
# =====================

PLAYWRIGHT_BROWSERS_PATH="${PLAYWRIGHT_BROWSERS_PATH:-$HOME/.cache/ms-playwright}"

log_debug "Checking playwright at $PLAYWRIGHT_BROWSERS_PATH/chromium-*"

if ls "$PLAYWRIGHT_BROWSERS_PATH"/chromium-* 1>/dev/null 2>&1; then
    log_debug "Playwright chromium exists, skipping install"
    echo -e "${GREEN}[bluera-knowledge] Playwright Chromium already installed ✓${NC}"
else
    echo -e "${YELLOW}[bluera-knowledge] Installing Playwright Chromium browser...${NC}"

    log_debug "Starting npx playwright install chromium (this can take several minutes)"
    if (cd "$PLUGIN_ROOT" && npx playwright install chromium); then
        log_debug "Playwright install complete"
        echo -e "${GREEN}[bluera-knowledge] Playwright Chromium installed ✓${NC}"
    else
        log_debug "Playwright install FAILED"
        echo -e "${RED}[bluera-knowledge] Playwright browser install failed${NC}"
        echo -e "${YELLOW}Manual fix: npx playwright install chromium${NC}"
        exit 1
    fi
fi

# =====================
# Python3 Check (Optional)
# =====================

log_debug "Checking python3"

if command -v python3 &> /dev/null; then
    python_version=$(python3 -c 'import sys; print(".".join(map(str, sys.version_info[:2])))')
    log_debug "Python $python_version found"
    echo -e "${GREEN}[bluera-knowledge] Python ${python_version} available (for code-graph) ✓${NC}"
else
    log_debug "Python3 not found"
    echo -e "${YELLOW}[bluera-knowledge] Python3 not found - code-graph feature unavailable${NC}"
fi

log_debug "Setup complete"
echo -e "${GREEN}[bluera-knowledge] Setup complete ✓${NC}"
