import sharp from "sharp";
import path from "path";
import { fileURLToPath } from "url";
import fs from "fs";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const iconsDir = path.join(__dirname, "../public/images/icons");
const publicDir = path.join(__dirname, "../public");
const source = path.join(iconsDir, "logo-mark.svg");

const BRAND = { r: 255, g: 16, b: 125, alpha: 1 };
const WHITE = { r: 255, g: 255, b: 255, alpha: 1 };

async function renderSquareIcon(size, paddingRatio = 0.18) {
  const inner = Math.round(size * (1 - paddingRatio * 2));
  const padding = Math.round((size - inner) / 2);

  const mark = await sharp(source, { density: 512 })
    .resize(inner, inner, {
      fit: "contain",
      background: { r: 0, g: 0, b: 0, alpha: 0 },
    })
    .png()
    .toBuffer();

  return sharp({
    create: {
      width: size,
      height: size,
      channels: 4,
      background: WHITE,
    },
  })
    .composite([{ input: mark, left: padding, top: padding }])
    .png()
    .toFile(path.join(iconsDir, `${size}x${size}.png`));
}

async function renderMaskableIcon(size) {
  const inner = Math.round(size * 0.52);
  const padding = Math.round((size - inner) / 2);

  const mark = await sharp(source, { density: 512 })
    .resize(inner, inner, {
      fit: "contain",
      background: { r: 0, g: 0, b: 0, alpha: 0 },
    })
    .png()
    .toBuffer();

  await sharp({
    create: {
      width: size,
      height: size,
      channels: 4,
      background: BRAND,
    },
  })
    .composite([{ input: mark, left: padding, top: padding }])
    .png()
    .toFile(path.join(iconsDir, `maskable-${size}.png`));

  console.log(`Created maskable-${size}.png`);
}

if (!fs.existsSync(source)) {
  console.error("Missing logo-mark.svg");
  process.exit(1);
}

for (const size of [192, 256, 512]) {
  await renderSquareIcon(size);
  console.log(`Created ${size}x${size}.png`);
}

await sharp(path.join(iconsDir, "512x512.png"))
  .resize(180, 180)
  .png()
  .toFile(path.join(iconsDir, "apple-touch-icon.png"));
console.log("Created apple-touch-icon.png");

await renderMaskableIcon(192);
await renderMaskableIcon(512);

await sharp(path.join(iconsDir, "192x192.png"))
  .resize(32, 32)
  .png()
  .toFile(path.join(publicDir, "favicon.png"));

await sharp(path.join(publicDir, "favicon.png"))
  .resize(16, 16)
  .toFile(path.join(publicDir, "favicon-16.png"));

console.log("Created favicon.png");
