<?php
/**
 * One-time utility: convert raster images under assets/images to compressed WebP.
 */
$root = dirname(__DIR__);
$imagesDir = $root . '/assets/images';
$quality = 82;
$logoQuality = 90;

$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($imagesDir, FilesystemIterator::SKIP_DOTS)
);

$converted = 0;
$failed = 0;
$origTotal = 0;
$newTotal = 0;

foreach ($iterator as $file) {
    if (!$file->isFile()) {
        continue;
    }

    $ext = strtolower($file->getExtension());
    if (!in_array($ext, ['png', 'jpg', 'jpeg', 'gif'], true)) {
        continue;
    }

    $src = $file->getPathname();
    $webp = preg_replace('/\.[^.]+$/i', '.webp', $src);
    $img = null;

    switch ($ext) {
        case 'png':
            $img = @imagecreatefrompng($src);
            if ($img) {
                imagepalettetotruecolor($img);
                imagealphablending($img, true);
                imagesavealpha($img, true);
            }
            break;
        case 'gif':
            $img = @imagecreatefromgif($src);
            break;
        case 'jpg':
        case 'jpeg':
            $img = @imagecreatefromjpeg($src);
            break;
    }

    if (!$img) {
        echo "FAIL: {$src}\n";
        $failed++;
        continue;
    }

    $q = (str_contains($src, 'platform-logos') || filesize($src) < 50000) ? $logoQuality : $quality;
    $origSize = filesize($src);
    imagewebp($img, $webp, $q);
    imagedestroy($img);

    if (!is_file($webp)) {
        echo "FAIL write: {$webp}\n";
        $failed++;
        continue;
    }

    $newSize = filesize($webp);
    $origTotal += $origSize;
    $newTotal += $newSize;
    $converted++;

    $rel = str_replace($root . DIRECTORY_SEPARATOR, '', $src);
    printf(
        "%s  %sKB -> %sKB\n",
        $rel,
        round($origSize / 1024, 1),
        round($newSize / 1024, 1)
    );
}

printf(
    "\nDone: %d converted, %d failed. Total %sKB -> %sKB (saved %sKB)\n",
    $converted,
    $failed,
    round($origTotal / 1024, 1),
    round($newTotal / 1024, 1),
    round(max(0, $origTotal - $newTotal) / 1024, 1)
);
