# Stop on first error
$ErrorActionPreference = "Stop"

function Show-Usage {
    Write-Host "Usage: ./release-windows.ps1 <version>"
    Write-Host "Example: ./release-windows.ps1 0.0.16"
    exit 1
}

# --- Argument validation ---
if ($args.Count -ne 1) {
    Write-Host "Error: version argument required."
    Show-Usage
}

$VERSION = $args[0]

if ($VERSION -notmatch '^[0-9]+\.[0-9]+\.[0-9]+$') {
    Write-Host "Error: invalid version format. Expected X.Y.Z"
    exit 1
}

$parts = $VERSION.Split('.')
$MAJOR = $parts[0]
$MINOR = $parts[1]
$PATCH = $parts[2]

Write-Host "==> Building Voxelverse $VERSION (Major: $MAJOR, Minor: $MINOR, Patch: $PATCH)"

# --- Clean previous release ---
Remove-Item -Recurse -Force release -ErrorAction SilentlyContinue | Out-Null

# --- Configure ---
Write-Host "==> Configuring project..."
$toolchain = "$env:VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake"
$flags = ('/DNO_PERF_TIMERS /MT /MP4 /EHsc /O2 /W1 /Zc:preprocessor /D\"BUILD_VERSION={{{0}, {1}, {2}}}\"' -f $MAJOR, $MINOR, $PATCH)
& cmake `
    "-G" "Visual Studio 17 2022" `
    "-A" "x64" `
    "-B" "release" `
    "-S" "." `
    "-D" "CMAKE_TOOLCHAIN_FILE=$toolchain" `
    "-D" "CMAKE_CXX_FLAGS:STRING=$flags" `
    "-D" "CMAKE_C_FLAGS:STRING=/MT" `
    "-D" "VOXELVERSE_BIN_SUBDIR=Release" `
    "-D" "CMAKE_BUILD_TYPE=Release"

# --- Build ---
Write-Host "==> Building release..."
cmake --build release --config Release --parallel

# --- Package ---
Write-Host "==> Creating package..."
New-Item -ItemType Directory -Force -Path "release/package" | Out-Null

# Build output folder (for Visual Studio generator)
$buildDir = "release/Release"

# Copy executables and DLLs
Copy-Item "$buildDir/*.exe" "release/package/" -Force
Copy-Item "$buildDir/*.dll" "release/package/" -Force -ErrorAction SilentlyContinue

# Optionally include licenses for all vcpkg dependencies
$licensesDir = "release/package/licenses"
New-Item -ItemType Directory -Force -Path $licensesDir | Out-Null

if ($env:VCPKG_ROOT) {
    $triplet = "x64-windows"
    $installedDir = Join-Path $env:VCPKG_ROOT "installed\$triplet"
    $vcpkgLicenses = Get-ChildItem -Recurse -Include "copyright" -Path $installedDir -ErrorAction SilentlyContinue

    foreach ($file in $vcpkgLicenses) {
        $packageName = Split-Path $file.DirectoryName -Leaf
        $targetFile = Join-Path $licensesDir "$packageName.txt"
        Copy-Item $file.FullName $targetFile -Force
    }

    Write-Host "→ Included $($vcpkgLicenses.Count) license files."
}

# We don't want to bundle vulkan-1.dll because it's part of the system.
Remove-Item -Force "release/package/vulkan-1.dll" -ErrorAction SilentlyContinue

# Compress the final package
Compress-Archive -Path "release/package/*" -DestinationPath "release/bins-windows-$VERSION.zip" -Force

Write-Host "✅ Release package made"