import { promises as fs } from 'fs';
import { join, dirname } from 'path';
import { exec } from 'child_process';
import { promisify } from 'util';
const execAsync = promisify(exec);
export async function executeRecommendation(recommendation, projectPath) {
    try {
        // Execute command if present
        if (recommendation.command) {
            const { stdout, stderr } = await execAsync(recommendation.command, {
                cwd: projectPath
            });
            if (stderr && !stdout) {
                throw new Error(stderr);
            }
        }
        // Create files if specified
        if (recommendation.files) {
            for (const file of recommendation.files) {
                const filePath = join(projectPath, file.path);
                const dir = dirname(filePath);
                // Ensure directory exists
                await fs.mkdir(dir, { recursive: true });
                // Write file
                await fs.writeFile(filePath, file.content, 'utf-8');
            }
        }
        // Update package.json if dependencies or scripts specified
        if (recommendation.dependencies || recommendation.devDependencies || recommendation.scripts) {
            await updatePackageJson(projectPath, recommendation.dependencies, recommendation.devDependencies, recommendation.scripts);
        }
        return {
            recommendationId: recommendation.id,
            success: true,
            message: `Successfully executed: ${recommendation.title}`
        };
    }
    catch (error) {
        return {
            recommendationId: recommendation.id,
            success: false,
            message: `Failed to execute: ${recommendation.title}`,
            error: error instanceof Error ? error.message : String(error)
        };
    }
}
async function updatePackageJson(projectPath, dependencies, devDependencies, scripts) {
    const packageJsonPath = join(projectPath, 'package.json');
    let packageJson = {};
    try {
        const content = await fs.readFile(packageJsonPath, 'utf-8');
        packageJson = JSON.parse(content);
    }
    catch {
        // Package.json doesn't exist, create a basic one
        packageJson = {
            name: 'project',
            version: '1.0.0',
            description: '',
            main: 'index.js',
            scripts: {},
            dependencies: {},
            devDependencies: {}
        };
    }
    // Update scripts
    if (scripts) {
        packageJson.scripts = {
            ...packageJson.scripts,
            ...scripts
        };
    }
    // Save updated package.json
    await fs.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf-8');
    // Install dependencies
    if (dependencies && dependencies.length > 0) {
        await execAsync(`npm install ${dependencies.join(' ')}`, {
            cwd: projectPath
        });
    }
    // Install dev dependencies
    if (devDependencies && devDependencies.length > 0) {
        await execAsync(`npm install --save-dev ${devDependencies.join(' ')}`, {
            cwd: projectPath
        });
    }
}
export async function executeMultipleRecommendations(recommendations, projectPath, onProgress) {
    const results = [];
    for (const recommendation of recommendations) {
        const result = await executeRecommendation(recommendation, projectPath);
        results.push(result);
        if (onProgress) {
            onProgress(result);
        }
        // Stop on failure for high priority items
        if (!result.success && recommendation.priority === 'high') {
            break;
        }
    }
    return results;
}
export function createBootstrapPlan(recommendations) {
    // Sort by priority
    const sorted = [...recommendations].sort((a, b) => {
        const priorityOrder = { high: 0, medium: 1, low: 2 };
        return priorityOrder[a.priority] - priorityOrder[b.priority];
    });
    // Estimate time
    const timeEstimates = {
        high: 5,
        medium: 3,
        low: 2
    };
    const totalMinutes = sorted.reduce((sum, rec) => sum + timeEstimates[rec.priority], 0);
    // Check if user input required
    const requiresInput = sorted.some(rec => rec.id === 'create-license' || rec.id === 'create-readme');
    return {
        recommendations: sorted,
        estimatedTime: `${totalMinutes} minutes`,
        requiresUserInput: requiresInput
    };
}
//# sourceMappingURL=bootstrapper.js.map