import { SecurityManager } from '../../utils/security-manager.js';
// Mock workflow recipes implementation
class WorkflowRecipes {
    async getAllRecipes() {
        return [
            {
                name: 'tdd_feature_implementation',
                description: 'Test-driven development workflow for implementing new features',
                category: 'development',
                riskLevel: 'medium',
                steps: [
                    { name: 'Write tests', description: 'Create test cases first' },
                    { name: 'Implement code', description: 'Write minimal code to pass tests' },
                    { name: 'Refactor', description: 'Improve code quality while keeping tests green' }
                ],
                prerequisites: ['Test framework setup', 'Clear requirements']
            },
            {
                name: 'security_review',
                description: 'Comprehensive security review process',
                category: 'security',
                riskLevel: 'high',
                steps: [
                    { name: 'Code scan', description: 'Automated security scanning' },
                    { name: 'Manual review', description: 'Human security expert review' },
                    { name: 'Fix issues', description: 'Address identified vulnerabilities' }
                ],
                prerequisites: ['Security scanning tools', 'Security expertise']
            }
        ];
    }
    async getRecipe(name) {
        const recipes = await this.getAllRecipes();
        return recipes.find(r => r.name === name);
    }
    async executeWorkflow(name, options) {
        return {
            workflowName: name,
            status: options.dryRun ? 'validated' : 'completed',
            currentStep: options.dryRun ? 0 : 3,
            totalSteps: 3,
            results: options.dryRun ? [] : [
                { stepName: 'Step 1', success: true, output: 'Completed successfully' },
                { stepName: 'Step 2', success: true, output: 'Completed successfully' },
                { stepName: 'Step 3', success: true, output: 'Completed successfully' }
            ],
            allValidationsPassed: true,
            readyForExecution: true
        };
    }
    async saveRecipe(recipe) {
        // Mock implementation - in real version would save to .atlas/workflows/
        console.log('Workflow recipe saved:', recipe.name);
    }
    async validateStep(workflowName, options) {
        return {
            stepName: options.stepName || `Step ${options.stepIndex + 1}`,
            valid: true,
            issues: [],
            warnings: [],
            recommendations: ['Consider adding error handling']
        };
    }
}
const workflowRecipes = new WorkflowRecipes();
const securityManager = SecurityManager.getInstance();
export async function setupWorkflowRecipes(server) {
    return {
        tools: [
            {
                name: 'list_workflow_recipes',
                description: 'List all available workflow recipes with descriptions and categories. Use this to discover proven workflows for common development tasks.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        category: {
                            type: 'string',
                            enum: ['development', 'planning', 'security', 'quality', 'deployment', 'all'],
                            default: 'all',
                            description: 'Filter workflows by category'
                        },
                        includeDetails: {
                            type: 'boolean',
                            default: false,
                            description: 'Include detailed workflow steps and prerequisites'
                        }
                    },
                    required: [],
                    additionalProperties: false
                }
            },
            {
                name: 'get_workflow_recipe',
                description: 'Get detailed information about a specific workflow recipe including steps, prerequisites, and validation criteria.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        workflowName: {
                            type: 'string',
                            description: 'Name of the workflow recipe to retrieve',
                            minLength: 1
                        },
                        format: {
                            type: 'string',
                            enum: ['detailed', 'checklist', 'summary'],
                            default: 'detailed',
                            description: 'Format for workflow information'
                        }
                    },
                    required: ['workflowName'],
                    additionalProperties: false
                }
            },
            {
                name: 'execute_workflow_recipe',
                description: 'Execute a workflow recipe with step-by-step guidance and validation. Use this to follow proven processes for complex tasks.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        workflowName: {
                            type: 'string',
                            description: 'Name of the workflow recipe to execute',
                            minLength: 1
                        },
                        parameters: {
                            type: 'object',
                            description: 'Parameters specific to the workflow execution'
                        },
                        dryRun: {
                            type: 'boolean',
                            default: false,
                            description: 'Execute in dry-run mode (validation only, no actual changes)'
                        },
                        autoExecute: {
                            type: 'boolean',
                            default: false,
                            description: 'Automatically execute all validated steps without manual confirmation'
                        }
                    },
                    required: ['workflowName'],
                    additionalProperties: false
                }
            },
            {
                name: 'create_workflow_recipe',
                description: 'Create a new custom workflow recipe with steps, validation, and rollback procedures. Use this to codify your team\'s processes.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        name: {
                            type: 'string',
                            description: 'Unique name for the workflow recipe',
                            minLength: 1
                        },
                        description: {
                            type: 'string',
                            description: 'Clear description of what this workflow accomplishes',
                            minLength: 1
                        },
                        category: {
                            type: 'string',
                            enum: ['development', 'planning', 'security', 'quality', 'deployment', 'custom'],
                            description: 'Category for organizing the workflow'
                        },
                        steps: {
                            type: 'array',
                            items: {
                                type: 'object',
                                properties: {
                                    name: { type: 'string' },
                                    description: { type: 'string' },
                                    command: { type: 'string' },
                                    validation: { type: 'string' },
                                    rollback: { type: 'string' }
                                },
                                required: ['name', 'description']
                            },
                            minItems: 1,
                            description: 'Array of workflow steps'
                        },
                        prerequisites: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Prerequisites that must be met before executing'
                        },
                        riskLevel: {
                            type: 'string',
                            enum: ['low', 'medium', 'high'],
                            default: 'medium',
                            description: 'Risk level for security assessment'
                        }
                    },
                    required: ['name', 'description', 'category', 'steps'],
                    additionalProperties: false
                }
            },
            {
                name: 'validate_workflow_step',
                description: 'Validate a specific step within a workflow execution. Use this to ensure prerequisites are met before proceeding.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        workflowName: {
                            type: 'string',
                            description: 'Name of the workflow being executed',
                            minLength: 1
                        },
                        stepIndex: {
                            type: 'number',
                            minimum: 0,
                            description: 'Index of the step to validate (0-based)'
                        },
                        stepName: {
                            type: 'string',
                            description: 'Name of the step to validate (alternative to stepIndex)'
                        },
                        context: {
                            type: 'object',
                            description: 'Execution context and parameters for validation'
                        }
                    },
                    required: ['workflowName'],
                    additionalProperties: false
                }
            }
        ],
        resources: []
    };
}
export async function handleWorkflowRecipeTool(name, args) {
    // For now, allow all workflow recipe access
    // TODO: Implement proper security validation
    try {
        switch (name) {
            case 'list_workflow_recipes': {
                const { category = 'all', includeDetails = false } = args;
                const recipes = await workflowRecipes.getAllRecipes();
                const filteredRecipes = category === 'all'
                    ? recipes
                    : recipes.filter((recipe) => recipe.category === category);
                return {
                    content: [{
                            type: 'text',
                            text: formatWorkflowList(filteredRecipes, includeDetails, category)
                        }],
                    structured: {
                        type: 'workflow_recipes_list',
                        category,
                        count: filteredRecipes.length,
                        recipes: includeDetails ? filteredRecipes : filteredRecipes.map((r) => ({
                            name: r.name,
                            description: r.description,
                            category: r.category,
                            riskLevel: r.riskLevel
                        })),
                        generatedAt: new Date().toISOString()
                    }
                };
            }
            case 'get_workflow_recipe': {
                const { workflowName, format = 'detailed' } = args;
                const recipe = await workflowRecipes.getRecipe(workflowName);
                if (!recipe) {
                    throw new Error(`Workflow recipe '${workflowName}' not found`);
                }
                return {
                    content: [{
                            type: 'text',
                            text: formatWorkflowRecipe(recipe, format)
                        }],
                    structured: {
                        type: 'workflow_recipe_details',
                        workflowName,
                        format,
                        recipe,
                        generatedAt: new Date().toISOString()
                    }
                };
            }
            case 'execute_workflow_recipe': {
                const { workflowName, parameters = {}, dryRun = false, autoExecute = false } = args;
                // Get recipe and check if it exists
                const recipe = await workflowRecipes.getRecipe(workflowName);
                if (!recipe) {
                    throw new Error(`Workflow recipe '${workflowName}' not found`);
                }
                // For high-risk workflows, show a warning but proceed
                if (recipe.riskLevel === 'high') {
                    console.warn(`Executing high-risk workflow: ${workflowName}`);
                }
                const execution = await workflowRecipes.executeWorkflow(workflowName, {
                    parameters,
                    dryRun,
                    autoExecute
                });
                return {
                    content: [{
                            type: 'text',
                            text: formatWorkflowExecution(execution, dryRun)
                        }],
                    structured: {
                        type: 'workflow_execution_result',
                        workflowName,
                        dryRun,
                        autoExecute,
                        execution,
                        generatedAt: new Date().toISOString()
                    }
                };
            }
            case 'create_workflow_recipe': {
                const { name, description, category, steps, prerequisites = [], riskLevel = 'medium' } = args;
                // Basic validation for creating workflows
                if (riskLevel === 'high') {
                    console.warn(`Creating high-risk workflow: ${name}`);
                }
                const recipe = {
                    name,
                    description,
                    category,
                    steps,
                    prerequisites,
                    riskLevel,
                    createdAt: new Date().toISOString(),
                    createdBy: 'user'
                };
                await workflowRecipes.saveRecipe(recipe);
                return {
                    content: [{
                            type: 'text',
                            text: formatWorkflowCreated(recipe)
                        }],
                    structured: {
                        type: 'workflow_recipe_created',
                        recipe,
                        createdAt: new Date().toISOString()
                    }
                };
            }
            case 'validate_workflow_step': {
                const { workflowName, stepIndex, stepName, context = {} } = args;
                const validation = await workflowRecipes.validateStep(workflowName, {
                    stepIndex,
                    stepName,
                    context
                });
                return {
                    content: [{
                            type: 'text',
                            text: formatStepValidation(validation)
                        }],
                    structured: {
                        type: 'workflow_step_validation',
                        workflowName,
                        stepIndex,
                        stepName,
                        validation,
                        validatedAt: new Date().toISOString()
                    }
                };
            }
            default:
                throw new Error(`Unknown workflow recipe tool: ${name}`);
        }
    }
    catch (error) {
        console.error(`Workflow recipe tool error (${name}):`, error);
        throw error;
    }
}
function formatWorkflowList(recipes, includeDetails, category) {
    if (recipes.length === 0) {
        return `# Workflow Recipes (${category})

No workflow recipes found${category !== 'all' ? ` in category '${category}'` : ''}.

💡 **Create your first workflow**:
Use the 'create_workflow_recipe' tool to codify your team's processes and ensure consistent execution.`;
    }
    let report = `# Workflow Recipes (${category})\n\n`;
    report += `Found **${recipes.length}** workflow recipes${category !== 'all' ? ` in category '${category}'` : ''}.\n\n`;
    const recipesByCategory = recipes.reduce((acc, recipe) => {
        acc[recipe.category] = acc[recipe.category] || [];
        acc[recipe.category].push(recipe);
        return acc;
    }, {});
    Object.entries(recipesByCategory).forEach(([cat, categoryRecipes]) => {
        report += `## ${cat.charAt(0).toUpperCase() + cat.slice(1)} Workflows\n\n`;
        categoryRecipes.forEach((recipe, index) => {
            const riskEmoji = recipe.riskLevel === 'high' ? '🔴' : recipe.riskLevel === 'medium' ? '🟡' : '🟢';
            report += `### ${index + 1}. ${recipe.name} ${riskEmoji}\n`;
            report += `**Description**: ${recipe.description}\n`;
            report += `**Risk Level**: ${recipe.riskLevel}\n`;
            if (includeDetails) {
                if (recipe.prerequisites?.length > 0) {
                    report += `**Prerequisites**: ${recipe.prerequisites.join(', ')}\n`;
                }
                if (recipe.steps?.length > 0) {
                    report += `**Steps** (${recipe.steps.length}):\n`;
                    recipe.steps.slice(0, 3).forEach((step, stepIndex) => {
                        report += `${stepIndex + 1}. ${step.name}\n`;
                    });
                    if (recipe.steps.length > 3) {
                        report += `... and ${recipe.steps.length - 3} more steps\n`;
                    }
                }
            }
            report += '\n';
        });
    });
    report += `## Quick Actions\n\n`;
    report += `- **View Recipe**: Use 'get_workflow_recipe' with the workflow name\n`;
    report += `- **Execute Recipe**: Use 'execute_workflow_recipe' to run a workflow\n`;
    report += `- **Create Custom**: Use 'create_workflow_recipe' to add your own\n`;
    return report;
}
function formatWorkflowRecipe(recipe, format) {
    const { name, description, category, steps, prerequisites, riskLevel } = recipe;
    const riskEmoji = riskLevel === 'high' ? '🔴' : riskLevel === 'medium' ? '🟡' : '🟢';
    if (format === 'summary') {
        return `# ${name} ${riskEmoji}

**Category**: ${category}  
**Risk Level**: ${riskLevel}  
**Steps**: ${steps?.length || 0}  

${description}

${prerequisites?.length > 0 ? `**Prerequisites**: ${prerequisites.join(', ')}` : ''}

Use 'execute_workflow_recipe' to run this workflow.`;
    }
    if (format === 'checklist') {
        let checklist = `# ${name} - Execution Checklist ${riskEmoji}\n\n`;
        checklist += `${description}\n\n`;
        if (prerequisites?.length > 0) {
            checklist += `## Prerequisites\n`;
            prerequisites.forEach((prereq, i) => {
                checklist += `- [ ] ${prereq}\n`;
            });
            checklist += '\n';
        }
        checklist += `## Workflow Steps\n`;
        steps?.forEach((step, i) => {
            checklist += `- [ ] **Step ${i + 1}**: ${step.name}\n`;
            checklist += `      ${step.description}\n`;
            if (step.command) {
                checklist += `      Command: \`${step.command}\`\n`;
            }
            if (step.validation) {
                checklist += `      Validation: ${step.validation}\n`;
            }
        });
        return checklist;
    }
    // Detailed format
    let detailed = `# ${name} ${riskEmoji}\n\n`;
    detailed += `**Category**: ${category}\n`;
    detailed += `**Risk Level**: ${riskLevel}\n`;
    detailed += `**Total Steps**: ${steps?.length || 0}\n\n`;
    detailed += `## Description\n${description}\n\n`;
    if (prerequisites?.length > 0) {
        detailed += `## Prerequisites\n`;
        prerequisites.forEach((prereq, i) => {
            detailed += `${i + 1}. ${prereq}\n`;
        });
        detailed += '\n';
    }
    if (steps?.length > 0) {
        detailed += `## Workflow Steps\n\n`;
        steps.forEach((step, i) => {
            detailed += `### Step ${i + 1}: ${step.name}\n`;
            detailed += `${step.description}\n\n`;
            if (step.command) {
                detailed += `**Command**:\n\`\`\`bash\n${step.command}\n\`\`\`\n\n`;
            }
            if (step.validation) {
                detailed += `**Validation**: ${step.validation}\n\n`;
            }
            if (step.rollback) {
                detailed += `**Rollback**: ${step.rollback}\n\n`;
            }
        });
    }
    detailed += `## Execution\n`;
    detailed += `Use the 'execute_workflow_recipe' tool with workflow name '${name}' to run this workflow.\n\n`;
    detailed += `**Dry Run**: Add \`"dryRun": true\` to validate without making changes.\n`;
    detailed += `**Auto Execute**: Add \`"autoExecute": true\` to run all steps automatically.\n`;
    return detailed;
}
function formatWorkflowExecution(execution, dryRun) {
    const { workflowName, status, currentStep, totalSteps, results, errors } = execution;
    const statusEmoji = status === 'completed' ? '✅' : status === 'failed' ? '❌' : status === 'running' ? '⏳' : '⚠️';
    let report = `# Workflow Execution Report ${statusEmoji}\n\n`;
    report += `**Workflow**: ${workflowName}\n`;
    report += `**Mode**: ${dryRun ? 'Dry Run (Validation Only)' : 'Live Execution'}\n`;
    report += `**Status**: ${status}\n`;
    report += `**Progress**: ${currentStep || 0}/${totalSteps || 0} steps\n\n`;
    if (status === 'completed') {
        report += `## ✅ Execution Completed Successfully\n\n`;
        if (results?.length > 0) {
            report += `### Results\n`;
            results.forEach((result, i) => {
                report += `**Step ${i + 1}**: ${result.stepName}\n`;
                report += `- Status: ${result.success ? '✅ Success' : '❌ Failed'}\n`;
                if (result.output)
                    report += `- Output: ${result.output}\n`;
                if (result.message)
                    report += `- Message: ${result.message}\n`;
                report += '\n';
            });
        }
    }
    else if (status === 'failed') {
        report += `## ❌ Execution Failed\n\n`;
        if (errors?.length > 0) {
            report += `### Errors\n`;
            errors.forEach((error, i) => {
                report += `**Error ${i + 1}**: ${error.step || 'Unknown Step'}\n`;
                report += `- Message: ${error.message}\n`;
                if (error.details)
                    report += `- Details: ${error.details}\n`;
                if (error.rollback)
                    report += `- Rollback: ${error.rollback}\n`;
                report += '\n';
            });
        }
    }
    else if (status === 'running') {
        report += `## ⏳ Execution In Progress\n\n`;
        report += `Currently executing step ${currentStep}: ${execution.currentStepName || 'Processing...'}\n\n`;
    }
    if (dryRun) {
        report += `## 🔍 Dry Run Summary\n`;
        report += `- All validations passed: ${execution.allValidationsPassed ? 'Yes' : 'No'}\n`;
        report += `- Ready for execution: ${execution.readyForExecution ? 'Yes' : 'No'}\n`;
        if (execution.validationWarnings?.length > 0) {
            report += `- Warnings: ${execution.validationWarnings.length}\n`;
        }
    }
    return report;
}
function formatWorkflowCreated(recipe) {
    return `# Workflow Recipe Created Successfully ✅

## Recipe Details
- **Name**: ${recipe.name}
- **Category**: ${recipe.category}
- **Risk Level**: ${recipe.riskLevel}
- **Steps**: ${recipe.steps.length}
- **Prerequisites**: ${recipe.prerequisites?.length || 0}

## Description
${recipe.description}

## Next Steps
1. **Test the workflow**: Use 'execute_workflow_recipe' with \`"dryRun": true\`
2. **Share with team**: Document the workflow in your team's process guide
3. **Iterate**: Refine the workflow based on actual usage

The workflow is now available for execution and will appear in workflow listings.`;
}
function formatStepValidation(validation) {
    const { stepName, valid, issues, warnings, recommendations } = validation;
    const statusEmoji = valid ? '✅' : '❌';
    let report = `# Step Validation Result ${statusEmoji}\n\n`;
    report += `**Step**: ${stepName}\n`;
    report += `**Valid**: ${valid ? 'Yes' : 'No'}\n\n`;
    if (!valid && issues?.length > 0) {
        report += `## ❌ Validation Issues\n`;
        issues.forEach((issue, i) => {
            report += `${i + 1}. ${issue}\n`;
        });
        report += '\n';
    }
    if (warnings?.length > 0) {
        report += `## ⚠️ Warnings\n`;
        warnings.forEach((warning, i) => {
            report += `${i + 1}. ${warning}\n`;
        });
        report += '\n';
    }
    if (recommendations?.length > 0) {
        report += `## 💡 Recommendations\n`;
        recommendations.forEach((rec, i) => {
            report += `${i + 1}. ${rec}\n`;
        });
        report += '\n';
    }
    if (valid) {
        report += `✅ **Step is ready for execution**\n`;
    }
    else {
        report += `❌ **Step validation failed** - Address the issues above before proceeding\n`;
    }
    return report;
}
//# sourceMappingURL=index.js.map