import sharp from "sharp";
import path from "path";
import fs from "fs";

const ICONS_DIR = path.join(process.cwd(), "public", "icons");

const SIZES: Record<string, number> = {
    "icon-192.png": 192,
    "icon-512.png": 512,
    "apple-touch-icon.png": 180, // valor estándar iPhone
    "favicon-32.png": 32,
};

export async function generatePngIcons(): Promise<void> {
    const svgPath = path.join(ICONS_DIR, "icon.svg");
    if (!fs.existsSync(svgPath)) {
        console.warn("[Icons] icon.svg no encontrado, se omite generación de PNG");
        return;
    }
    if (!fs.existsSync(ICONS_DIR)) fs.mkdirSync(ICONS_DIR, { recursive: true });

    const svgBuffer = fs.readFileSync(svgPath);

    for (const [name, size] of Object.entries(SIZES)) {
        const outPath = path.join(ICONS_DIR, name);
        // Solo regenerar si el SVG es más reciente
        if (fs.existsSync(outPath)) {
            const svgMtime = fs.statSync(svgPath).mtimeMs;
            const pngMtime = fs.statSync(outPath).mtimeMs;
            if (pngMtime > svgMtime) continue;
        }
        await sharp(svgBuffer)
            .resize(size, size)
            .png({ compressionLevel: 9 })
            .toFile(outPath);
        console.log(`[Icons] Generado ${name} (${size}x${size}px)`);
    }
}
