import { existsSync, readFileSync, statSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const currentDir = dirname(fileURLToPath(import.meta.url));
const iconDir = join(currentDir, "..", "public", "icons");
const requiredSizes = [16, 32, 48, 128, 192, 512, 1024];

function pngDimensions(filePath) {
  const buffer = readFileSync(filePath);
  if (
    buffer.length < 24 ||
    buffer[0] !== 0x89 ||
    buffer[1] !== 0x50 ||
    buffer[2] !== 0x4e ||
    buffer[3] !== 0x47
  ) {
    throw new Error(`${filePath} is not a PNG file.`);
  }

  return {
    width: buffer.readUInt32BE(16),
    height: buffer.readUInt32BE(20)
  };
}

const missingOrInvalid = requiredSizes.flatMap((size) => {
  const filePath = join(iconDir, `icon-${size}.png`);
  if (!existsSync(filePath) || statSync(filePath).size === 0) return [`icon-${size}.png`];

  const dimensions = pngDimensions(filePath);
  if (dimensions.width !== size || dimensions.height !== size) {
    return [`icon-${size}.png (${dimensions.width}x${dimensions.height})`];
  }

  return [];
});

if (missingOrInvalid.length > 0) {
  throw new Error(
    `Missing or invalid branded ProjectCraft Pro icons: ${missingOrInvalid.join(", ")}.`
  );
}

console.log("Using branded ProjectCraft Pro mobile icons.");
