# index1 Windows 安装脚本
# 用法: irm https://raw.githubusercontent.com/gladego/index1/main/scripts/install.ps1 | iex
# 或:   .\scripts\install.ps1 [-SkipOllama]

param(
    [switch]$SkipOllama
)

$ErrorActionPreference = "Stop"

Write-Host "=== index1 安装脚本 ===" -ForegroundColor Cyan
Write-Host ""

# Step 1: 检测 Python
$python = $null
foreach ($cmd in @("python3", "python")) {
    try {
        $ver = & $cmd -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>$null
        if ($ver) {
            $parts = $ver.Split(".")
            if ($parts.Count -ge 2 -and [int]$parts[0] -ge 3 -and [int]$parts[1] -ge 10) {
                $python = $cmd
                Write-Host "✅ Python $ver detected ($cmd)" -ForegroundColor Green
                break
            }
        }
    } catch {}
}

if (-not $python) {
    Write-Host "❌ Python >= 3.10 required" -ForegroundColor Red
    Write-Host "   Install: https://www.python.org/downloads/"
    exit 1
}

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

$installed = $false

# 优先使用 pipx
if (Get-Command pipx -ErrorAction SilentlyContinue) {
    Write-Host "  Using pipx..."
    try {
        pipx install index1 2>$null
        $installed = $true
        Write-Host "✅ index1 installed (via pipx)" -ForegroundColor Green
    } catch {
        Write-Host "⚠️  pipx install failed, trying pip..." -ForegroundColor Yellow
    }
}

# pipx 不可用或失败时，尝试 pip
if (-not $installed) {
    # 检测虚拟环境
    if ($env:VIRTUAL_ENV -or $env:CONDA_DEFAULT_ENV) {
        Write-Host "  Using pip (virtual environment detected)..."
        & $python -m pip install --quiet index1
        $installed = $true
        Write-Host "✅ index1 installed (via pip, venv)" -ForegroundColor Green
    } else {
        Write-Host "  Using pip --user..."
        try {
            & $python -m pip install --quiet --user index1 2>$null
            $installed = $true
            Write-Host "✅ index1 installed (via pip --user)" -ForegroundColor Green
        } catch {
            try {
                & $python -m pip install --quiet index1 2>$null
                $installed = $true
                Write-Host "✅ index1 installed (via pip)" -ForegroundColor Green
            } catch {}
        }
    }
}

if (-not $installed) {
    Write-Host "❌ 安装失败" -ForegroundColor Red
    Write-Host ""
    Write-Host "请手动安装:"
    Write-Host "  pipx install index1    # 推荐"
    Write-Host "  pip install index1     # venv / Docker"
    Write-Host ""
    Write-Host "没有 pipx？先安装:"
    Write-Host "  scoop install pipx"
    Write-Host "  pip install --user pipx"
    exit 1
}

# 验证安装
if (Get-Command index1 -ErrorAction SilentlyContinue) {
    Write-Host "✅ index1 command available" -ForegroundColor Green
} else {
    Write-Host "⚠️  index1 已安装但不在 PATH 中" -ForegroundColor Yellow
    Write-Host "   尝试重新打开终端，或检查 PATH 设置"
}

# Step 3: 检测 Ollama
Write-Host ""
if (Get-Command ollama -ErrorAction SilentlyContinue) {
    Write-Host "✅ Ollama detected" -ForegroundColor Green
} else {
    Write-Host "⚠️  Ollama not found (semantic search will be disabled)" -ForegroundColor Yellow
    Write-Host "   Install: https://ollama.ai"
    $SkipOllama = $true
}

# Step 4: 下载 embedding 模型
if (-not $SkipOllama) {
    Write-Host ""
    Write-Host "Pulling nomic-embed-text model..."
    try {
        ollama pull nomic-embed-text 2>$null
        Write-Host "✅ nomic-embed-text model ready" -ForegroundColor Green
    } catch {
        Write-Host "⚠️  Model pull failed (is 'ollama serve' running?)" -ForegroundColor Yellow
    }
}

# Step 5: 创建默认配置
$configDir = Join-Path $env:USERPROFILE ".claude-index1"
$configFile = Join-Path $configDir "config.yaml"
if (-not (Test-Path $configFile)) {
    New-Item -ItemType Directory -Path $configDir -Force | Out-Null
    @"
# index1 configuration
# See: https://github.com/gladego/index1
embedding_model: nomic-embed-text
"@ | Set-Content -Path $configFile -Encoding UTF8
    Write-Host "✅ Config created: $configFile" -ForegroundColor Green
} else {
    Write-Host "✅ Config exists: $configFile" -ForegroundColor Green
}

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