<#
.SYNOPSIS
    Edu stop all application services script
.DESCRIPTION
    Closes all edu-app-* terminal windows (started by start-all.ps1)
    Optional: kill processes by port (fallback when windows are closed but processes linger)
.PARAMETER KillByPort
    Kill processes by port (fallback when windows are closed but processes still alive)
.EXAMPLE
    .\scripts\stop-all.ps1
    .\scripts\stop-all.ps1 -KillByPort
#>
param(
    [switch]$KillByPort
)

$ErrorActionPreference = "Continue"

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  Edu Stop All Services" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# ===== 1. Close app service terminal windows =====
Write-Host "[1/2] Closing app service windows..." -ForegroundColor Yellow

$appTitles = @(
    "edu-app-classes",
    "edu-app-iam",
    "edu-app-teacher-bff",
    "edu-app-core-edu",
    "edu-app-content",
    "edu-app-msg",
    "edu-app-data-ana",
    "edu-app-ai",
    "edu-app-api-gateway",
    "edu-app-push-gateway",
    "edu-app-teacher-portal"
)

$closedCount = 0
foreach ($title in $appTitles) {
    $procs = Get-Process -Name "powershell","pwsh","node","python","uvicorn","go" -ErrorAction SilentlyContinue |
        Where-Object { $_.MainWindowTitle -like "*$title*" }

    if ($procs) {
        foreach ($p in $procs) {
            try {
                Stop-Process -Id $p.Id -Force -ErrorAction Stop
                Write-Host "  [OK] Closed $title (PID $($p.Id))" -ForegroundColor Green
                $closedCount++
            } catch {
                Write-Host "  [WARN] Cannot close $title (PID $($p.Id)): $($_.Exception.Message)" -ForegroundColor Yellow
            }
        }
    } else {
        Write-Host "  [--] $title window not found" -ForegroundColor Gray
    }
}

Write-Host ""
Write-Host "  Closed $closedCount windows" -ForegroundColor Green
Write-Host ""

# ===== 2. Kill by port (optional) =====
if ($KillByPort) {
    Write-Host "[2/2] Killing processes by port..." -ForegroundColor Yellow

    $ports = @(3000,3001,3002,3003,3004,3005,3006,3007,3008,8080,8081)

    foreach ($port in $ports) {
        $connections = Get-NetTCPConnection -LocalPort $port -State Listen -ErrorAction SilentlyContinue
        if ($connections) {
            foreach ($conn in $connections) {
                try {
                    $proc = Get-Process -Id $conn.OwningProcess -ErrorAction Stop
                    Stop-Process -Id $conn.OwningProcess -Force -ErrorAction Stop
                    Write-Host "  [OK] Port $port -> killed $($proc.ProcessName) (PID $($conn.OwningProcess))" -ForegroundColor Green
                } catch {
                    Write-Host "  [WARN] Port $port -> cannot kill PID $($conn.OwningProcess)" -ForegroundColor Yellow
                }
            }
        } else {
            Write-Host "  [--] Port $port free" -ForegroundColor Gray
        }
    }
} else {
    Write-Host "[2/2] Skipping port kill (use -KillByPort to enable)" -ForegroundColor Gray
}

Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  Stop complete" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "To stop infrastructure:" -ForegroundColor Yellow
Write-Host "  docker compose -f infra/docker-compose.yml --profile p6 --profile observability down" -ForegroundColor White
Write-Host ""
