# FASS 2.0 multi-car UDP integration script
param(
    [switch]$StartSimulators,
    [switch]$SkipTests
)

$ErrorActionPreference = "Stop"
$root = Join-Path $PSScriptRoot ".."
$sln = Join-Path $root "StandardScene.sln"
$testProj = Join-Path $root "StandardScene.Magnetic.Tests\StandardScene.Magnetic.Tests.csproj"
$simProj = Join-Path $root "StandardScene.Fass2Simulator\StandardScene.Fass2Simulator.csproj"

Write-Host "== FASS2 multi-car UDP ==" -ForegroundColor Cyan
Write-Host "Solution: $sln"

dotnet build $sln -c Release | Out-Host
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

if (-not $SkipTests) {
    Write-Host ""
    Write-Host "== Protocol golden + UDP hub tests ==" -ForegroundColor Cyan
    dotnet test $testProj -c Release --no-build --filter "FullyQualifiedName~StandardScene.Magnetic.Tests.Protocol" -v n
    if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

    Write-Host ""
    Write-Host "== Simulator self-tests ==" -ForegroundColor Cyan
    dotnet run --project $simProj -c Release --no-build -- --motion-test
    if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
    dotnet run --project $simProj -c Release --no-build -- --action-test
    if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
}

if ($StartSimulators) {
    $simDir = Join-Path $root "StandardScene.Fass2Simulator\bin\Release\net8.0-windows"
    $exe = Join-Path $simDir "StandardScene.Fass2Simulator.exe"
    if (-not (Test-Path $exe)) {
        throw "Simulator not found: $exe"
    }

    Copy-Item (Join-Path $root "StandardScene.Fass2Simulator\appsettings.car2.json") (Join-Path $simDir "appsettings.car2.json") -Force

    Write-Host ""
    Write-Host "== Starting dual simulators ==" -ForegroundColor Cyan
    Write-Host "Car1: VehicleCode=1, Listen=5000 -> 127.0.0.1:20103"
    Write-Host "Car2: VehicleCode=2, Listen=5001 -> 127.0.0.1:20103"
    Write-Host "SimpleLite: two Mag2Car, VehicleCode 1/2, Port 5000/5001, ListenPort 20103"

    Start-Process $exe -WorkingDirectory $simDir
    Start-Process $exe -WorkingDirectory $simDir -ArgumentList @("--config", "appsettings.car2.json")
    Write-Host "Started two simulator processes." -ForegroundColor Green
}
else {
    Write-Host ""
    Write-Host "Manual dual-car steps:" -ForegroundColor Yellow
    Write-Host "  dotnet test StandardScene.Magnetic.Tests -c Release"
    Write-Host "  Start two simulators; second with --config appsettings.car2.json"
    Write-Host "  Or: .\run-fass2-multi-car-udp.ps1 -StartSimulators"
}

Write-Host ""
Write-Host "Done." -ForegroundColor Green
