const fs = require('fs');
const fsp = fs.promises;
const path = require('path');

const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);

/**
 * 使用系统命令创建ZIP（跨平台）
 * @param {string} sourceDir - 要压缩的目录路径
 * @param {string} outputDir - 压缩文件输出目录
 * @returns {Promise<string>} - 压缩文件的路径
 */
async function createZipWithSystemCommand(sourceDir, outputDir) {
    // 检查源目录
    if (!fs.existsSync(sourceDir)) {
        throw new Error(`源目录不存在: ${sourceDir}`);
    }

    // 生成文件名
    const dateString = new Date().toISOString().split('T')[0];
    const zipFileName = `mp-weixin-${dateString}-${new Date().getTime()}.zip`;
    const zipFilePath = path.join(outputDir, zipFileName);

    let command;
    
    // 根据操作系统选择命令
    if (process.platform === 'win32') {
        // Windows: 使用PowerShell的Compress-Archive
        const sourcePath = sourceDir.replace(/'/g, "''");
        const destPath = zipFilePath.replace(/'/g, "''");
        command = `powershell -Command "Compress-Archive -Path '${sourcePath}\\*' -DestinationPath '${destPath}' -Force"`;
    } else {
        // Linux/Mac: 使用zip命令
        const sourceBase = path.dirname(sourceDir);
        const sourceName = path.basename(sourceDir);
        command = `cd '${sourceBase}' && zip -r '${zipFilePath}' '${sourceName}' -x '*/node_modules/*' '*.git/*' '*.DS_Store' '*.log'`;
    }

    try {
        console.log(`执行命令: ${command}`);
        const { stdout, stderr } = await execAsync(command);
        
        if (stderr) {
            console.warn('警告:', stderr);
        }
        
        console.log(`✅ ZIP文件创建完成: ${zipFileName}`);
        return zipFilePath;
    } catch (error) {
        throw new Error(`系统命令执行失败: ${error.message}`);
    }
}

module.exports = {
    createZipWithSystemCommand
}