#!/usr/bin/env bash
#
# AiIndexer - Cursor IDE MCP Setup
# Configures ai-indexer as an MCP server for Cursor
#
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 ───────────────────────────────────────────────────
BINARY_PATH=""
SCOPE="project"
REPO_PATH=""

while [[ $# -gt 0 ]]; do
    case "$1" in
        --binary)    BINARY_PATH="$2"; shift 2 ;;
        --global)    SCOPE="global"; shift ;;
        --project)   SCOPE="project"; shift ;;
        --repo)      REPO_PATH="$2"; shift 2 ;;
        --help|-h)
            echo "Usage: setup-cursor.sh [--global|--project] [--binary /path/to/ai-indexer-mcp] [--repo /path/to/project]"
            echo ""
            echo "Flags:"
            echo "  --global     Configure globally for all Cursor projects"
            echo "  --project    Configure for current project only (default)"
            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"
    else
        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}"

# ─── Determine config location ─────────────────────────────────────────
if [[ "$SCOPE" == "global" ]]; then
    # Cursor global MCP config
    if [[ "$(uname -s)" == "Darwin" ]]; then
        CURSOR_DIR="${HOME}/.cursor"
    else
        CURSOR_DIR="${HOME}/.cursor"
    fi
    MCP_FILE="${CURSOR_DIR}/mcp.json"
    info "Scope: global (${MCP_FILE})"
else
    CURSOR_DIR="${REPO_PATH}/.cursor"
    MCP_FILE="${CURSOR_DIR}/mcp.json"
    info "Scope: project (${MCP_FILE})"
fi

mkdir -p "$CURSOR_DIR"

# ─── Configure MCP ─────────────────────────────────────────────────────
if [[ -f "$MCP_FILE" ]]; then
    # Backup existing
    BACKUP="${MCP_FILE}.backup.$(date +%Y%m%d_%H%M%S)"
    cp "$MCP_FILE" "$BACKUP"
    success "Backup: ${BACKUP}"

    if grep -q '"ai-indexer"' "$MCP_FILE" 2>/dev/null; then
        warn "ai-indexer already configured. Updating..."
    fi

    if command -v python3 &>/dev/null; then
        python3 - "$MCP_FILE" "$BINARY_PATH" "$REPO_PATH" <<'PYEOF'
import json, sys
mcp_path = sys.argv[1]
binary_path = sys.argv[2]
repo_path = sys.argv[3]
with open(mcp_path, 'r') as f:
    config = json.load(f)
if 'mcpServers' not in config:
    config['mcpServers'] = {}
config['mcpServers']['ai-indexer'] = {
    "command": binary_path,
    "args": ["serve", "--repo", repo_path]
}
with open(mcp_path, 'w') as f:
    json.dump(config, f, indent=2)
    f.write('\n')
PYEOF
    else
        die "python3 required for safe JSON merging."
    fi
else
    cat > "$MCP_FILE" <<JSONEOF
{
  "mcpServers": {
    "ai-indexer": {
      "command": "${BINARY_PATH}",
      "args": ["serve", "--repo", "${REPO_PATH}"]
    }
  }
}
JSONEOF
fi

success "Cursor MCP configuration written to ${MCP_FILE}"

# ─── Create .cursorrules if desired ─────────────────────────────────────
CURSORRULES=".cursorrules"
if [[ "$SCOPE" == "project" ]] && [[ ! -f "$CURSORRULES" ]]; then
    info "Creating .cursorrules with AiIndexer instructions..."
    cat > "$CURSORRULES" <<'RULES'
# AiIndexer Integration (5 tools, Router Pattern)

You have access to 5 AiIndexer MCP tools for code intelligence:

1. `context` — Primary tool. Use for ANY coding task. Auto-detects intent.
   - `context task="fix the bug"` — auto-finds relevant files
   - `context task="..." files=["src/auth.rs"] mode="full"` — full source for editing
   - `context task="..." mode="skeleton"` — compressed overview
2. `search` — Find symbols, patterns, text. `search query="User" kind="class"`
3. `navigate` — Deps, traces, architecture, dead-code, impact analysis.
4. `remember` — Save/recall observations across sessions.
5. `status` — Index health and stats.

Always prefer `context` over reading raw files. It returns precisely targeted,
token-efficient context with full source for target files and compressed
skeletons for dependencies (65-74% token savings).

Use `navigate action="duplicates"` for duplicate code and
`navigate action="rules"` to improve `.ai-indexer.toml`. Do not call legacy
specialized tools unless the current agent already exposes them.
RULES
    success "Created .cursorrules"
elif [[ -f "$CURSORRULES" ]]; then
    info ".cursorrules already exists -- not overwriting"
    info "Consider adding AiIndexer instructions from guides/AI_INTEGRATION.md"
fi

# ─── Done ───────────────────────────────────────────────────────────────
printf "\n"
success "Cursor setup complete!"
printf "\n"
printf "  ${BOLD}Config:${RESET}  %s\n" "$MCP_FILE"
printf "\n"
printf "  ${BOLD}${CYAN}Next steps:${RESET}\n"
printf "  1. Restart Cursor\n"
printf "  2. Open a project and ask Cursor to analyze code\n"
printf "  3. Cursor will automatically use ai-indexer MCP tools\n"
printf "\n"
