import { execSync } from 'child_process';
import { logger } from './logger.js';
import { FileUtils } from './file.js';
/**
 * 包管理工具
 */
export class PackageUtils {
    /**
     * 安装依赖
     */
    static async install(dir, packageManager = 'pnpm') {
        try {
            logger.info(`Installing dependencies with ${packageManager}...`);
            const command = packageManager === 'pnpm' ? 'pnpm install' :
                packageManager === 'yarn' ? 'yarn install' :
                    'npm install';
            execSync(command, { cwd: dir, stdio: 'inherit' });
            logger.success('Dependencies installed successfully');
        }
        catch (error) {
            logger.error(`Failed to install dependencies with ${packageManager}`);
            throw error;
        }
    }
    /**
     * 添加依赖
     */
    static async add(dir, packages, options) {
        try {
            const { dev = false, packageManager = 'pnpm' } = options || {};
            const flag = dev ? '-D' : '';
            const command = packageManager === 'pnpm' ? `pnpm add ${flag} ${packages.join(' ')}` :
                packageManager === 'yarn' ? `yarn add ${dev ? '--dev' : ''} ${packages.join(' ')}` :
                    `npm install ${dev ? '--save-dev' : '--save'} ${packages.join(' ')}`;
            logger.info(`Adding packages: ${packages.join(', ')}`);
            execSync(command, { cwd: dir, stdio: 'inherit' });
            logger.success('Packages added successfully');
        }
        catch (error) {
            logger.error('Failed to add packages');
            throw error;
        }
    }
    /**
     * 更新 package.json
     */
    static async updatePackageJson(dir, updates) {
        try {
            const packageJsonPath = `${dir}/package.json`;
            const packageJson = await FileUtils.readJson(packageJsonPath);
            const updatedPackageJson = { ...packageJson, ...updates };
            await FileUtils.writeJson(packageJsonPath, updatedPackageJson);
            logger.success('package.json updated successfully');
        }
        catch (error) {
            logger.error('Failed to update package.json');
            throw error;
        }
    }
    /**
     * 获取包管理器
     */
    static getPackageManager() {
        try {
            execSync('pnpm --version', { stdio: 'pipe' });
            return 'pnpm';
        }
        catch {
            try {
                execSync('yarn --version', { stdio: 'pipe' });
                return 'yarn';
            }
            catch {
                return 'npm';
            }
        }
    }
    /**
     * 检查包管理器是否可用
     */
    static isPackageManagerAvailable(packageManager) {
        try {
            execSync(`${packageManager} --version`, { stdio: 'pipe' });
            return true;
        }
        catch {
            return false;
        }
    }
}
//# sourceMappingURL=package.js.map