#!/usr/bin/env node
/**
 * Generate icon assets for the AI-Do agent.
 *
 * Produces:
 *   public/icons/favicon.svg        — 32x32 SVG for web
 *   public/icons/icon-192.png       — 192px PNG (via sips/convert)
 *   public/icons/icon-512.png       — 512px PNG (via sips/convert)
 *   electron/icons/icon.svg         — 1024x1024 master SVG
 *   electron/icons/icon-1024.png    — 1024px PNG for electron-builder
 *   electron/icons/tray-icon.png    — 22px colour PNG
 *   electron/icons/tray-iconTemplate.png   — 22px monochrome (macOS menu bar)
 *   electron/icons/tray-iconTemplate@2x.png — 44px monochrome @2x
 *
 * PNG conversion uses macOS `sips` or ImageMagick `convert` if available.
 * If neither is installed the script still generates SVGs and reports
 * which PNGs it could not create.
 *
 * Usage:  node scripts/generate-icons.mjs
 */

import { writeFile, mkdir } from 'fs/promises';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { execSync } from 'child_process';
import { existsSync } from 'fs';

const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = join(__dirname, '..');
const ELECTRON_ICONS = join(ROOT, 'electron', 'icons');
const PUBLIC_ICONS = join(ROOT, 'public', 'icons');

const BRAND_COLOR = '#6366f1';

// ---------------------------------------------------------------------------
// SVG generators
// ---------------------------------------------------------------------------

function brandSVG(size) {
  const cx = size / 2;
  const cy = size / 2;
  const fontSize = size * 0.22;
  const textY = cy + fontSize * 0.37;
  return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">
  <defs>
    <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
      <stop offset="0%" stop-color="#818cf8"/>
      <stop offset="100%" stop-color="#4f46e5"/>
    </linearGradient>
  </defs>
  <rect x="${size * 0.06}" y="${size * 0.06}" width="${size * 0.88}" height="${size * 0.88}" rx="${size * 0.22}" fill="url(#bg)"/>
  <text x="${cx}" y="${textY}" font-size="${fontSize}" text-anchor="middle" fill="white" font-family="system-ui, -apple-system, 'Segoe UI', sans-serif" font-weight="700" letter-spacing="${size * -0.005}">AI-Do</text>
</svg>`;
}

/** macOS menu-bar template images must be black-on-transparent. */
function templateSVG(size) {
  const cx = size / 2;
  const cy = size / 2;
  const fontSize = size * 0.22;
  const textY = cy + fontSize * 0.37;
  return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">
  <rect x="${size * 0.06}" y="${size * 0.06}" width="${size * 0.88}" height="${size * 0.88}" rx="${size * 0.22}" fill="black"/>
  <text x="${cx}" y="${textY}" font-size="${fontSize}" text-anchor="middle" fill="white" font-family="system-ui, -apple-system, 'Segoe UI', sans-serif" font-weight="700" letter-spacing="${size * -0.005}">AI-Do</text>
</svg>`;
}

// ---------------------------------------------------------------------------
// SVG → PNG conversion helpers
// ---------------------------------------------------------------------------

function hasSips() {
  try { execSync('which sips', { stdio: 'ignore' }); return true; } catch { return false; }
}

function hasConvert() {
  try { execSync('which convert', { stdio: 'ignore' }); return true; } catch { return false; }
}

function hasRsvgConvert() {
  try { execSync('which rsvg-convert', { stdio: 'ignore' }); return true; } catch { return false; }
}

/**
 * Convert an SVG file to PNG at the given pixel size.
 * Tries rsvg-convert (best quality), then sips (macOS), then ImageMagick convert.
 * Returns true on success.
 */
function svgToPng(svgPath, pngPath, size) {
  if (hasRsvgConvert()) {
    try {
      execSync(`rsvg-convert -w ${size} -h ${size} "${svgPath}" -o "${pngPath}"`, { stdio: 'ignore' });
      return true;
    } catch { /* fall through */ }
  }

  // sips can't read SVG directly, but we can try via a temporary approach
  // Actually sips on macOS can convert SVG in some versions
  if (hasSips()) {
    try {
      // sips approach: copy SVG, convert. sips can handle SVG on newer macOS
      execSync(`sips -s format png -z ${size} ${size} "${svgPath}" --out "${pngPath}" 2>/dev/null`, { stdio: 'ignore' });
      if (existsSync(pngPath)) return true;
    } catch { /* fall through */ }
  }

  if (hasConvert()) {
    try {
      execSync(`convert -background none -density 300 -resize ${size}x${size} "${svgPath}" "${pngPath}"`, { stdio: 'ignore' });
      return true;
    } catch { /* fall through */ }
  }

  return false;
}

// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------

