param(
    [string]$OutputZip = "nuget-cache-export.zip",
    [switch]$IncludeDotnetHome
)

$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
$outputPath = if ([System.IO.Path]::IsPathRooted($OutputZip)) { $OutputZip } else { Join-Path $repoRoot $OutputZip }
$outputDir = Split-Path -Parent $outputPath
if (-not (Test-Path $outputDir)) {
    New-Item -ItemType Directory -Force -Path $outputDir | Out-Null
}

Write-Host "Priming restore cache..."
& (Join-Path $PSScriptRoot "dotnet-min.ps1") restore "Journal.Sidecar/Journal.Sidecar.csproj"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& (Join-Path $PSScriptRoot "dotnet-min.ps1") restore "Journal.WebGateway/Journal.WebGateway.csproj"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& (Join-Path $PSScriptRoot "dotnet-min.ps1") restore "Journal.SmokeTests/Journal.SmokeTests.csproj"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

$staging = Join-Path $repoRoot ".nuget-export-staging"
if (Test-Path $staging) {
    Remove-Item -Recurse -Force $staging
}
New-Item -ItemType Directory -Force -Path $staging | Out-Null

$nugetRoot = Join-Path $repoRoot ".nuget"
if (-not (Test-Path $nugetRoot)) {
    Write-Error "No .nuget directory found under $repoRoot"
    exit 1
}

Copy-Item -Recurse -Force -Path $nugetRoot -Destination (Join-Path $staging ".nuget")
if ($IncludeDotnetHome) {
    $dotnetHome = Join-Path $repoRoot ".dotnet_home"
    if (Test-Path $dotnetHome) {
        Copy-Item -Recurse -Force -Path $dotnetHome -Destination (Join-Path $staging ".dotnet_home")
    }
}

$manifest = @(
    "exported_utc=$([DateTime]::UtcNow.ToString("o"))"
    "repo_root=$repoRoot"
    "include_dotnet_home=$($IncludeDotnetHome.IsPresent)"
    "note=Copy this zip to target machine and run scripts/nuget-import-cache.ps1"
)
$manifest | Set-Content -Encoding UTF8 -Path (Join-Path $staging "nuget-cache-manifest.txt")

if (Test-Path $outputPath) {
    Remove-Item -Force $outputPath
}

Compress-Archive -Path (Join-Path $staging "*") -DestinationPath $outputPath -Force
Remove-Item -Recurse -Force $staging

Write-Host "NuGet cache export created at: $outputPath"

