#!/usr/bin/env bash
#
# AiIndexer - VS Code Extension Setup
# Builds and installs the AiIndexer VS Code extension
#
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="${AI_INDEXER_BINARY:-}"
REPO_PATH=""

while [[ $# -gt 0 ]]; do
    case "$1" in
        --binary) BINARY_PATH="$2"; shift 2 ;;
        --repo) REPO_PATH="$2"; shift 2 ;;
        --help|-h)
            echo "Usage: setup-vscode.sh [--repo /path/to/project] [--binary /path/to/ai-indexer-mcp]"
            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)"

# ─── Locate project root ───────────────────────────────────────────────
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
EXTENSION_DIR="${PROJECT_DIR}/vscode-extension"

if [[ -z "$BINARY_PATH" ]]; then
    if command -v ai-indexer-mcp &>/dev/null; then
        BINARY_PATH="$(command -v ai-indexer-mcp)"
    elif [[ -x "${HOME}/.local/bin/ai-indexer-mcp" ]]; then
        BINARY_PATH="${HOME}/.local/bin/ai-indexer-mcp"
    elif [[ -x "${HOME}/.cargo/bin/ai-indexer-mcp" ]]; then
        BINARY_PATH="${HOME}/.cargo/bin/ai-indexer-mcp"
    elif [[ -x "${PROJECT_DIR}/target/release/ai-indexer-mcp" ]]; then
        BINARY_PATH="${PROJECT_DIR}/target/release/ai-indexer-mcp"
    fi
fi

configure_project_settings() {
    if [[ -z "$BINARY_PATH" ]]; then
        warn "AiIndexer binary not found; skipping project VS Code settings"
        return 0
    fi
    local settings_dir="${REPO_PATH}/.vscode"
    local settings_file="${settings_dir}/settings.json"
    mkdir -p "$settings_dir"
    if command -v python3 &>/dev/null; then
        python3 - "$settings_file" "$BINARY_PATH" <<'PY'
import json, pathlib, sys
path = pathlib.Path(sys.argv[1])
binary = sys.argv[2]
data = {}
if path.exists():
    try:
        data = json.loads(path.read_text())
    except json.JSONDecodeError:
        data = {}
data["aiIndexer.binaryPath"] = binary
data["aiIndexer.autoIndex"] = True
path.write_text(json.dumps(data, indent=2) + "\n")
PY
    else
        cat > "$settings_file" <<JSON
{
  "aiIndexer.binaryPath": "${BINARY_PATH}",
  "aiIndexer.autoIndex": true
}
JSON
    fi
    success "VS Code project settings written to ${settings_file}"
}

# Check for VS Code CLI before deciding whether to build from source or install
# the public VSIX shipped in the release.
VSCODE_CMD=""
if command -v code &>/dev/null; then
    VSCODE_CMD="code"
elif command -v code-insiders &>/dev/null; then
    VSCODE_CMD="code-insiders"
fi

if [[ ! -d "$EXTENSION_DIR" ]]; then
    info "VS Code extension source not found at ${EXTENSION_DIR}; using public VSIX release"
    configure_project_settings
    if [[ -z "$VSCODE_CMD" ]]; then
        warn "'code' CLI not found. Skipping VS Code extension auto-install."
        warn "Install manually from https://aindex.floriansola.fr/releases/latest/ai-indexer-0.1.0.vsix"
        exit 0
    fi
    VERSION="${AI_INDEXER_VERSION:-0.1.0}"
    VERSION="${VERSION#v}"
    SUPPORT_DIR="${AI_INDEXER_SUPPORT_DIR:-${HOME}/.ai-indexer}"
    VSIX_DIR="${SUPPORT_DIR}/vscode"
    VSIX_FILE="${VSIX_DIR}/ai-indexer-${VERSION}.vsix"
    VSIX_URL="${AI_INDEXER_VSIX_URL:-https://aindex.floriansola.fr/releases/latest/ai-indexer-${VERSION}.vsix}"
    mkdir -p "$VSIX_DIR"
    if [[ ! -f "$VSIX_FILE" ]]; then
        info "Downloading VSIX: ${VSIX_URL}"
        if command -v curl &>/dev/null; then
            curl -fsSL "$VSIX_URL" -o "$VSIX_FILE"
        elif command -v wget &>/dev/null; then
            wget -q "$VSIX_URL" -O "$VSIX_FILE"
        else
            die "curl or wget is required to download the public VSIX"
        fi
    fi
    "${VSCODE_CMD}" --install-extension "$VSIX_FILE" --force 2>&1
    success "VS Code extension installed from public VSIX"
    exit 0
fi

# ─── Check prerequisites ───────────────────────────────────────────────
info "Checking prerequisites..."

if ! command -v node &>/dev/null; then
    die "Node.js is required. Install from https://nodejs.org/"
fi
success "Node.js: $(node --version)"

if ! command -v npm &>/dev/null; then
    die "npm is required. It should come with Node.js."
fi
success "npm: $(npm --version)"

