[CmdletBinding()]
param(
    [ValidateSet('Debug', 'Release')]
    [string]$Configuration = 'Release',
    [string]$ClientPath = '',
    [string]$PackagePath = '',
    [switch]$Deploy,
    [switch]$NativeRenderer
)

$ErrorActionPreference = 'Stop'
$repoRoot = $PSScriptRoot
$cmake = 'C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe'
if (-not (Test-Path -LiteralPath $cmake)) {
    $cmakeCommand = Get-Command cmake -ErrorAction SilentlyContinue
    if (-not $cmakeCommand) { throw 'CMake 3.20+ was not found.' }
    $cmake = $cmakeCommand.Source
}

& git -C $repoRoot submodule update --init --recursive
if ($LASTEXITCODE -ne 0) { throw 'Failed to initialize WarcraftXL submodules.' }

$win32BuildDir = Join-Path $repoRoot 'build\warcraftxl-win32'
$hostBuildDir = Join-Path $repoRoot 'build\warcraftxl-host-x64'
$stockExe = Join-Path $repoRoot 'Wow_Original.exe'

if ($Deploy -or -not [string]::IsNullOrWhiteSpace($PackagePath)) {
    if (-not (Test-Path -LiteralPath $stockExe -PathType Leaf)) {
        throw "Stock executable was not found: $stockExe"
    }
    $expectedStockHash = 'AA63A5750D60EF16746C686B3D5E26876D98953EAB08B1C026CD0FAF78E88CB8'
    $stockHash = (Get-FileHash -LiteralPath $stockExe -Algorithm SHA256).Hash
    if ($stockHash -ne $expectedStockHash) {
        throw "Wow_Original.exe is not the verified MoonWell 3.3.5a stock executable (SHA-256 $stockHash)."
    }
}

& $cmake -S $repoRoot -B $win32BuildDir -A Win32 '-DCLIENT_PATH='
if ($LASTEXITCODE -ne 0) { throw 'WarcraftXL Win32 configure failed.' }
& $cmake --build $win32BuildDir --config $Configuration --target WarcraftXL d3d9 MoonWellLoader
if ($LASTEXITCODE -ne 0) { throw 'WarcraftXL Win32 build failed.' }

& $cmake -S $repoRoot -B $hostBuildDir -A x64 '-DWXL_BUILD_HOST=ON' '-DCLIENT_PATH='
if ($LASTEXITCODE -ne 0) { throw 'WarcraftXL Host configure failed.' }
& $cmake --build $hostBuildDir --config $Configuration --target WarcraftXLHost
if ($LASTEXITCODE -ne 0) { throw 'WarcraftXL Host build failed.' }

$win32ArtifactDir = Join-Path $win32BuildDir "vendor\warcraftxl\$Configuration"
$hostArtifactDir = Join-Path $hostBuildDir "vendor\warcraftxl\$Configuration"
$warcraftXL = Join-Path $win32ArtifactDir 'WarcraftXL.dll'
$modernProxy = Join-Path $win32ArtifactDir 'd3d9.dll'
$nativeProxy = Join-Path $win32BuildDir "artifacts\$Configuration\d3d9-native.dll"
$hostExe = Join-Path $hostArtifactDir 'WarcraftXLHost.exe'
$selectedProxy = if ($NativeRenderer) { $nativeProxy } else { $modernProxy }
$adtResources = Join-Path $repoRoot 'vendor\modules\wxl-modern-adt\_resources'

function Install-WarcraftXLArtifacts {
    param([Parameter(Mandatory)][string]$Destination)

    $utils = Join-Path $Destination 'Utils'
    $loosePatch = Join-Path $Destination 'Data\Patch-WXL.MPQ'
    New-Item -ItemType Directory -Path $Destination, $utils, $loosePatch -Force | Out-Null

    Copy-Item -LiteralPath $stockExe -Destination (Join-Path $Destination 'Wow.exe') -Force
    Copy-Item -LiteralPath $warcraftXL -Destination (Join-Path $Destination 'WarcraftXL.dll') -Force
    Copy-Item -LiteralPath $selectedProxy -Destination (Join-Path $Destination 'd3d9.dll') -Force
    Copy-Item -LiteralPath $nativeProxy -Destination (Join-Path $utils 'd3d9-native.dll') -Force
    Copy-Item -LiteralPath $hostExe -Destination (Join-Path $utils 'WarcraftXLHost.exe') -Force
    Get-ChildItem -LiteralPath $adtResources | ForEach-Object {
        Copy-Item -LiteralPath $_.FullName -Destination $loosePatch -Recurse -Force
    }
}

if ($Deploy) {
    if ([string]::IsNullOrWhiteSpace($ClientPath)) {
        $ClientPath = 'C:\Program Files (x86)\World of Warcraft'
    }
    $ClientPath = [System.IO.Path]::GetFullPath($ClientPath)
    if (-not (Test-Path -LiteralPath $ClientPath -PathType Container)) {
        throw "Client directory was not found: $ClientPath"
    }

    $clientExe = Join-Path $ClientPath 'Wow.exe'
    if (Test-Path -LiteralPath $clientExe -PathType Leaf) {
        $clientHash = (Get-FileHash -LiteralPath $clientExe -Algorithm SHA256).Hash
        if ($clientHash -ne $stockHash) {
            $legacyBackup = Join-Path $ClientPath 'Wow.moonwell-patched.backup.exe'
            if (-not (Test-Path -LiteralPath $legacyBackup)) {
                Copy-Item -LiteralPath $clientExe -Destination $legacyBackup
            }
            Write-Host "Legacy executable saved as $legacyBackup"
        }
    }

    Install-WarcraftXLArtifacts -Destination $ClientPath
    Write-Host "Installed WarcraftXL runtime, host and modules in $ClientPath"
}

if (-not [string]::IsNullOrWhiteSpace($PackagePath)) {
    $PackagePath = [System.IO.Path]::GetFullPath($PackagePath)
    Install-WarcraftXLArtifacts -Destination $PackagePath
    Write-Host "Packaged stock Wow.exe and WarcraftXL artifacts in $PackagePath"
}

$renderer = if ($NativeRenderer) { 'native D3D9 recovery proxy' } else { 'WarcraftXL D3D9On12 proxy' }
Write-Host "WarcraftXL build complete ($renderer): $win32ArtifactDir"
