[CmdletBinding()]
param(
    [ValidateSet("Debug", "Release")]
    [string]$Configuration = "Release",

    [ValidateSet("NoAimbot", "WithAimbot")]
    [string]$Flavor = "NoAimbot",

    [ValidateSet("x64")]
    [string]$Platform = "x64",

    [string]$DeployDir = "",
    [string]$MSBuildPath = ""
)

$ErrorActionPreference = "Stop"
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
$project = Join-Path $root "src\TarkovAddonsRefactored.vcxproj"
$configurationDir = $Configuration.ToLowerInvariant()
$flavorDir = if ($Flavor -eq "WithAimbot") { "with_aimbot" } else { "no_aimbot" }
$packageDir = Join-Path $root ("out\{0}\{1}\TarkovAddonsRefactored" -f $configurationDir, $flavorDir)

function Find-MSBuild {
    param([string]$ExplicitPath)

    if ($ExplicitPath) {
        if (-not (Test-Path -LiteralPath $ExplicitPath)) {
            throw "MSBuild.exe was not found: $ExplicitPath"
        }
        return (Resolve-Path -LiteralPath $ExplicitPath).Path
    }

    $vswherePaths = @(
        "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe",
        "${env:ProgramFiles}\Microsoft Visual Studio\Installer\vswhere.exe"
    )
    foreach ($vswhere in $vswherePaths) {
        if (-not (Test-Path -LiteralPath $vswhere)) { continue }
        $installation = & $vswhere -latest -products * -requires Microsoft.Component.MSBuild -property installationPath
        if ($installation) {
            $candidate = Join-Path $installation "MSBuild\Current\Bin\MSBuild.exe"
            if (Test-Path -LiteralPath $candidate) { return $candidate }
        }
    }

    $knownPaths = @(
        "C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\MSBuild.exe",
        "C:\Program Files\Microsoft Visual Studio\2022\BuildTools\MSBuild\Current\Bin\MSBuild.exe"
    )
    foreach ($candidate in $knownPaths) {
        if (Test-Path -LiteralPath $candidate) { return $candidate }
    }

    throw "MSBuild.exe was not found. Install Visual Studio C++ Build Tools or pass -MSBuildPath."
}

if (-not (Test-Path -LiteralPath $project)) {
    throw "Project was not found: $project"
}

$msbuild = Find-MSBuild -ExplicitPath $MSBuildPath
Write-Host "Building and packaging TarkovAddonsRefactored" -ForegroundColor Cyan
Write-Host "  Configuration: $Configuration"
Write-Host "  Flavor:        $Flavor"
Write-Host "  Platform:      $Platform"
Write-Host "  MSBuild:       $msbuild"
Write-Host "  Package:       $packageDir"

$arguments = @(
    $project,
    "/t:Package",
    "/p:Configuration=$Configuration",
    "/p:Platform=$Platform",
    "/p:Flavor=$Flavor",
    "/p:PackageDir=$packageDir",
    "/m"
)
if ($DeployDir.Trim().Length -gt 0) {
    $arguments += "/p:DeployDir=$DeployDir"
}

& $msbuild @arguments
if ($LASTEXITCODE -ne 0) {
    throw "Build/package failed with exit code $LASTEXITCODE."
}

$required = @(
    (Join-Path $packageDir "TarkovAddonsRefactored.dll"),
    (Join-Path $packageDir "locales\de-DE.json"),
    (Join-Path $packageDir "locales\en.json"),
    (Join-Path $packageDir "locales\es-ES.json"),
    (Join-Path $packageDir "locales\fr-FR.json"),
    (Join-Path $packageDir "locales\ja-JP.json"),
    (Join-Path $packageDir "locales\ko-KR.json"),
    (Join-Path $packageDir "locales\ru-RU.json"),
    (Join-Path $packageDir "locales\zh-CN.json"),
    (Join-Path $packageDir "resources\chams.bundle")
)
foreach ($path in $required) {
    if (-not (Test-Path -LiteralPath $path)) {
        throw "Package validation failed: $path"
    }
}

$dll = Get-Item -LiteralPath $required[0]
$hash = (Get-FileHash -LiteralPath $dll.FullName -Algorithm SHA256).Hash
Write-Host ""
Write-Host "Package succeeded:" -ForegroundColor Green
Write-Host "  $packageDir"
Write-Host "  DLL bytes: $($dll.Length)"
Write-Host "  DLL SHA256: $hash"
if ($DeployDir.Trim().Length -gt 0) {
    Write-Host "  Deployed: $DeployDir"
}
