/**
 * convert-to-webp.js
 * Converte todas as imagens PNG de assets/images/ para WebP
 * Uso: node scripts/convert-to-webp.js
 */

const sharp = require('sharp');
const path  = require('path');
const fs    = require('fs');

const inputDir  = path.join(__dirname, '..', 'assets', 'images');
const outputDir = inputDir; // mesmo diretório — arquivo .webp lado a lado

const files = fs.readdirSync(inputDir).filter(f => /\.(png|jpg|jpeg)$/i.test(f));

console.log(`\n🖼️  Encontradas ${files.length} imagens para converter...\n`);

(async () => {
  for (const file of files) {
    const inputPath  = path.join(inputDir, file);
    const outputName = file.replace(/\.(png|jpg|jpeg)$/i, '.webp');
    const outputPath = path.join(outputDir, outputName);

    try {
      const info = await sharp(inputPath)
        .webp({ quality: 82, effort: 6 })
        .toFile(outputPath);

      const origSize = fs.statSync(inputPath).size;
      const newSize  = fs.statSync(outputPath).size;
      const saving   = (((origSize - newSize) / origSize) * 100).toFixed(1);

      console.log(
        `  ✅ ${file.padEnd(22)} → ${outputName.padEnd(22)}` +
        `  ${(origSize / 1024).toFixed(0).padStart(6)} KB → ${(newSize / 1024).toFixed(0).padStart(5)} KB  (-${saving}%)`
      );
    } catch (err) {
      console.error(`  ❌ Erro em ${file}: ${err.message}`);
    }
  }

  console.log('\n✨ Conversão concluída!\n');
})();
