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

/**
 * afterPack hook - 在打包后复制 TSS 二进制文件到正确位置
 *
 * 由于 electron-builder 的 extraResources 的 ${platform}/${arch} 宏
 * 在 from 路径中可能不稳定，使用 afterPack hook 确保可靠复制
 *
 * 参考: https://github.com/electron-userland/electron-builder/issues/7891
 */
exports.default = async function afterPack(context) {
  const { appOutDir, packager } = context;
  const platform = packager.platform.name; // 'mac', 'linux', 'windows'
  const arch = context.arch; // 1 = x64, 3 = arm64, etc.

  // 映射 arch 数字到字符串
  const archMap = {
    1: 'x64',
    3: 'arm64',
    0: 'ia32',
  };
  const archStr = archMap[arch] || 'x64';

  // 映射 platform 到 Node.js process.platform 风格
  const platformMap = {
    'windows': 'win32',
    'mac': 'darwin',
    'linux': 'linux',
  };
  const platformStr = platformMap[platform] || platform;

  console.log(`[afterPack] Platform: ${platform} (${platformStr}), Arch: ${arch} (${archStr})`);

  // 源目录和目标目录
  const sourceDir = path.join(__dirname, '..', 'bin', `${platformStr}-${archStr}`);
  const targetDir = path.join(appOutDir, 'resources', 'bin');

  console.log(`[afterPack] Source: ${sourceDir}`);
  console.log(`[afterPack] Target: ${targetDir}`);

  // 检查源目录是否存在
  if (!fs.existsSync(sourceDir)) {
    console.warn(`[afterPack] Source directory not found: ${sourceDir}`);
    console.warn(`[afterPack] Skipping binary copy for ${platformStr}-${archStr}`);
    return;
  }

  // 创建目标目录
  if (!fs.existsSync(targetDir)) {
    fs.mkdirSync(targetDir, { recursive: true });
    console.log(`[afterPack] Created target directory: ${targetDir}`);
  }

  // 复制所有文件
  const files = fs.readdirSync(sourceDir);
  for (const file of files) {
    const sourcePath = path.join(sourceDir, file);
    const targetPath = path.join(targetDir, file);

    // 获取文件信息
    const stat = fs.statSync(sourcePath);
    if (stat.isFile()) {
      fs.copyFileSync(sourcePath, targetPath);
      console.log(`[afterPack] Copied: ${file} (${(stat.size / 1024 / 1024).toFixed(2)} MB)`);

      // 在 Unix 系统上设置可执行权限
      if (platformStr !== 'win32') {
        fs.chmodSync(targetPath, 0o755);
      }
    }
  }

  console.log(`[afterPack] Binary copy completed for ${platformStr}-${archStr}`);
};
