import imagemin from 'imagemin';
import imageminMozjpeg from 'imagemin-mozjpeg';
import imageminOptipng from 'imagemin-optipng';
import imageminWebp from 'imagemin-webp';
import imageminAvif from 'imagemin-avif';
import path from 'path';

const source = path.join(process.cwd(), 'public/images/*.{jpg,png}');
const destinationOptimized = path.join(process.cwd(), 'public/images-optimized');
const destinationWebP = path.join(process.cwd(), 'public/images-optimized/webp');
const destinationAvif = path.join(process.cwd(), 'public/images-optimized/avif');

(async () => {
  try {
    // Optimize JPEG / PNG
    const filesOptimized = await imagemin([source], {
      destination: destinationOptimized,
      plugins: [
        imageminMozjpeg({ quality: 90 }),
        imageminOptipng({ optimizationLevel: 3 }),
      ],
    });

    console.log('JPEG/PNG optimized:', filesOptimized.map(f => f.destinationPath));

    // Convert to WebP
    const filesWebP = await imagemin([source], {
      destination: destinationWebP,
      plugins: [
        imageminWebp({ quality: 80 }),
      ],
    });
    console.log('Converted to WebP:', filesWebP.map(f => f.destinationPath));

    // Convert to AVIF
    const filesAvif = await imagemin([source], {
      destination: destinationAvif,
      plugins: [
        imageminAvif({ quality: 50 }),
      ],
    });
    console.log('Converted to AVIF:', filesAvif.map(f => f.destinationPath));

  } catch (error) {
    console.error('Error optimizing images:', error);
  }
})();
