/**
 * 图标生成脚本
 * 从 SVG 生成各种尺寸的 PNG 图标
 * 
 * 使用方法：
 *   cd client
 *   npm install sharp --save-dev
 *   node scripts/generate-icons.js
 */

const fs = require('fs');
const path = require('path');

// 检查是否安装了 sharp
let sharp;
try {
  sharp = require('sharp');
} catch (e) {
  console.error('请先安装 sharp: npm install sharp --save-dev');
  process.exit(1);
}

const SVG_PATH = path.join(__dirname, '../public/favicon.svg');
const OUTPUT_DIR = path.join(__dirname, '../public/icons');
const BUILD_DIR = path.join(__dirname, '../build');

// 需要生成的图标尺寸
const ICON_SIZES = {
  // 应用图标
  'icon-16.png': 16,
  'icon-24.png': 24,
  'icon-32.png': 32,
  'icon-48.png': 48,
  'icon-64.png': 64,
  'icon-128.png': 128,
  'icon-256.png': 256,
  'icon-512.png': 512,
  
  // 托盘图标 (Windows 需要 16x16 或 32x32)
  'tray-icon.png': 32,
  'tray-icon@2x.png': 64,
  
  // README logo
  'logo.png': 128,
};

async function generateIcons() {
  // 确保输出目录存在
  if (!fs.existsSync(OUTPUT_DIR)) {
    fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  }
  if (!fs.existsSync(BUILD_DIR)) {
    fs.mkdirSync(BUILD_DIR, { recursive: true });
  }

  // 读取 SVG 文件
  const svgBuffer = fs.readFileSync(SVG_PATH);

  console.log('开始生成图标...\n');

  // 生成各尺寸 PNG
  for (const [filename, size] of Object.entries(ICON_SIZES)) {
    const outputPath = path.join(OUTPUT_DIR, filename);
    
    await sharp(svgBuffer)
      .resize(size, size)
      .png()
      .toFile(outputPath);
    
    console.log(`✓ ${filename} (${size}x${size})`);
  }

  // 复制主图标到 build 目录
  const icon256Path = path.join(OUTPUT_DIR, 'icon-256.png');
  const buildIconPath = path.join(BUILD_DIR, 'icon.png');
  fs.copyFileSync(icon256Path, buildIconPath);
  console.log(`\n✓ 复制 icon.png 到 build 目录`);

  // 复制 logo 到根目录用于 README
  const logoPath = path.join(OUTPUT_DIR, 'logo.png');
  const readmeLogoPath = path.join(__dirname, '../../docs/logo.png');
  const docsDir = path.join(__dirname, '../../docs');
  if (!fs.existsSync(docsDir)) {
    fs.mkdirSync(docsDir, { recursive: true });
  }
  fs.copyFileSync(logoPath, readmeLogoPath);
  console.log(`✓ 复制 logo.png 到 docs 目录`);

  console.log('\n图标生成完成！');
  console.log('\n生成的文件：');
  console.log(`  - client/public/icons/ (应用图标)`);
  console.log(`  - client/build/icon.png (打包用图标)`);
  console.log(`  - docs/logo.png (README logo)`);
  
  console.log('\n下一步：');
  console.log('  1. 使用在线工具将 icon-256.png 转换为 icon.ico (Windows)');
  console.log('     推荐: https://convertio.co/png-ico/');
  console.log('  2. 将生成的 icon.ico 放到 client/build/ 目录');
}

generateIcons().catch(console.error);
