param(
    [string]$LogPath,
    [int]$Port = 3000
)

$ErrorActionPreference = "Stop"

$repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..")
$configFile = Join-Path $repoRoot "ops/observability/local/config.local-observability.yaml"

$env:ATHENA_AUTH_CONFIG_FILE = (Resolve-Path -LiteralPath $configFile).Path
$env:PORT = $Port.ToString()
$env:BASE_URL = "http://localhost:$Port"

Write-Host "ATHENA_AUTH_CONFIG_FILE=$env:ATHENA_AUTH_CONFIG_FILE"
Write-Host "PORT=$env:PORT"
Write-Host "BASE_URL=$env:BASE_URL"

if ($LogPath) {
    $resolvedLogPath = $LogPath
    if (-not [System.IO.Path]::IsPathRooted($resolvedLogPath)) {
        $resolvedLogPath = Join-Path $repoRoot $resolvedLogPath
    }

    $logDirectory = Split-Path -Parent $resolvedLogPath
    if ($logDirectory) {
        New-Item -ItemType Directory -Force -Path $logDirectory | Out-Null
    }

    Write-Host "Writing combined cargo/server output to $resolvedLogPath"
    $quotedLogPath = '"' + $resolvedLogPath + '"'
    cmd /c "cargo run --bin server --features server > $quotedLogPath 2>&1"
    exit $LASTEXITCODE
}

cargo run --bin server --features server
