#!/usr/bin/env bash
#
# AiIndexer - Claude Code MCP Setup
# Configures ai-indexer as an MCP server for Claude Code
#
set -euo pipefail

BOLD='\033[1m'
DIM='\033[2m'
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
RESET='\033[0m'

info()    { printf "${BLUE}[INFO]${RESET}  %s\n" "$*"; }
success() { printf "${GREEN}[  OK]${RESET}  %s\n" "$*"; }
warn()    { printf "${YELLOW}[WARN]${RESET}  %s\n" "$*"; }
error()   { printf "${RED}[FAIL]${RESET}  %s\n" "$*" >&2; }

die() { error "$@"; exit 1; }

# ─── Parse arguments ───────────────────────────────────────────────────
SCOPE="global"
BINARY_PATH=""
REPO_PATH=""

while [[ $# -gt 0 ]]; do
    case "$1" in
        --global)    SCOPE="global"; shift ;;
        --local)     SCOPE="local"; shift ;;
        --binary)    BINARY_PATH="$2"; shift 2 ;;
        --repo)      REPO_PATH="$2"; shift 2 ;;
        --help|-h)
            echo "Usage: setup-claude.sh [--global|--local] [--binary /path/to/ai-indexer-mcp] [--repo /path/to/project]"
            echo ""
            echo "Flags:"
            echo "  --global    Configure in ~/.claude/settings.json (default)"
            echo "  --local     Configure in ./.claude/settings.json (project-level)"
            echo "  --binary    Path to ai-indexer-mcp binary"
            echo "  --repo      Repository path served by AiIndexer (default: current directory)"
            exit 0
            ;;
        *) die "Unknown option: $1" ;;
    esac
done

if [[ -z "$REPO_PATH" ]]; then
    REPO_PATH="$(pwd)"
fi
if [[ ! -d "$REPO_PATH" ]]; then
    die "Repository path does not exist: ${REPO_PATH}"
fi
cd "$REPO_PATH"
REPO_PATH="$(pwd)"

# ─── Find binary ───────────────────────────────────────────────────────
if [[ -z "$BINARY_PATH" ]]; then
    if command -v ai-indexer-mcp &>/dev/null; then
        BINARY_PATH="$(which ai-indexer-mcp)"
    elif [[ -f "${HOME}/.local/bin/ai-indexer-mcp" ]]; then
        BINARY_PATH="${HOME}/.local/bin/ai-indexer-mcp"
    elif [[ -f "/usr/local/bin/ai-indexer-mcp" ]]; then
        BINARY_PATH="/usr/local/bin/ai-indexer-mcp"
    else
        # Try to find in likely build locations
        SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
        PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
        if [[ -f "${PROJECT_DIR}/target/release/ai-indexer-mcp" ]]; then
            BINARY_PATH="${PROJECT_DIR}/target/release/ai-indexer-mcp"
        else
            die "Cannot find ai-indexer-mcp binary. Build first or pass --binary /path/to/binary"
        fi
    fi
fi

info "Using binary: ${BINARY_PATH}"

# Verify binary works
if ! "$BINARY_PATH" version &>/dev/null; then
    warn "Binary found but 'version' command failed. Continuing anyway..."
fi

# ─── Determine settings path ───────────────────────────────────────────
if [[ "$SCOPE" == "local" ]]; then
    SETTINGS_DIR="${REPO_PATH}/.claude"
    SETTINGS_FILE="${SETTINGS_DIR}/settings.json"
    info "Scope: project-local (${SETTINGS_FILE})"
else
    SETTINGS_DIR="${HOME}/.claude"
    SETTINGS_FILE="${SETTINGS_DIR}/settings.json"
    info "Scope: global (~/.claude/settings.json)"
fi

mkdir -p "$SETTINGS_DIR"

# ─── Build MCP config ──────────────────────────────────────────────────
MCP_ENTRY='{
    "command": "'"${BINARY_PATH}"'",
    "args": ["serve", "--repo", "'"${REPO_PATH}"'"]
}'

# ─── Read existing settings and show before state ──────────────────────
if [[ -f "$SETTINGS_FILE" ]]; then
    info "Existing settings found"

    # Create backup
    BACKUP="${SETTINGS_FILE}.backup.$(date +%Y%m%d_%H%M%S)"
    cp "$SETTINGS_FILE" "$BACKUP"
    success "Backup created: ${BACKUP}"

    BEFORE=$(cat "$SETTINGS_FILE")

    # Check if already configured
    if grep -q '"ai-indexer"' "$SETTINGS_FILE" 2>/dev/null; then
        warn "ai-indexer is already configured in ${SETTINGS_FILE}; updating it idempotently"
    fi

    # Merge using python3
    if command -v python3 &>/dev/null; then
        python3 - "$SETTINGS_FILE" "$BINARY_PATH" "$REPO_PATH" <<'PYEOF'
import json, sys
settings_path = sys.argv[1]
binary_path = sys.argv[2]
repo_path = sys.argv[3]
with open(settings_path, 'r') as f:
    settings = json.load(f)
if 'mcpServers' not in settings:
    settings['mcpServers'] = {}
settings['mcpServers']['ai-indexer'] = {
    "command": binary_path,
    "args": ["serve", "--repo", repo_path]
}
with open(settings_path, 'w') as f:
    json.dump(settings, f, indent=2)
    f.write('\n')
PYEOF
    else
        die "python3 required for safe JSON merging. Install python3 or edit ${SETTINGS_FILE} manually."
    fi
else
    info "Creating new settings file"
    BEFORE="(none)"
    cat > "$SETTINGS_FILE" <<JSONEOF
{
  "mcpServers": {
    "ai-indexer": {
      "command": "${BINARY_PATH}",
      "args": ["serve", "--repo", "${REPO_PATH}"]
    }
  }
}
JSONEOF
fi

AFTER=$(cat "$SETTINGS_FILE")

# ─── Show diff ──────────────────────────────────────────────────────────
printf "\n${BOLD}${CYAN}Before:${RESET}\n"
if [[ "$BEFORE" == "(none)" ]]; then
    printf "  ${DIM}(no settings file)${RESET}\n"
else
    echo "$BEFORE" | sed 's/^/  /'
fi

printf "\n${BOLD}${GREEN}After:${RESET}\n"
echo "$AFTER" | sed 's/^/  /'

printf "\n"
success "Claude Code MCP configuration complete!"
printf "\n"
info "Restart Claude Code or run '/mcp' to verify the connection."
info "The ai-indexer MCP server will start automatically when Claude Code connects."
info "Repo served by MCP: ${REPO_PATH}"
printf "\n"
printf "  ${BOLD}Available MCP tools (5-tool Router Pattern):${RESET}\n"
printf "    ${DIM}context${RESET}    Get code context for any task (auto-detects intent)\n"
printf "    ${DIM}search${RESET}     Find symbols, patterns, or text\n"
printf "    ${DIM}navigate${RESET}   Deps, traces, architecture, dead-code, impact, duplicates, rules\n"
printf "    ${DIM}remember${RESET}   Save/recall observations across sessions\n"
printf "    ${DIM}status${RESET}     Index health and codebase statistics\n"
