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

const imagesToConvert = [
  { src: 'sh.png', dest: 'sh.avif' },
  { src: 'seeds.jpg', dest: 'seeds.avif' },
  { src: 'cutlings.jpg', dest: 'cutlings.avif' },
  { src: 'gg.png', dest: 'gg.avif' },
  { src: 'konfigurator.png', dest: 'konfigurator.avif' },
  { src: 'maps.png', dest: 'maps.avif' }
];

const run = async () => {
  const imagesDir = path.join(__dirname, '../public/assets/images');
  let hasError = false;

  for (const image of imagesToConvert) {
    const inputPath = path.join(imagesDir, image.src);
    const outputPath = path.join(imagesDir, image.dest);

    if (!fs.existsSync(inputPath)) {
      console.warn(`⚠️ Input file not found: ${inputPath}`);
      continue;
    }

    // Check if output file exists and compare modification times
    // Only convert if source is newer or destination doesn't exist
    let shouldConvert = true;
    if (fs.existsSync(outputPath)) {
      const inputStat = fs.statSync(inputPath);
      const outputStat = fs.statSync(outputPath);
      if (inputStat.mtime <= outputStat.mtime) {
        shouldConvert = false;
      }
    }

    if (shouldConvert) {
      try {
        await sharp(inputPath)
          .toFormat('avif')
          .toFile(outputPath);
        console.log(`✅ Converted ${image.src} to ${image.dest}`);
      } catch (error) {
        console.error(`❌ Error converting ${image.src}:`, error.message);
        hasError = true;
      }
    } else {
      // Silent skip if already up to date to keep logs clean, or use verbose flag
      // console.log(`Skipping ${image.src} (already up to date)`);
    }
  }

  if (hasError) {
    process.exit(1);
  }
};

run();
