import fs from "node:fs/promises";
import path from "node:path";
import sharp from "sharp";

const publicDir = path.resolve("public");
const files = (await fs.readdir(publicDir)).filter((name) => /^(login-(?:workspace|landscape)-.+|admin-login-workspace)\.png$/.test(name));

for (const filename of files) {
  const source = path.join(publicDir, filename);
  const basename = filename.replace(/\.png$/, "");
  await sharp(source)
    .resize({ width: 1672, height: 1000, fit: "inside", withoutEnlargement: true })
    .webp({ quality: 80, effort: 6, smartSubsample: true })
    .toFile(path.join(publicDir, `${basename}.webp`));

  if (basename.startsWith("login-")) {
    await sharp(source)
      .resize({ width: 420, height: 236, fit: "cover", position: "centre" })
      .webp({ quality: 68, effort: 6, smartSubsample: true })
      .toFile(path.join(publicDir, `${basename}-thumb.webp`));
  }
}

for (const filename of ["brand-logo.png", "pwa-192.png", "pwa-512.png"]) {
  const source = path.join(publicDir, filename);
  const temporary = `${source}.optimized`;
  await sharp(source).png({ compressionLevel: 9, palette: true, quality: 88, effort: 10 }).toFile(temporary);
  const [original, optimized] = await Promise.all([fs.stat(source), fs.stat(temporary)]);
  if (optimized.size < original.size) await fs.rename(temporary, source);
  else await fs.unlink(temporary);
}
