# Stop on errors
$ErrorActionPreference = "Stop"

# --- Resolve project root (folder where script is located)
$ROOT = Split-Path -Parent $MyInvocation.MyCommand.Path

# --- Load .env if WOW_HOME not already set
if (-not $env:WOW_HOME) {
    $envFile = Join-Path $ROOT ".env"

    if (Test-Path $envFile) {
        Write-Host "Loading .env file..."

        Get-Content $envFile | ForEach-Object {
            if ($_ -match "^\s*([^#][^=]+)=(.+)$") {
                $name = $matches[1].Trim()
                $value = $matches[2].Trim()
                [System.Environment]::SetEnvironmentVariable($name, $value)
                Set-Item -Path "Env:$name" -Value $value
            }
        }
    }
}

# --- Validate WOW_HOME
if (-not $env:WOW_HOME) {
    Write-Error "WOW_HOME is not set (env or .env)"
    exit 1
}

$WOW_HOME = $env:WOW_HOME
Write-Host "WOW_HOME = $WOW_HOME"

# --- Paths
$SRC_DIR      = Join-Path $ROOT "src"
$DIST_DIR     = Join-Path $ROOT "dist"
$TOOL         = Join-Path $ROOT "tool\target\release\tool.exe"
$RELOAD_SCRIPT = Join-Path $ROOT "reload_wow.bat"
$WXL_BUILD_SCRIPT = Join-Path $ROOT "build-warcraftxl.ps1"

# --- Ensure tool exists
if (!(Test-Path $TOOL)) {
    Write-Host "Building Rust tool..."
    Push-Location (Join-Path $ROOT "tool")
    cargo build --release
    Pop-Location
}

# --- Build MPQ archives into dist/
Write-Host "Building MPQ archives from src/ -> dist/..."
& $TOOL $SRC_DIR $DIST_DIR
if ($LASTEXITCODE -ne 0) {
    Write-Error "MPQ build failed!"
    exit 1
}

# --- Verify result
if (!(Test-Path (Join-Path $DIST_DIR "Data"))) {
    Write-Error "dist\Data not found after build!"
    exit 1
}

# --- Build/package/deploy WarcraftXL before the dist sync. The packaged files
#     are uploaded by upload_to_s3.py and consumed by the launcher manifest.
Write-Host "Building and packaging WarcraftXL..."
& $WXL_BUILD_SCRIPT -Configuration Release -ClientPath $WOW_HOME `
    -PackagePath $DIST_DIR -Deploy
if ($LASTEXITCODE -ne 0) {
    Write-Error "WarcraftXL build/deploy failed!"
    exit 1
}

# --- Sync dist/ -> WOW_HOME
Write-Host "Syncing dist/ -> WOW_HOME..."
robocopy $DIST_DIR $WOW_HOME /E /NFL /NDL
# robocopy exit codes 0-7 are success/warnings; 8+ are errors
if ($LASTEXITCODE -ge 8) {
    Write-Error "robocopy failed with exit code $LASTEXITCODE"
    exit 1
}

Write-Host "MPQ archives deployed to $WOW_HOME"

# --- Run WoW reload script
Write-Host "Launching WoW..."
cmd /c $RELOAD_SCRIPT
