$ErrorActionPreference = "Stop"

# Download libwebp
Write-Host "Downloading libwebp..."
Invoke-WebRequest -Uri "https://storage.googleapis.com/downloads.webmproject.org/releases/webp/libwebp-1.3.2-windows-x64.zip" -OutFile "libwebp.zip"

Write-Host "Extracting..."
Expand-Archive -Path "libwebp.zip" -DestinationPath "libwebp_extract" -Force

$cwebp = (Resolve-Path "libwebp_extract\libwebp-*\bin\cwebp.exe").Path
Write-Host "Found cwebp at: $cwebp"

$folders = @("imgs\floorplan", "imgs\amenities", "imgs\gallery")
foreach ($folder in $folders) {
    if (Test-Path $folder) {
        $files = Get-ChildItem -Path $folder -Include *.jpg,*.jpeg,*.png -Recurse
        foreach ($file in $files) {
            $outFile = [System.IO.Path]::ChangeExtension($file.FullName, ".webp")
            Write-Host "Converting $($file.Name) to WebP..."
            & $cwebp -q 80 $file.FullName -o $outFile
        }
    }
}

# Also convert Elevation.jpg
if (Test-Path "imgs\Elevation.jpg") {
    $outFile = [System.IO.Path]::ChangeExtension("imgs\Elevation.jpg", ".webp")
    Write-Host "Converting Elevation.jpg to WebP..."
    & $cwebp -q 80 "imgs\Elevation.jpg" -o $outFile
}

Write-Host "Done converting images!"
