param(
    [ValidateSet("Release", "Debug")]
    [string]$Configuration = "Release",
    [string]$Runtime = "win-x64",
    [switch]$SkipSidecar,
    [switch]$SkipWeb,
    [switch]$SkipWebGateway,
    [switch]$SkipTauri,
    [switch]$DryRun
)

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

$repoRoot = Resolve-JournalRepoRoot -StartPath $PSScriptRoot
$appRoot = Resolve-JournalAppRoot -RepoRoot $repoRoot
$outputRoot = Join-Path $repoRoot "output"

$publishSidecar = Join-Path $PSScriptRoot "publish-sidecar.ps1"
$publishApp = Join-Path $PSScriptRoot "publish-app.ps1"
$publishGateway = Join-Path $PSScriptRoot "publish-webgateway.ps1"

Write-Host "Publishing all outputs to: $outputRoot" -ForegroundColor Cyan
Write-Host "Configuration: $Configuration  Runtime: $Runtime" -ForegroundColor DarkGray

if (-not (Test-Path $outputRoot)) {
    New-Item -ItemType Directory -Force -Path $outputRoot | Out-Null
}

function Invoke-Step {
    param(
        [string]$Label,
        [string]$ScriptPath,
        [string[]]$Args
    )

    Write-Host "`n> $Label" -ForegroundColor Cyan
    Write-Host "  $ScriptPath $($Args -join ' ')" -ForegroundColor DarkGray
    if (-not $DryRun) {
        & $ScriptPath @Args
    }
}

if (-not $SkipSidecar) {
    Invoke-Step "Publish Sidecar" $publishSidecar @(
        "-Configuration", $Configuration,
        "-Runtime", $Runtime
    )
}
else {
    Write-Host "Skipping sidecar publish." -ForegroundColor DarkGray
}

if (-not $SkipWeb) {
    Invoke-Step "Build Web UI" $publishApp @(
        "-Target", "web",
        "-Configuration", $Configuration
    )
}
else {
    Write-Host "Skipping web build." -ForegroundColor DarkGray
}

if (-not $SkipWebGateway) {
    Invoke-Step "Publish WebGateway" $publishGateway @(
        "-Configuration", $Configuration,
        "-Runtime", $Runtime
    )
}
else {
    Write-Host "Skipping WebGateway publish." -ForegroundColor DarkGray
}

if (-not $SkipTauri) {
    Invoke-Step "Build Tauri Desktop App" $publishApp @(
        "-Target", "tauri",
        "-Configuration", $Configuration,
        "-TauriBundles", "none"
    )

    $targetConfigDir = if ($Configuration -eq "Debug") { "debug" } else { "release" }
    $tauriExePath = Join-Path $appRoot "src-tauri\\target\\$targetConfigDir\\journalapp.exe"
    $stagedExePath = Join-Path $outputRoot "journalapp.exe"

    if (Test-Path $tauriExePath) {
        if ($DryRun) {
            Write-Host "Would copy: $tauriExePath -> $stagedExePath" -ForegroundColor Yellow
        }
        else {
            Copy-Item -Force $tauriExePath $stagedExePath
            Write-Host "Staged desktop exe: $stagedExePath" -ForegroundColor Green
        }
    }
    else {
        Write-Warning "Tauri exe not found at $tauriExePath"
    }
}
else {
    Write-Host "Skipping Tauri build." -ForegroundColor DarkGray
}