async function main() {
  await mkdir(ELECTRON_ICONS, { recursive: true });
  await mkdir(PUBLIC_ICONS, { recursive: true });

  console.log('[icons] Generating SVG icons...');

  // Web favicon
  const faviconSvg = brandSVG(32);
  await writeFile(join(PUBLIC_ICONS, 'favicon.svg'), faviconSvg);
  console.log('[icons]   public/icons/favicon.svg');

  // Master SVG for Electron / app stores
  const masterSvg = brandSVG(1024);
  await writeFile(join(ELECTRON_ICONS, 'icon.svg'), masterSvg);
  console.log('[icons]   electron/icons/icon.svg');

  // Tray colour SVG (used as fallback source)
  const traySvg = brandSVG(44);
  const traySvgPath = join(ELECTRON_ICONS, 'tray-icon.svg');
  await writeFile(traySvgPath, traySvg);

  // Tray template SVGs
  const template22Svg = templateSVG(22);
  const template44Svg = templateSVG(44);
  await writeFile(join(ELECTRON_ICONS, 'tray-iconTemplate.svg'), template22Svg);
  await writeFile(join(ELECTRON_ICONS, 'tray-iconTemplate@2x.svg'), template44Svg);

  // ---- PNG conversion ----
  console.log('[icons] Converting SVGs to PNG...');

  const conversions = [
    { svg: join(ELECTRON_ICONS, 'icon.svg'), png: join(ELECTRON_ICONS, 'icon-1024.png'), size: 1024 },
    { svg: join(ELECTRON_ICONS, 'icon.svg'), png: join(ELECTRON_ICONS, 'icon-512.png'), size: 512 },
    { svg: join(ELECTRON_ICONS, 'icon.svg'), png: join(ELECTRON_ICONS, 'icon-256.png'), size: 256 },
    { svg: join(ELECTRON_ICONS, 'icon.svg'), png: join(PUBLIC_ICONS, 'icon-192.png'), size: 192 },
    { svg: join(ELECTRON_ICONS, 'icon.svg'), png: join(PUBLIC_ICONS, 'icon-512.png'), size: 512 },
    { svg: traySvgPath, png: join(ELECTRON_ICONS, 'tray-icon.png'), size: 22 },
    { svg: join(ELECTRON_ICONS, 'tray-iconTemplate.svg'), png: join(ELECTRON_ICONS, 'tray-iconTemplate.png'), size: 22 },
    { svg: join(ELECTRON_ICONS, 'tray-iconTemplate@2x.svg'), png: join(ELECTRON_ICONS, 'tray-iconTemplate@2x.png'), size: 44 },
  ];

  let converted = 0;
  let skipped = 0;
  for (const { svg, png, size } of conversions) {
    if (svgToPng(svg, png, size)) {
      console.log(`[icons]   ${png.replace(ROOT + '/', '')} (${size}px)`);
      converted++;
    } else {
      console.log(`[icons]   SKIP ${png.replace(ROOT + '/', '')} — no converter available`);
      skipped++;
    }
  }

  // ---- macOS .icns generation (if iconutil is available) ----
  try {
    execSync('which iconutil', { stdio: 'ignore' });
    const iconsetDir = join(ELECTRON_ICONS, 'icon.iconset');
    await mkdir(iconsetDir, { recursive: true });

    const icnsSizes = [16, 32, 64, 128, 256, 512, 1024];
    const masterSvgPath = join(ELECTRON_ICONS, 'icon.svg');
    let icnsOk = true;

    for (const s of icnsSizes) {
      const name = s === 1024 ? 'icon_512x512@2x.png' : (
        s === 64 ? 'icon_32x32@2x.png' : (
          s <= 512 ? `icon_${s}x${s}.png` : `icon_${s}x${s}.png`
        )
      );
      // Standard iconset naming: icon_NxN.png and icon_NxN@2x.png
      const baseName = s <= 16 ? 'icon_16x16.png'
        : s <= 32 ? (s === 16 ? 'icon_16x16.png' : (s === 32 ? 'icon_32x32.png' : `icon_${s}x${s}.png`))
        : `icon_${s}x${s}.png`;

      if (!svgToPng(masterSvgPath, join(iconsetDir, baseName), s)) {
        icnsOk = false;
        break;
      }
    }

    // Generate @2x variants
    const retinaMap = { 16: '16x16@2x', 32: '32x32@2x', 128: '128x128@2x', 256: '256x256@2x', 512: '512x512@2x' };
    for (const [srcSize, label] of Object.entries(retinaMap)) {
      const targetSize = Number(srcSize) * 2;
      if (!svgToPng(masterSvgPath, join(iconsetDir, `icon_${label}.png`), targetSize)) {
        icnsOk = false;
        break;
      }
    }

    if (icnsOk) {
      try {
        execSync(`iconutil -c icns "${iconsetDir}" -o "${join(ELECTRON_ICONS, 'icon.icns')}"`, { stdio: 'ignore' });
        console.log('[icons]   electron/icons/icon.icns (macOS)');
      } catch (err) {
        console.log(`[icons]   SKIP icon.icns — iconutil failed: ${err.message}`);
      }
    }
    // Clean up iconset directory
    execSync(`rm -rf "${iconsetDir}"`, { stdio: 'ignore' });
  } catch {
    console.log('[icons]   SKIP icon.icns — iconutil not available (not on macOS)');
  }

  console.log(`[icons] Done! ${converted} PNGs generated, ${skipped} skipped.`);

  if (skipped > 0) {
    console.log('[icons]');
    console.log('[icons] To generate PNGs, install one of:');
    console.log('[icons]   brew install librsvg    (rsvg-convert — best quality)');
    console.log('[icons]   brew install imagemagick (convert)');
  }
}

main().catch(err => {
  console.error('[icons] Error:', err);
  process.exit(1);
});
