/**
 * Растеризует app-logo.svg в app-window-icon.png для nativeImage (Windows).
 * Пишет build/icon.png (macOS / fallback) и build/icon.ico — для exe/NSIS и «Программы и компоненты».
 * Запуск: node scripts/gen-window-icon.mjs
 */
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

import { Resvg } from '@resvg/resvg-js';
import toIco from 'to-ico';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const root = path.join(__dirname, '..');
const svgPath = path.join(root, 'app', 'renderer', 'public', 'app-logo.svg');
const outPath = path.join(root, 'app', 'renderer', 'public', 'app-window-icon.png');

const svg = fs.readFileSync(svgPath);
const resvg = new Resvg(svg, {
  fitTo: { mode: 'width', value: 256 },
});
const out = resvg.render();
fs.writeFileSync(outPath, out.asPng());
console.log('wrote', outPath, out.width, 'x', out.height);

const buildDir = path.join(root, 'build');
fs.mkdirSync(buildDir, { recursive: true });
const packIconPath = path.join(buildDir, 'icon.png');
const resvg512 = new Resvg(svg, {
  fitTo: { mode: 'width', value: 512 },
});
const packOut = resvg512.render();
fs.writeFileSync(packIconPath, packOut.asPng());
console.log('wrote', packIconPath, packOut.width, 'x', packOut.height, '(electron-builder mac / fallback)');

function renderPngForWidth(width) {
  const r = new Resvg(svg, {
    fitTo: { mode: 'width', value: width },
  });
  return Buffer.from(r.render().asPng());
}

const icoSizes = [16, 24, 32, 48, 64, 128, 256];
const icoPngs = icoSizes.map((w) => renderPngForWidth(w));
const icoBuf = await toIco(icoPngs);
const icoPath = path.join(buildDir, 'icon.ico');
fs.writeFileSync(icoPath, icoBuf);
console.log('wrote', icoPath, '(electron-builder win)');