if [[ -z "$VSCODE_CMD" ]]; then
    warn "'code' CLI not found. Extension will be built but not auto-installed."
    warn "Install the 'code' command: VS Code > Cmd+Shift+P > 'Shell Command: Install'"
fi

if [[ -n "$VSCODE_CMD" ]]; then
    success "VS Code CLI: ${VSCODE_CMD}"
fi

# Check for vsce
HAS_VSCE=false
if command -v vsce &>/dev/null; then
    HAS_VSCE=true
    success "vsce: available"
elif npx vsce --version &>/dev/null 2>&1; then
    HAS_VSCE=true
    success "vsce: available (via npx)"
else
    info "Installing @vscode/vsce..."
    npm install -g @vscode/vsce 2>/dev/null || warn "Could not install vsce globally, will use npx"
fi

if [[ -n "$BINARY_PATH" ]]; then
    success "AiIndexer binary: ${BINARY_PATH}"
else
    warn "AiIndexer binary not found. Build with: cargo build --release"
fi

# ─── Install npm dependencies ──────────────────────────────────────────
info "Installing extension dependencies..."
cd "$EXTENSION_DIR"
npm install --silent 2>&1 | tail -1
success "Dependencies installed"

# ─── Compile TypeScript ─────────────────────────────────────────────────
info "Compiling extension..."
npm run compile 2>&1 || npx tsc -p . 2>&1 || die "TypeScript compilation failed"
success "Extension compiled"

# ─── Package extension ─────────────────────────────────────────────────
info "Packaging extension..."
VSIX_FILE="${EXTENSION_DIR}/ai-indexer-0.1.0.vsix"

if command -v vsce &>/dev/null; then
    vsce package --no-dependencies -o "$VSIX_FILE" 2>&1 | tail -1
elif npx vsce --version &>/dev/null 2>&1; then
    npx vsce package --no-dependencies -o "$VSIX_FILE" 2>&1 | tail -1
else
    warn "Cannot package without vsce. Install: npm install -g @vscode/vsce"
    info "The extension is compiled in ${EXTENSION_DIR}/out/ -- you can load it as a dev extension."
    printf "\n"
    exit 0
fi

if [[ -f "$VSIX_FILE" ]]; then
    VSIX_SIZE=$(du -h "$VSIX_FILE" | cut -f1)
    success "Packaged: ${VSIX_FILE} (${VSIX_SIZE})"
else
    warn "VSIX file not created. Extension may still work in dev mode."
fi

# ─── Install extension ─────────────────────────────────────────────────
if [[ -n "$VSCODE_CMD" ]] && [[ -f "$VSIX_FILE" ]]; then
    info "Installing extension..."
    ${VSCODE_CMD} --install-extension "$VSIX_FILE" --force 2>&1
    success "Extension installed in VS Code"
else
    if [[ -z "$VSCODE_CMD" ]]; then
        info "Install manually: code --install-extension ${VSIX_FILE}"
    fi
fi

# ─── Configure VS Code settings ────────────────────────────────────────
info "Checking VS Code settings..."
configure_project_settings

if [[ "$(uname -s)" == "Darwin" ]]; then
    VSCODE_SETTINGS_DIR="${HOME}/Library/Application Support/Code/User"
else
    VSCODE_SETTINGS_DIR="${HOME}/.config/Code/User"
fi

VSCODE_SETTINGS="${VSCODE_SETTINGS_DIR}/settings.json"

if [[ -f "$VSCODE_SETTINGS" ]] && [[ -n "$BINARY_PATH" ]]; then
    if grep -q "aiIndexer.binaryPath" "$VSCODE_SETTINGS" 2>/dev/null; then
        success "VS Code settings already contain aiIndexer config"
    else
        info "You may want to add to your VS Code settings.json:"
        printf "\n"
        printf "  ${DIM}\"aiIndexer.binaryPath\": \"${BINARY_PATH}\",${RESET}\n"
        printf "  ${DIM}\"aiIndexer.autoIndex\": true${RESET}\n"
        printf "\n"
    fi
fi

# ─── Done ───────────────────────────────────────────────────────────────
printf "\n"
success "VS Code extension setup complete!"
printf "\n"
printf "  ${BOLD}Extension:${RESET}  AiIndexer v0.1.0\n"
if [[ -f "$VSIX_FILE" ]]; then
    printf "  ${BOLD}Package:${RESET}    %s\n" "$VSIX_FILE"
fi
printf "\n"
printf "  ${BOLD}${CYAN}Features:${RESET}\n"
printf "    - Sidebar panel with index status and quick actions\n"
printf "    - CodeLens annotations showing dependency counts\n"
printf "    - Commands for search, skeleton, and dependency graphs\n"
printf "    - Auto-indexing on workspace open and file save\n"
printf "\n"
printf "  ${BOLD}${CYAN}Next steps:${RESET}\n"
printf "  1. Restart VS Code\n"
printf "  2. Open a project -- indexing starts automatically\n"
printf "  3. Look for the AiIndexer icon in the sidebar\n"
printf "\n"
