#!/usr/bin/env node
/**
 * Generate favicon.ico and apple-touch-icon.png from frontend/public/icon.svg
 * Run from repo root: node scripts/generate-favicons.js
 */
const fs = require('fs');
const path = require('path');

const PUBLIC = path.join(__dirname, '..', 'frontend', 'public');
const SVG_PATH = path.join(PUBLIC, 'icon.svg');
const APPLE_TOUCH_PATH = path.join(PUBLIC, 'apple-touch-icon.png');
const FAVICON_PATH = path.join(PUBLIC, 'favicon.ico');

async function main() {
  let sharp, toIco;
  try {
    sharp = require('sharp');
    toIco = require('to-ico');
  } catch (e) {
    console.error('Missing dependencies. Run: npm install sharp to-ico --save-dev');
    process.exit(1);
  }

  if (!fs.existsSync(SVG_PATH)) {
    console.error('SVG not found:', SVG_PATH);
    process.exit(1);
  }

  const svgBuffer = fs.readFileSync(SVG_PATH);

  // Apple touch icon: 180x180 PNG
  await sharp(svgBuffer)
    .resize(180, 180)
    .png()
    .toFile(APPLE_TOUCH_PATH);
  console.log('Wrote', APPLE_TOUCH_PATH);

  // Favicon: multi-size ICO (16, 32, 48)
  const sizes = [16, 32, 48];
  const pngBuffers = await Promise.all(
    sizes.map((size) =>
      sharp(svgBuffer).resize(size, size).png().toBuffer()
    )
  );
  const icoBuffer = await toIco(pngBuffers);
  fs.writeFileSync(FAVICON_PATH, icoBuffer);
  console.log('Wrote', FAVICON_PATH);
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
