#!/usr/bin/env bash
set -euo pipefail

# index1 一键安装脚本
# 用法: curl -sSL https://raw.githubusercontent.com/gladego/index1/main/scripts/install.sh | bash
# 或:   bash scripts/install.sh [--skip-ollama]

SKIP_OLLAMA=false
for arg in "$@"; do
    case "$arg" in
        --skip-ollama) SKIP_OLLAMA=true ;;
        --help|-h)
            echo "用法: bash install.sh [--skip-ollama]"
            echo "  --skip-ollama  跳过 Ollama 模型下载"
            exit 0
            ;;
    esac
done

echo "=== index1 安装脚本 ==="
echo ""

# Step 1: 检测 Python
PYTHON=""
for cmd in python3 python; do
    if command -v "$cmd" &>/dev/null; then
        ver=$("$cmd" -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")' 2>/dev/null || echo "0.0")
        major=$(echo "$ver" | cut -d. -f1)
        minor=$(echo "$ver" | cut -d. -f2)
        if [ -z "$major" ] || [ -z "$minor" ]; then
            continue
        fi
        if [ "$major" -ge 3 ] && [ "$minor" -ge 10 ]; then
            PYTHON="$cmd"
            echo "✅ Python $ver detected ($cmd)"
            break
        fi
    fi
done

if [ -z "$PYTHON" ]; then
    echo "❌ Python >= 3.10 required"
    echo "   Install: https://www.python.org/downloads/"
    exit 1
fi

# Step 2: 安装 index1（pipx 优先，pip 兜底）
echo ""
echo "Installing index1..."

INSTALLED=false

# 优先使用 pipx（避免 macOS externally-managed-environment 问题）
if command -v pipx &>/dev/null; then
    echo "  Using pipx..."
    if pipx install index1 2>/dev/null; then
        pipx ensurepath 2>/dev/null || true
        INSTALLED=true
        echo "✅ index1 installed (via pipx)"
    else
        echo "⚠️  pipx install failed, trying pip..."
    fi
fi

# pipx 不可用或失败时，尝试 pip
if [ "$INSTALLED" = false ]; then
    # 检测是否在虚拟环境中（venv/conda）
    if [ -n "${VIRTUAL_ENV:-}" ] || [ -n "${CONDA_DEFAULT_ENV:-}" ]; then
        echo "  Using pip (virtual environment detected)..."
        $PYTHON -m pip install --quiet index1
        INSTALLED=true
        echo "✅ index1 installed (via pip, venv)"
    else
        # 非虚拟环境，尝试 pip install --user
        echo "  Using pip --user..."
        if $PYTHON -m pip install --quiet --user index1 2>/dev/null; then
            INSTALLED=true
            echo "✅ index1 installed (via pip --user)"
        else
            # 最后尝试普通 pip（Linux 等无限制环境）
            if $PYTHON -m pip install --quiet index1 2>/dev/null; then
                INSTALLED=true
                echo "✅ index1 installed (via pip)"
            fi
        fi
    fi
fi

if [ "$INSTALLED" = false ]; then
    echo "❌ 安装失败"
    echo ""
    echo "请手动安装:"
    echo "  pipx install index1    # 推荐（macOS / Linux）"
    echo "  pip install index1     # Linux / venv / Docker"
    echo ""
    echo "没有 pipx？先安装:"
    echo "  brew install pipx      # macOS"
    echo "  pip install --user pipx  # Linux"
    exit 1
fi

# 验证安装
if command -v index1 &>/dev/null; then
    echo "✅ index1 command available: $(which index1)"
else
    echo "⚠️  index1 已安装但不在 PATH 中"
    echo ""
    echo "   请重新打开终端，或手动添加到 PATH:"
    if command -v pipx &>/dev/null; then
        echo "   pipx ensurepath"
    fi
    echo "   export PATH=\"\$HOME/.local/bin:\$PATH\""
fi

# Step 3: 检测 Ollama
echo ""
if command -v ollama &>/dev/null; then
    echo "✅ Ollama detected"
else
    echo "⚠️  Ollama not found (semantic search will be disabled)"
    echo "   Install: https://ollama.ai"
    SKIP_OLLAMA=true
fi

# Step 4: 下载 embedding 模型
if [ "$SKIP_OLLAMA" = false ]; then
    echo ""
    echo "Pulling nomic-embed-text model..."
    if ollama pull nomic-embed-text 2>/dev/null; then
        echo "✅ nomic-embed-text model ready"
    else
        echo "⚠️  Model pull failed (is 'ollama serve' running?)"
    fi
fi

# Step 5: 创建默认配置
CONFIG_DIR="$HOME/.claude-index1"
CONFIG_FILE="$CONFIG_DIR/config.yaml"
if [ ! -f "$CONFIG_FILE" ]; then
    mkdir -p "$CONFIG_DIR"
    cat > "$CONFIG_FILE" << 'YAML'
# index1 configuration
# See: https://github.com/gladego/index1
embedding_model: nomic-embed-text
YAML
    echo "✅ Config created: $CONFIG_FILE"
else
    echo "✅ Config exists: $CONFIG_FILE"
fi

# Done
echo ""
echo "=== 安装完成 ==="
echo ""
echo "Quick start:"
echo "  index1 index ./docs ./src"
echo "  index1 search \"your query\""
echo ""
echo "Claude Code MCP:"
echo "  Add to ~/.claude/settings.json:"
echo '  { "mcpServers": { "index1": { "command": "index1", "args": ["serve"] } } }'
echo ""
