$ErrorActionPreference = 'Stop'

function Stop-TrackedProcess {
    param(
        [string]$PidFile
    )

    if (-not (Test-Path $PidFile)) {
        return
    }

    $pidText = (Get-Content $PidFile -Raw).Trim()
    if (-not $pidText) {
        Remove-Item $PidFile -Force -ErrorAction SilentlyContinue
        return
    }

    $existing = Get-Process -Id ([int]$pidText) -ErrorAction SilentlyContinue
    if ($null -ne $existing) {
        Stop-Process -Id $existing.Id -Force
        Write-Host "Stopped PID $($existing.Id)"
    }

    Remove-Item $PidFile -Force -ErrorAction SilentlyContinue
}

$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
$runtimeRoot = Join-Path $repoRoot 'runtime'

Stop-TrackedProcess -PidFile (Join-Path $runtimeRoot 'backend.pid')
Stop-TrackedProcess -PidFile (Join-Path $runtimeRoot 'frontend.pid')
