param(
    [string]$PidDir = $env:VGA_PID_DIR,
    [string]$UeExe = $env:VGA_UE_EXE,
    [string]$UeArgs = $env:VGA_UE_ARGS,
    [string]$SignallingBat = $env:VGA_SIGNALLING_BAT,
    [string]$UeWorkingDir = $env:VGA_UE_WORKDIR,
    [int]$SignallingStartupDelaySeconds = $(if ($env:VGA_SIGNALLING_DELAY) { [int]$env:VGA_SIGNALLING_DELAY } else { 5 }),
    [switch]$ShowSignallingWindow
)

if (-not $PidDir) {
    $PidDir = "C:\Users\Student\Documents\Dannick\avatar"
}

if (-not $UeExe) {
    $UeExe = "C:\Users\Student\Documents\Dannick\avatar\Windows\Prototyp1.exe"
}

if (-not $UeArgs) {
    $UeArgs = "-PixelStreamingURL=ws://127.0.0.1 -RenderOffscreen -PixelStreamingWebRTCDisableTransmitAudio"
}

if (-not $SignallingBat) {
    $SignallingBat = "C:\Users\Student\Documents\Dannick\avatar\Windows\Prototyp1\Samples\PixelStreaming\WebServers\SignallingWebServer\platform_scripts\cmd\start_with_stun.bat"
}

if (-not $UeWorkingDir) {
    $UeWorkingDir = Split-Path -Path $UeExe -Parent
}

if (-not (Test-Path -LiteralPath $SignallingBat)) {
    throw "Signalling script not found: $SignallingBat"
}

if (-not (Test-Path -LiteralPath $UeExe)) {
    throw "Unreal executable not found: $UeExe"
}

if (-not (Test-Path -LiteralPath $UeWorkingDir)) {
    throw "Unreal working directory not found: $UeWorkingDir"
}

New-Item -ItemType Directory -Path $PidDir -Force | Out-Null

$signallingWindowStyle = if ($ShowSignallingWindow.IsPresent) { "Normal" } else { "Hidden" }
$signalling = Start-Process -FilePath $SignallingBat -PassThru -WindowStyle $signallingWindowStyle

Start-Sleep -Seconds $SignallingStartupDelaySeconds

$ueStartParams = @{
    FilePath = $UeExe
    WorkingDirectory = $UeWorkingDir
    PassThru = $true
}

if ($UeArgs) {
    $ueStartParams["ArgumentList"] = $UeArgs
}

$ue = Start-Process @ueStartParams

$ue.Id | Out-File (Join-Path $PidDir "unreal.pid") -Encoding ascii
$signalling.Id | Out-File (Join-Path $PidDir "signalling.pid") -Encoding ascii

