import sharp from 'sharp';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const assetsDir = path.join(__dirname, '..', 'assets');

let totalOriginal = 0;
let totalOptimized = 0;
let fileCount = 0;

async function optimizeImage(filePath) {
    const ext = path.extname(filePath).toLowerCase();
    if (!['.png', '.jpg', '.jpeg'].includes(ext)) return;

    const stats = fs.statSync(filePath);
    const originalSize = stats.size;
    totalOriginal += originalSize;

    const webpPath = filePath.replace(/\.(png|jpg|jpeg)$/i, '.webp');

    try {
        await sharp(filePath)
            .resize({ width: 800, withoutEnlargement: true })
            .webp({ quality: 80 })
            .toFile(webpPath);

        const newStats = fs.statSync(webpPath);
        totalOptimized += newStats.size;
        fileCount++;

        // Delete the original PNG/JPG
        fs.unlinkSync(filePath);

        const saved = ((1 - newStats.size / originalSize) * 100).toFixed(1);
        console.log(`✓ ${path.basename(filePath)} → ${path.basename(webpPath)} (${(originalSize/1024/1024).toFixed(2)}MB → ${(newStats.size/1024/1024).toFixed(2)}MB, saved ${saved}%)`);
    } catch (err) {
        console.error(`✗ Failed: ${filePath}`, err.message);
    }
}

async function walkDir(dir) {
    const entries = fs.readdirSync(dir, { withFileTypes: true });
    for (const entry of entries) {
        const fullPath = path.join(dir, entry.name);
        if (entry.isDirectory()) {
            await walkDir(fullPath);
        } else {
            await optimizeImage(fullPath);
        }
    }
}

console.log('🔄 Starting image optimization...\n');
await walkDir(assetsDir);
console.log(`\n✅ Done! Optimized ${fileCount} images.`);
console.log(`📊 Total: ${(totalOriginal/1024/1024).toFixed(2)}MB → ${(totalOptimized/1024/1024).toFixed(2)}MB (saved ${((1 - totalOptimized/totalOriginal) * 100).toFixed(1)}%)`);
