import fs from 'fs';
import path from 'path';
import { execSync } from 'child_process';

// 工程目录路径
const projectDir = '/Users/hongkai/Documents/work/bolian/web/projects';

// 获取命令行参数
const args = process.argv.slice(2);
const targetProject = args[0];

// 读取工程目录下的所有子目录
const directories = fs.readdirSync(projectDir).filter(file => {
    const filePath = path.join(projectDir, file);
    return fs.statSync(filePath).isDirectory();
});

directories.forEach(directory => {
    // 如果指定了目标项目且当前目录不是目标项目，则跳过
    if (targetProject && directory !== targetProject) {
        console.log(`Skipping project ${directory} as it's not the target project...`);
        return;
    }

    if (directory === 'base') {
        console.log(`Skipping base project...`);
        return;
    }

    const packageJsonPath = path.join(projectDir, directory, 'package.json');
    if (fs.existsSync(packageJsonPath)) {
        console.log(`Building project in ${directory}...`);
        try {
            // 添加调试信息
            console.log(`Executing: pnpm run build in ${directory}`);
            execSync('pnpm run build', { cwd: path.join(projectDir, directory), stdio: 'inherit' });
        } catch (error) {
            console.error(`Failed to build project in ${directory}:`, error.message);
        }
    } else {
        console.log(`No package.json found in ${directory}, skipping...`);
    }
});