param(
    [ValidateSet("Release", "Debug")]
    [string]$Configuration = "Release",
    [string]$Urls = "http://0.0.0.0:5180",
    [string]$ProjectRoot,
    [ValidateSet("Dev", "Output")]
    [string]$Mode = "Dev"
)

$commonScript = Join-Path $PSScriptRoot "script-common.ps1"
if (-not (Test-Path $commonScript)) {
    throw "Missing helper script: $commonScript"
}
. $commonScript

$repoRoot = Resolve-JournalRepoRoot -StartPath $PSScriptRoot
$gatewayProject = Resolve-JournalWebGatewayProjectPath -RepoRoot $repoRoot

$effectiveProjectRoot = if ([string]::IsNullOrWhiteSpace($ProjectRoot)) {
    $repoRoot
}
else {
    [System.IO.Path]::GetFullPath($ProjectRoot)
}

if (-not (Test-Path $effectiveProjectRoot)) {
    throw "ProjectRoot does not exist: $effectiveProjectRoot"
}

Clear-JournalProxyEnv
Initialize-JournalDotnetEnv -RepoRoot $repoRoot
$env:JOURNAL_PROJECT_ROOT = $effectiveProjectRoot

if ($Mode -eq "Output") {
    $exeName = if ([System.Environment]::OSVersion.Platform -eq "Win32NT") { "Journal.WebGateway.exe" } else { "Journal.WebGateway" }
    $exePath = Join-Path $repoRoot "output\webgateway\$exeName"
    
    if (-not (Test-Path $exePath)) {
        Write-Host "Output executable not found at $exePath" -ForegroundColor Red
        Write-Host "Please build WebGateway first (e.g. scripts\publish-webgateway.ps1)" -ForegroundColor Yellow
        exit 1
    }

    Write-Host "Running Journal.WebGateway (Published Output)..." -ForegroundColor Cyan
    Write-Host "Executable: $exePath" -ForegroundColor DarkGray
    Write-Host "URLs: $Urls" -ForegroundColor DarkGray
    Write-Host "JOURNAL_PROJECT_ROOT: $effectiveProjectRoot" -ForegroundColor DarkGray

    & $exePath --urls $Urls
}
else {
    Write-Host "Running Journal.WebGateway ($Configuration Dev Server)..." -ForegroundColor Cyan
    Write-Host "Project: $gatewayProject" -ForegroundColor DarkGray
    Write-Host "URLs: $Urls" -ForegroundColor DarkGray
    Write-Host "JOURNAL_PROJECT_ROOT: $effectiveProjectRoot" -ForegroundColor DarkGray

    $runArgs = @(
        "run",
        "--project", $gatewayProject,
        "-c", $Configuration,
        "--no-launch-profile",
        "--urls", $Urls,
        "-p:RestoreIgnoreFailedSources=true",
        "-p:NuGetAudit=false"
    )

    & dotnet @runArgs
}
exit $LASTEXITCODE
