param()

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

$repoRoot = Resolve-JournalRepoRoot -StartPath $PSScriptRoot
$outputDir = Join-Path $repoRoot "output"

# Ensure output exists
New-Item -ItemType Directory -Force -Path $outputDir | Out-Null

Write-Host "Syncing all recent built assets to output directory..." -ForegroundColor Cyan

# Helper to find the newest compiled binary
function Find-NewestBin([string]$SearchPath, [string]$Pattern) {
    if (-not (Test-Path $SearchPath)) { return $null }
    $files = Get-ChildItem -Path $SearchPath -Filter $Pattern -Recurse -File -ErrorAction SilentlyContinue |
    Where-Object { $_.FullName -notmatch '\\obj\\' } |
    Sort-Object LastWriteTime -Descending
    if ($files) { return $files[0] }
    return $null
}

# 1. Front-end Web Assets
$webBuildDir = Join-Path $repoRoot "Journal.App\build"
if (Test-Path $webBuildDir) {
    $webOutputDir = Join-Path $outputDir "webgateway\wwwroot"
    New-Item -ItemType Directory -Force -Path $webOutputDir | Out-Null
    Copy-Item -Path (Join-Path $webBuildDir "*") -Destination $webOutputDir -Recurse -Force
    Write-Host "Synced web assets -> $webOutputDir" -ForegroundColor Green
}

# 2. Sidecar
$sidecarExeName = if ([System.Environment]::OSVersion.Platform -eq "Win32NT") { "Journal.Sidecar.exe" } else { "Journal.Sidecar" }
$sidecarExe = Find-NewestBin -SearchPath (Join-Path $repoRoot "Journal.Sidecar\bin") -Pattern $sidecarExeName
if ($sidecarExe) {
    Copy-Item -Path (Join-Path $sidecarExe.DirectoryName "*") -Destination $outputDir -Recurse -Force
    Write-Host "Synced Journal.Sidecar -> $outputDir" -ForegroundColor Green
}

# 3. WebGateway
$gwExeName = if ([System.Environment]::OSVersion.Platform -eq "Win32NT") { "Journal.WebGateway.exe" } else { "Journal.WebGateway" }
$gwExe = Find-NewestBin -SearchPath (Join-Path $repoRoot "Journal.WebGateway\bin") -Pattern $gwExeName
if ($gwExe) {
    $gwOutputDir = Join-Path $outputDir "webgateway"
    New-Item -ItemType Directory -Force -Path $gwOutputDir | Out-Null
    Copy-Item -Path (Join-Path $gwExe.DirectoryName "*") -Destination $gwOutputDir -Recurse -Force
    Write-Host "Synced Journal.WebGateway -> $gwOutputDir" -ForegroundColor Green
}

# 4. Tauri Desktop App
$tauriExe = Find-NewestBin -SearchPath (Join-Path $repoRoot "Journal.App\src-tauri\target") -Pattern "*.exe"
if ($tauriExe) {
    # Don't try to copy sidecar.exe again if it ended up in tauri target dir
    if ($tauriExe.Name -ne "Journal.Sidecar.exe") {
        Copy-Item -Path $tauriExe.FullName -Destination $outputDir -Force
        Write-Host "Synced Tauri App ($($tauriExe.Name)) -> $outputDir" -ForegroundColor Green
    }
}

Write-Host "Sync complete!" -ForegroundColor Cyan
