import sharp from 'sharp';
import { writeFile, unlink, stat } from 'node:fs/promises';
import { join } from 'node:path';

// Opaque-photo PNGs to convert to JPG (verified via metadata: no alpha)
const targets = [
  'archie-auckland-dog-walking-review',
  'monty-auckland-dog-walking-review',
  'otis-auckland-dog-walking-review',
  'wallace-auckland-dog-walking-review',
  'one-on-one-dog-portrait-1',
  'one-on-one-dog-portrait-2',
  'one-on-one-dog-portrait-3',
  'small-medium-dogs-pack-walk',
  'auckland-pack-walk-small-dogs-group',
  'founder-image-aless-goodwalk'
];

const dirs = ['src/lib/images', 'static/images'];
const MAX_WIDTH = 1600;

let totalOrig = 0;
let totalNew = 0;
for (const dir of dirs) {
  for (const name of targets) {
    const png = join(dir, name + '.png');
    const jpg = join(dir, name + '.jpg');
    try {
      const orig = (await stat(png)).size;
      const buf = await sharp(png)
        .rotate()
        .resize({ width: MAX_WIDTH, withoutEnlargement: true })
        .jpeg({ quality: 82, mozjpeg: true, progressive: true })
        .toBuffer();
      await writeFile(jpg, buf);
      await unlink(png);
      totalOrig += orig;
      totalNew += buf.length;
      console.log(`${name.padEnd(45)} ${(orig/1024).toFixed(0).padStart(5)}KB png → ${(buf.length/1024).toFixed(0).padStart(4)}KB jpg`);
    } catch (err) {
      console.error('FAILED', png, err.message);
    }
  }
}
console.log(`\nTotal: ${(totalOrig/1024/1024).toFixed(2)} MB → ${(totalNew/1024/1024).toFixed(2)} MB`);
