# 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

# --- patch-ruRU-4
$INPUT_DIR_4 = Join-Path $ROOT "patch-ruRU-4"
$OUTPUT_MPQ_4 = Join-Path $WOW_HOME "Data\ruRU\patch-ruRU-4.MPQ"

# --- patch-ruRU-5
$INPUT_DIR_5 = Join-Path $ROOT "patch-ruRU-5"
$OUTPUT_MPQ_5 = Join-Path $WOW_HOME "Data\ruRU\patch-ruRU-5.MPQ"

$TOOL = Join-Path $ROOT "tool\target\release\tool.exe"
$RELOAD_SCRIPT = Join-Path $ROOT "reload_wow.bat"

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

# --- Ensure WoW directory exists
$wowDataDir = Join-Path $WOW_HOME "Data\ruRU"
if (!(Test-Path $wowDataDir)) {
    New-Item -ItemType Directory -Force -Path $wowDataDir | Out-Null
}

# --- Build MPQ
Write-Host "Building MPQ..."
& $TOOL $INPUT_DIR_4 $OUTPUT_MPQ_4
& $TOOL $INPUT_DIR_5 $OUTPUT_MPQ_5

# --- Verify result
if (!(Test-Path $OUTPUT_MPQ_5)) {
    Write-Error "MPQ build failed!"
    exit 1
}

Write-Host "MPQ created"

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