# ============================================
# BraceIQMed - Local Update Script (Windows)
# Rebuilds and restarts Docker containers
# ============================================

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  BraceIQMed - Local Update" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# Change to project directory
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$projectDir = Split-Path -Parent $scriptDir
Set-Location $projectDir

Write-Host "[1/3] Building Docker images..." -ForegroundColor Yellow
docker compose build
if ($LASTEXITCODE -ne 0) {
    Write-Host "Build failed!" -ForegroundColor Red
    exit 1
}

Write-Host ""
Write-Host "[2/3] Restarting containers..." -ForegroundColor Yellow
docker compose up -d
if ($LASTEXITCODE -ne 0) {
    Write-Host "Failed to start containers!" -ForegroundColor Red
    exit 1
}

Write-Host ""
Write-Host "[3/3] Waiting for health checks..." -ForegroundColor Yellow
Start-Sleep -Seconds 5

# Check health
$health = docker compose ps --format json | ConvertFrom-Json
$allHealthy = $true
foreach ($container in $health) {
    $status = $container.Health
    $name = $container.Name
    if ($status -eq "healthy") {
        Write-Host "  ✓ $name - healthy" -ForegroundColor Green
    } elseif ($status -eq "starting") {
        Write-Host "  ⏳ $name - starting..." -ForegroundColor Yellow
    } else {
        Write-Host "  ✗ $name - $status" -ForegroundColor Red
        $allHealthy = $false
    }
}

Write-Host ""
if ($allHealthy) {
    Write-Host "========================================" -ForegroundColor Green
    Write-Host "  Update complete!" -ForegroundColor Green
    Write-Host "  App running at: http://localhost" -ForegroundColor Green
    Write-Host "========================================" -ForegroundColor Green
} else {
    Write-Host "Some containers may still be starting..." -ForegroundColor Yellow
    Write-Host "Check status with: docker compose ps" -ForegroundColor Yellow
}
