"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.installDependencies = installDependencies;
const child_process_1 = require("child_process");
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const chalk_1 = __importDefault(require("chalk"));
const inquirer_1 = __importDefault(require("inquirer"));
async function installDependencies(dependencies, cwd, options = {}) {
    if (dependencies.length === 0)
        return;
    const packageJsonPath = path_1.default.join(cwd, 'package.json');
    // Check if package.json exists
    if (!await fs_extra_1.default.pathExists(packageJsonPath)) {
        console.warn(chalk_1.default.yellow('⚠️  Warning: package.json not found in the target directory.'));
        console.log(chalk_1.default.gray('Please make sure you are in a valid Node.js project directory.'));
        return;
    }
    // Read and check existing dependencies
    const packageJson = await fs_extra_1.default.readJson(packageJsonPath);
    const existingDeps = {
        ...packageJson.dependencies,
        ...packageJson.devDependencies,
        ...packageJson.peerDependencies
    };
    const missingDeps = [];
    const existingDepsFound = [];
    dependencies.forEach(dep => {
        if (!existingDeps[dep]) {
            missingDeps.push(dep);
        }
        else {
            existingDepsFound.push(dep);
        }
    });
    // Show status of dependencies
    if (existingDepsFound.length > 0) {
        console.log(chalk_1.default.green('✓ Found existing dependencies:'));
        existingDepsFound.forEach(dep => console.log(chalk_1.default.gray(`  • ${dep}`)));
    }
    if (missingDeps.length > 0) {
        console.log(chalk_1.default.yellow('⚠️  Missing dependencies:'));
        missingDeps.forEach(dep => console.log(chalk_1.default.gray(`  • ${dep}`)));
        // Add to package.json if requested
        if (options.addToPackageJson !== false) {
            const { shouldAddToPackageJson } = await inquirer_1.default.prompt([
                {
                    type: 'confirm',
                    name: 'shouldAddToPackageJson',
                    message: 'Would you like to add missing dependencies to package.json?',
                    default: true
                }
            ]);
            if (shouldAddToPackageJson) {
                await addDependenciesToPackageJson(missingDeps, packageJsonPath);
                console.log(chalk_1.default.green('✓ Dependencies added to package.json'));
            }
        }
        // Install dependencies if not skipped
        if (!options.skipInstall) {
            const { shouldInstall } = await inquirer_1.default.prompt([
                {
                    type: 'confirm',
                    name: 'shouldInstall',
                    message: 'Would you like to install the missing dependencies now?',
                    default: true
                }
            ]);
            if (shouldInstall) {
                await installMissingDependencies(missingDeps, cwd);
            }
            else {
                console.log(chalk_1.default.yellow('⚠️  Please install the dependencies manually:'));
                const packageManager = await detectPackageManager(cwd);
                const installCommand = getInstallCommand(packageManager, missingDeps);
                console.log(chalk_1.default.gray(`  ${installCommand}`));
            }
        }
    }
}
async function addDependenciesToPackageJson(dependencies, packageJsonPath) {
    try {
        const packageJson = await fs_extra_1.default.readJson(packageJsonPath);
        // Initialize dependencies object if it doesn't exist
        if (!packageJson.dependencies) {
            packageJson.dependencies = {};
        }
        // Add dependencies with latest version
        dependencies.forEach(dep => {
            packageJson.dependencies[dep] = 'latest';
        });
        // Write back to package.json with proper formatting
        await fs_extra_1.default.writeJson(packageJsonPath, packageJson, { spaces: 2 });
    }
    catch (error) {
        console.error(chalk_1.default.red('Failed to update package.json:'), error);
    }
}
async function installMissingDependencies(dependencies, cwd) {
    const packageManager = await detectPackageManager(cwd);
    try {
        const installCommand = getInstallCommand(packageManager, dependencies);
        console.log(chalk_1.default.blue(`Installing dependencies with ${packageManager}...`));
        (0, child_process_1.execSync)(installCommand, {
            cwd,
            stdio: 'inherit',
            env: { ...process.env, NODE_ENV: 'development' }
        });
        console.log(chalk_1.default.green('✓ Dependencies installed successfully'));
    }
    catch (error) {
        console.error(chalk_1.default.red('Failed to install dependencies:'), error);
        console.log(chalk_1.default.yellow('Please install manually:'));
        dependencies.forEach(dep => console.log(chalk_1.default.gray(`  ${packageManager} ${packageManager === 'npm' ? 'install' : 'add'} ${dep}`)));
    }
}
async function detectPackageManager(cwd) {
    // Check for lock files
    if (await fs_extra_1.default.pathExists(path_1.default.join(cwd, 'pnpm-lock.yaml'))) {
        return 'pnpm';
    }
    if (await fs_extra_1.default.pathExists(path_1.default.join(cwd, 'yarn.lock'))) {
        return 'yarn';
    }
    if (await fs_extra_1.default.pathExists(path_1.default.join(cwd, 'package-lock.json'))) {
        return 'npm';
    }
    // Default to npm
    return 'npm';
}
function getInstallCommand(packageManager, dependencies) {
    const deps = dependencies.join(' ');
    switch (packageManager) {
        case 'yarn':
            return `yarn add ${deps}`;
        case 'pnpm':
            return `pnpm add ${deps}`;
        case 'npm':
        default:
            return `npm install ${deps}`;
    }
}
//# sourceMappingURL=dependencies.js.map