# ==================================================================================================
#  一键重启后端服务（支持从任意位置运行）
#  用法：scripts\restart_backend.ps1
# ==================================================================================================

$SCRIPT_DIR  = Split-Path -Parent $MyInvocation.MyCommand.Path
$PROJECT_ROOT = Split-Path -Parent $SCRIPT_DIR
$BACKEND_DIR  = Join-Path $PROJECT_ROOT "backend"

# ===================================================================
#  Step 1: 杀掉占用 8000 端口的旧进程
# ===================================================================
Write-Host "=== Step 1: Kill old processes on port 8000 ===" -ForegroundColor Yellow
$raw   = netstat -ano | Select-String ":8000" | Select-String "LISTENING"
$pids  = $raw | ForEach-Object { ($_ -split '\s+')[-1] } | Sort-Object -Unique
foreach ($pid in $pids) {
    if ($pid -match '^\d+$') {
        Write-Host "  Killing PID $pid ..." -ForegroundColor Red
        Stop-Process -Id ([int]$pid) -Force -ErrorAction SilentlyContinue
    }
}
Start-Sleep -Seconds 2
Write-Host "  Done." -ForegroundColor Green

# ===================================================================
#  Step 2: 检查 PostgreSQL
# ===================================================================
Write-Host ""
Write-Host "=== Step 2: Check PostgreSQL ===" -ForegroundColor Yellow

# 动态查找 psql.exe（常见安装路径 → PATH）
$PG_CANDIDATES = @(
    "C:\Program Files\PostgreSQL\16\bin\psql.exe",
    "C:\Program Files\PostgreSQL\15\bin\psql.exe",
    "C:\Program Files\PostgreSQL\14\bin\psql.exe"
)
$PG_CLI = $PG_CANDIDATES | Where-Object { Test-Path $_ } | Select-Object -First 1
if (-not $PG_CLI) {
    $PG_CLI = Get-Command psql -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source
}

if ($PG_CLI -and (Test-Path $PG_CLI)) {
    # 从 .env 文件读取数据库密码（优先 POSTGRES_PASSWORD，其次解析 DATABASE_URL）
    $envFile = Join-Path $PROJECT_ROOT ".env"
    $pgPassword = "postgres"  # 兜底默认值
    if (Test-Path $envFile) {
        $envLines = Get-Content $envFile
        # 方式1：直接读取 POSTGRES_PASSWORD
        $pwLine = $envLines | Where-Object { $_ -match '^POSTGRES_PASSWORD=' }
        if ($pwLine) {
            $pgPassword = ($pwLine -replace '^POSTGRES_PASSWORD=' , '').Trim('"')
        } else {
            # 方式2：从 DATABASE_URL 中解析密码
            $dbLine = $envLines | Where-Object { $_ -match '^DATABASE_URL=' }
            if ($dbLine -match '://[^:]+:([^@]+)@') {
                $pgPassword = $matches[1]
            }
        }
    }
    $env:PGPASSWORD = $pgPassword

    $pgResult = & $PG_CLI -U postgres -h localhost -c "SELECT 1" -d it_smart_desk 2>&1
    if ($pgResult -match "1 row") {
        Write-Host "  PostgreSQL OK" -ForegroundColor Green
    } else {
        Write-Host "  PostgreSQL FAILED - make sure it is running" -ForegroundColor Red
    }
} else {
    Write-Host "  psql.exe not found. Install PostgreSQL client or add it to PATH." -ForegroundColor Red
}

# ===================================================================
#  Step 3: 检查 Redis
# ===================================================================
Write-Host ""
Write-Host "=== Step 3: Check Redis ===" -ForegroundColor Yellow

# 动态查找 redis-cli.exe
$REDIS_CANDIDATES = @(
    "C:\Program Files\Redis\redis-cli.exe",
    "C:\Program Files (x86)\Redis\redis-cli.exe"
)
$REDIS_CLI = $REDIS_CANDIDATES | Where-Object { Test-Path $_ } | Select-Object -First 1
if (-not $REDIS_CLI) {
    $REDIS_CLI = Get-Command redis-cli -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source
}

if ($REDIS_CLI -and (Test-Path $REDIS_CLI)) {
    $redisResult = & $REDIS_CLI ping 2>&1
    if ($redisResult -match "PONG") {
        Write-Host "  Redis OK" -ForegroundColor Green
    } else {
        Write-Host "  Redis FAILED - make sure it is running" -ForegroundColor Red
    }
} else {
    Write-Host "  redis-cli.exe not found. Install Redis client or add it to PATH." -ForegroundColor Red
}

# ===================================================================
#  Step 4: 启动后端
# ===================================================================
Write-Host ""
Write-Host "=== Step 4: Starting backend ===" -ForegroundColor Yellow
Set-Location $BACKEND_DIR

# 优先使用 venv 中的 python，找不到则使用 PATH 中的 python
if (Test-Path "venv\Scripts\python.exe") {
    $PYTHON_EXE = "venv\Scripts\python.exe"
} elseif (Get-Command python -ErrorAction SilentlyContinue) {
    $PYTHON_EXE = "python"
} else {
    Write-Host "  [ERROR] python not found. Please install Python or create backend\venv." -ForegroundColor Red
    Read-Host "Press Enter to exit"
    exit 1
    exit 1
}

Write-Host "  Backend dir : $BACKEND_DIR"
Write-Host "  Python      : $PYTHON_EXE"
Write-Host ""
& $PYTHON_EXE -m uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
