#!/bin/bash
# Bluera Knowledge Plugin - Auto Setup
# Runs on: SessionStart (async) - automatically sets up plugin if needed
#
# This script runs in the background on every session start.
# It exits quickly (0) if already set up, or runs full setup if needed.
# Non-interactive: cannot prompt for user input (no TTY).

# Drain stdin so the pipe doesn't hang
cat > /dev/null 2>&1 || true

PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(dirname "$(dirname "$0")")}"

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

# Debug logging
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
    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\":\"auto-setup.sh\",\"msg\":\"$msg\"}" >> "$LOG_FILE" 2>/dev/null || true
}

log_debug "Auto-setup starting, PLUGIN_ROOT=$PLUGIN_ROOT"

# Fast exit if already set up AND version hasn't changed
WRAPPER_PATH="$HOME/.local/bin/bluera-knowledge-mcp"
VERSION_FILE="$PLUGIN_ROOT/.installed-version"
CURRENT_VERSION=$(cat "$PLUGIN_ROOT/package.json" 2>/dev/null | grep '"version"' | head -1 | sed 's/.*"\([0-9][0-9.]*\)".*/\1/')
INSTALLED_VERSION=$(cat "$VERSION_FILE" 2>/dev/null || echo "none")

if [ -d "$PLUGIN_ROOT/node_modules" ] && [ -f "$WRAPPER_PATH" ]; then
    if [ "$CURRENT_VERSION" = "$INSTALLED_VERSION" ]; then
        log_debug "Already set up (v$INSTALLED_VERSION), exiting"
        exit 0
    fi
    log_debug "Version changed ($INSTALLED_VERSION -> $CURRENT_VERSION), re-running setup"
fi

log_debug "Setup needed - node_modules: $([ -d "$PLUGIN_ROOT/node_modules" ] && echo 'exists' || echo 'missing'), wrapper: $([ -f "$WRAPPER_PATH" ] && echo 'exists' || echo 'missing')"

# Check for build tools - if missing, print instructions and exit with error
# Cannot auto-install because that requires sudo (interactive)
if ! command -v make &>/dev/null; then
    log_debug "Build tools (make) not found, printing instructions"
    echo "[bluera-knowledge] 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 2
fi

# Run setup non-interactively
log_debug "Running setup.sh with NONINTERACTIVE=1"
echo -e "${YELLOW}[bluera-knowledge] Running first-time setup (this may take a moment)...${NC}"

export NONINTERACTIVE=1
if "$PLUGIN_ROOT/scripts/setup.sh"; then
    log_debug "Setup completed successfully"
    echo "$CURRENT_VERSION" > "$VERSION_FILE" 2>/dev/null || true
    echo -e "${GREEN}[bluera-knowledge] Setup complete ✓${NC}"
    echo -e "${GREEN}[bluera-knowledge] Restart Claude Code to enable MCP server.${NC}"
else
    log_debug "Setup failed"
    echo -e "${YELLOW}[bluera-knowledge] Setup failed. Run manually: $PLUGIN_ROOT/scripts/setup.sh${NC}"
fi
