// In-place raster image optimizer using sharp.
// Keeps filenames + extensions (no code reference changes needed).
// Caps max dimension and re-encodes at good-quality settings.
const fs = require('fs');
const path = require('path');
const sharp = require(path.join(process.cwd(), 'node_modules', 'sharp'));

const DIR = path.join(process.cwd(), 'public', 'images');
const MAX_DIM = 1600;      // cap longest side (hero/bg safe)
const MIN_BYTES = 120 * 1024; // only touch files > 120KB
const WEBP_Q = 72;
const JPG_Q = 76;

async function run() {
  const files = fs.readdirSync(DIR);
  let before = 0, after = 0, changed = 0;
  for (const name of files) {
    const ext = path.extname(name).toLowerCase();
    if (!['.webp', '.png', '.jpg', '.jpeg'].includes(ext)) continue;
    const fp = path.join(DIR, name);
    const stat = fs.statSync(fp);
    if (!stat.isFile() || stat.size < MIN_BYTES) continue;

    try {
      const input = fs.readFileSync(fp);
      const img = sharp(input, { failOn: 'none' });
      const meta = await img.metadata();
      const longest = Math.max(meta.width || 0, meta.height || 0);
      let pipe = sharp(input, { failOn: 'none' }).rotate();
      if (longest > MAX_DIM) {
        pipe = pipe.resize({ width: meta.width >= meta.height ? MAX_DIM : null,
                             height: meta.height > meta.width ? MAX_DIM : null,
                             withoutEnlargement: true });
      }
      let out;
      if (ext === '.webp') out = await pipe.webp({ quality: WEBP_Q, effort: 5 }).toBuffer();
      else if (ext === '.png') out = await pipe.png({ compressionLevel: 9, palette: true, quality: 80 }).toBuffer();
      else out = await pipe.jpeg({ quality: JPG_Q, mozjpeg: true }).toBuffer();

      before += stat.size;
      if (out.length < stat.size) {
        fs.writeFileSync(fp, out);
        after += out.length;
        changed++;
        console.log(`${(stat.size/1024).toFixed(0)}KB -> ${(out.length/1024).toFixed(0)}KB  (${meta.width}x${meta.height}${longest>MAX_DIM?' resized':''})  ${name}`);
      } else {
        after += stat.size;
      }
    } catch (e) {
      console.log(`SKIP ${name}: ${e.message}`);
    }
  }
  console.log(`\n=== ${changed} files optimized. ${(before/1048576).toFixed(1)}MB -> ${(after/1048576).toFixed(1)}MB (saved ${((before-after)/1048576).toFixed(1)}MB) ===`);
}
run();
