#!/usr/bin/env pwsh
# update.ps1 - One-command update & restart for ocr-sprint-service (local dev)

$Port = 8000

# ── [1/5] Git pull ──────────────────────────────────────────────────────────
Write-Host "`n[1/5] Pulling latest code..." -ForegroundColor Cyan
git pull

# ── [2/5] Install/update dependencies ───────────────────────────────────────
Write-Host "`n[2/5] Installing/updating dependencies..." -ForegroundColor Cyan
pip install -e ".[dev]" -q

# ── [3/5] Database migration ─────────────────────────────────────────────────
Write-Host "`n[3/5] Running database migrations..." -ForegroundColor Cyan
alembic upgrade head
if ($LASTEXITCODE -ne 0) {
    Write-Host "  Migration conflict detected, stamping current state as head..." -ForegroundColor Yellow
    alembic stamp head
    Write-Host "  Retrying upgrade for any remaining new migrations..." -ForegroundColor Yellow
    alembic upgrade head
    if ($LASTEXITCODE -ne 0) {
        Write-Host "  Migration still failed. Please check alembic manually." -ForegroundColor Red
        exit 1
    }
}
Write-Host "  Migrations OK." -ForegroundColor Green

# ── [4/5] Free up port ───────────────────────────────────────────────────────
Write-Host "`n[4/5] Checking port $Port..." -ForegroundColor Cyan

# Use Get-NetTCPConnection for reliable port detection on Windows
$connections = Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue
if ($connections) {
    foreach ($conn in $connections) {
        $procId = $conn.OwningProcess
        $procName = (Get-Process -Id $procId -ErrorAction SilentlyContinue).Name
        Write-Host "  Port $Port used by '$procName' (PID $procId), killing..." -ForegroundColor Yellow
        Stop-Process -Id $procId -Force -ErrorAction SilentlyContinue
    }
    # Wait until port is actually released (max 5 seconds)
    $waited = 0
    do {
        Start-Sleep -Milliseconds 500
        $waited += 500
        $still = Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue
    } while ($still -and $waited -lt 5000)

    if ($still) {
        Write-Host "  Port $Port still in use after waiting. Try a different port or restart manually." -ForegroundColor Red
        exit 1
    }
    Write-Host "  Port $Port freed." -ForegroundColor Green
} else {
    Write-Host "  Port $Port is free." -ForegroundColor Green
}

# ── [5/5] Start dev server ───────────────────────────────────────────────────
Write-Host "`n[5/5] Starting dev server on port $Port (Ctrl+C to stop)..." -ForegroundColor Cyan
uvicorn ocr_sprint.main:app --reload --host 0.0.0.0 --port $Port
