$ErrorActionPreference = "Stop"
$texturesDir = "textures"
$texconvUrl = "https://github.com/Microsoft/DirectXTex/releases/latest/download/texconv.exe"
$texconvPath = ".\texconv.exe"

Write-Host "=== Texture Optimization Tool ===" -ForegroundColor Cyan
Write-Host ""

# Download texconv if not present
if (-not (Test-Path $texconvPath)) {
    Write-Host "Downloading texconv.exe..." -ForegroundColor Yellow
    try {
        Invoke-WebRequest -Uri $texconvUrl -OutFile $texconvPath -UseBasicParsing
        Write-Host "Downloaded texconv.exe" -ForegroundColor Green
    } catch {
        Write-Host "Failed to download texconv. Please download manually from:" -ForegroundColor Red
        Write-Host "https://github.com/Microsoft/DirectXTex/releases" -ForegroundColor Yellow
        exit 1
    }
}

Write-Host "1. Converting PNG to DDS..." -ForegroundColor Cyan
$pngFiles = @("8539177_orig.png", "Decals.png", "Logo.png", "Piano89.png")
foreach ($png in $pngFiles) {
    $pngPath = Join-Path $texturesDir $png
    if (Test-Path $pngPath) {
        Write-Host "  Converting $png..." -ForegroundColor White
        & $texconvPath -f DXT5 -o $texturesDir $pngPath
        if ($LASTEXITCODE -eq 0) {
            Remove-Item $pngPath
            Write-Host "  ✓ Converted and removed $png" -ForegroundColor Green
        }
    }
}

Write-Host ""
Write-Host "2. Resizing oversized DDS files..." -ForegroundColor Cyan
$oversizedFiles = @("ElectriciansHammer_albedo.dds", "Tools_BaseColor.dds")
foreach ($dds in $oversizedFiles) {
    $ddsPath = Join-Path $texturesDir $dds
    if (Test-Path $ddsPath) {
        $sizeMB = (Get-Item $ddsPath).Length / 1MB
        Write-Host "  $dds - $([math]::Round($sizeMB, 2)) MB" -ForegroundColor White
        Write-Host "  Resizing to 2048x2048..." -ForegroundColor White
        
        $backup = $ddsPath + ".backup"
        Copy-Item $ddsPath $backup
        
        & $texconvPath -w 2048 -h 2048 -f DXT5 -y -o $texturesDir $ddsPath
        
        if ($LASTEXITCODE -eq 0) {
            $newSizeMB = (Get-Item $ddsPath).Length / 1MB
            Write-Host "  ✓ Resized to $([math]::Round($newSizeMB, 2)) MB (backup saved)" -ForegroundColor Green
        } else {
            Move-Item $backup $ddsPath -Force
            Write-Host "  ✗ Failed, restored from backup" -ForegroundColor Red
        }
    }
}

Write-Host ""
Write-Host "=== Complete ===" -ForegroundColor Green
Write-Host "Check your textures folder and test in-game!"
