$ErrorActionPreference = "Stop"
$root = Split-Path -Parent $PSScriptRoot

Write-Host "Building Nexus Identity API..." -ForegroundColor Cyan
dotnet build "$root\source\nexus-identity\NexusIdentity.Api\NexusIdentity.Api.csproj" -c Release

Write-Host "Building Nexus Shell..." -ForegroundColor Cyan
dotnet build "$root\source\nexus-shell\NexusShell\NexusShell.csproj" -c Release

Write-Host ""
Write-Host "Starting Identity API on http://localhost:5000 ..." -ForegroundColor Green
$identityJob = Start-Job {
    Set-Location $using:root
    Set-Location "source\nexus-identity\NexusIdentity.Api"
    dotnet run --no-build -c Release
}

Start-Sleep -Seconds 4

try {
    $health = Invoke-RestMethod -Uri "http://localhost:5000/health" -TimeoutSec 5
    Write-Host "Health: $($health.status) v$($health.version)" -ForegroundColor Green
}
catch {
    Write-Host "Warning: Identity API not ready yet. Wait a few seconds." -ForegroundColor Yellow
}

Write-Host "Starting Nexus Shell (overlay mode)..." -ForegroundColor Green
Set-Location "$root\source\nexus-shell\NexusShell"
dotnet run --no-build -c Release -- --safe-poc

Stop-Job $identityJob -ErrorAction SilentlyContinue
Remove-Job $identityJob -ErrorAction SilentlyContinue
