<#
.SYNOPSIS
  Free ports, switch to Node 22, rebuild SQL driver, start API + web.
.EXAMPLE
  .\scripts\start-sovereign.ps1
#>
[CmdletBinding()]
param(
    [int[]]$Ports = @(3041, 3000)
)

$ErrorActionPreference = 'Stop'
$root = Split-Path -Parent $PSScriptRoot
Set-Location $root

Write-Host '=== DBAOps Sovereign — start (pilot) ===' -ForegroundColor Cyan

foreach ($port in $Ports) {
    $conns = Get-NetTCPConnection -LocalPort $port -ErrorAction SilentlyContinue
    if ($conns) {
        $conns | Select-Object -ExpandProperty OwningProcess -Unique | ForEach-Object {
            Write-Host "Stopping process $_ on port $port"
            Stop-Process -Id $_ -Force -ErrorAction SilentlyContinue
        }
    }
}
Start-Sleep -Seconds 2

# Prefer nvm Node 22 when available
if (Get-Command nvm -ErrorAction SilentlyContinue) {
    nvm use 22.22.0 2>$null
    if ($LASTEXITCODE -ne 0) {
        Write-Host 'Installing Node 22.22.0 via nvm...' -ForegroundColor Yellow
        nvm install 22.22.0
        nvm use 22.22.0
    }
}

$nodeVer = node -v
Write-Host "Node $nodeVer"
node scripts/check-node-version.js
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

npm run repair:sql
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

npm start
