$root = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $root

$dockerExe = (Get-Command docker.exe).Source
$dotnetExe = (Get-Command dotnet.exe).Source
$ps = (Get-Command powershell.exe).Source

Write-Host "Building RelayCore..."
& $dotnetExe build .\RelayCore\RelayCore.csproj
if ($LASTEXITCODE -ne 0) { throw "RelayCore build failed." }

Write-Host "Building RelayServer..."
& $dotnetExe build .\RelayServer\RelayServer.csproj
if ($LASTEXITCODE -ne 0) { throw "RelayServer build failed." }

Write-Host "Building RelayClient (Windows only)..."
& $dotnetExe build .\RelayClient\RelayClient.csproj -f net10.0-windows10.0.19041.0
if ($LASTEXITCODE -ne 0) { throw "RelayClient build failed." }

$coreDll   = Join-Path $root "RelayCore\bin\Debug\net9.0\RelayCore.dll"
$serverDll = Join-Path $root "RelayServer\bin\Debug\net10.0\RelayServer.dll"
$clientExe = Join-Path $root "RelayClient\bin\Debug\net10.0-windows10.0.19041.0\win-x64\RelayClient.exe"

$tempDir = Join-Path $env:TEMP "RelayTabs"
New-Item -ItemType Directory -Force -Path $tempDir | Out-Null

function New-TabScript {
    param(
        [string]$Name,
        [string]$Content
    )

    $path = Join-Path $tempDir "$Name.ps1"
    Set-Content -Path $path -Value $Content -Encoding UTF8
    return $path
}

$dockerScript = New-TabScript -Name "SurrealDB" -Content @"
Set-Location '$root'
& '$dockerExe' run --rm -p 8000:8000 -v /mydata:/mydata surrealdb/surrealdb:v2.2.1 start --user root --pass secret
"@

$coreScript = New-TabScript -Name "RelayCore" -Content @"
Set-Location '$root'
Start-Sleep -Seconds 1
& '$dotnetExe' '$coreDll'
"@

$serverScript = New-TabScript -Name "RelayServer" -Content @"
Set-Location '$root'
Start-Sleep -Seconds 1
& '$dotnetExe' '$serverDll'
"@

$keeperScript = New-TabScript -Name "Keeper317" -Content @"
Set-Location '$root'
Start-Sleep -Seconds 5
& '$clientExe' --user Keeper317
"@

$kiraScript = New-TabScript -Name "Ru_Kira" -Content @"
Set-Location '$root'
Start-Sleep -Seconds 5
& '$clientExe' --user Ru_Kira
"@

$testScript = New-TabScript -Name "Test" -Content @"
Set-Location '$root'
Start-Sleep -Seconds 25
& '$clientExe' --user Test
"@

$wtArgs = @(
    "new-tab --title `"SurrealDB`" `"$ps`" -NoExit -ExecutionPolicy Bypass -File `"$dockerScript`"",
    "new-tab --title `"RelayCore`" `"$ps`" -NoExit -ExecutionPolicy Bypass -File `"$coreScript`"",
    "new-tab --title `"RelayServer`" `"$ps`" -NoExit -ExecutionPolicy Bypass -File `"$serverScript`"",
    "new-tab --title `"Keeper317`" `"$ps`" -NoExit -ExecutionPolicy Bypass -File `"$keeperScript`"",
    "new-tab --title `"Test`" `"$ps`" -NoExit -ExecutionPolicy Bypass -File `"$testScript`"",
    "new-tab --title `"Ru_Kira`" `"$ps`" -NoExit -ExecutionPolicy Bypass -File `"$kiraScript`""
) -join " ; "

Write-Host ""
Write-Host "Everything started."
Write-Host "Close out terminal to end all applications."
Start-Process wt.exe -ArgumentList $wtArgs