import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { DevelopmentDataStore } from './store.js';
import { TDDEnforcer } from './tdd-enforcer.js';
import { FeatureDiscoveryWizard } from './feature-discovery-wizard.js';
import { ConfigManager } from '../../config/config-manager.js';
let devStore;
let tddEnforcer;
let featureWizard;
let configManager;
export async function setupDevelopmentTools(server, config) {
    configManager = config || new ConfigManager();
    devStore = new DevelopmentDataStore(configManager);
    tddEnforcer = new TDDEnforcer();
    featureWizard = new FeatureDiscoveryWizard();
    await devStore.init();
    // Add development-specific tool handlers
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
        const { name, arguments: args } = request.params;
        if (!args) {
            throw new Error('No arguments provided');
        }
        switch (name) {
            case 'create_feature': {
                const { name: featureName, description } = args;
                const feature = devStore.createFeature(featureName, description);
                await devStore.save();
                return {
                    content: [
                        {
                            type: 'text',
                            text: `✅ Feature "${feature.name}" created\n\n⚠️  TDD Reminder: You must write tests before implementing!\nUse the "write_test" tool to create your first failing test.`,
                        },
                    ],
                    structured: {
                        feature: {
                            id: feature.id,
                            name: feature.name,
                            description: feature.description,
                            testCount: 0,
                            coverage: 0,
                        },
                        nextSteps: [
                            'Write your first test using write_test',
                            'Run the test to see it fail (RED phase)',
                            'Implement minimal code to pass',
                            'Refactor while keeping tests green',
                        ],
                    },
                };
            }
            case 'create_feature_interactive': {
                const { action, workflowId, response } = args;
                try {
                    if (action === 'start') {
                        const workflow = featureWizard.startFeatureDiscovery();
                        const currentStep = featureWizard.formatCurrentStep(workflow.id);
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: `🚀 Starting Interactive Feature Discovery Wizard

This wizard will help you define a feature by understanding the user problem, technical approach, and testing strategy.

${currentStep}

💡 Use the tool with action='continue', workflowId='${workflow.id}', and your response to proceed.`,
                                },
                            ],
                            structured: {
                                workflowId: workflow.id,
                                action: 'waiting_for_response',
                            },
                        };
                    }
                    if (action === 'continue' && workflowId) {
                        const result = await featureWizard.processWorkflowResponse(workflowId, response);
                        if (!result.valid) {
                            return {
                                content: [
                                    {
                                        type: 'text',
                                        text: `❌ ${result.message}\n\nPlease try again.`,
                                    },
                                ],
                                structured: {
                                    workflowId,
                                    action: 'waiting_for_response',
                                    error: result.message,
                                },
                            };
                        }
                        if (result.completed) {
                            const featureData = featureWizard.completeWorkflow(workflowId);
                            if (featureData) {
                                // Create the feature
                                const feature = devStore.createFeature(featureData.name, featureData.description);
                                await devStore.save();
                                // Generate initial test template
                                const testTemplate = devStore.generateTestTemplate(feature.name, `${feature.name} Core Functionality`);
                                return {
                                    content: [
                                        {
                                            type: 'text',
                                            text: `✅ Feature created successfully through interactive discovery!

🎯 **Feature**: ${feature.name}
📖 **User Story**: ${featureData.userStory}
🏗️ **Type**: ${featureData.featureType}
📊 **Complexity**: ${featureData.complexity}

**Problem Solved**: ${featureData.userProblem}

**Success Criteria**:
${featureData.successCriteria.map((criterion) => `• ${criterion}`).join('\n')}

**Acceptance Criteria**:
${featureData.acceptanceCriteria.map((criterion) => `• ${criterion}`).join('\n')}

**Testing Strategy**: ${featureData.testingStrategy}
${featureData.dependencies ? `\n🔗 **Dependencies**: ${featureData.dependencies}` : ''}
${featureData.performanceRequirements ? `\n⚡ **Performance**: ${featureData.performanceRequirements}` : ''}
${featureData.securityConsiderations ? `\n🔒 **Security**: ${featureData.securityConsiderations}` : ''}

⚠️ **TDD Reminder**: You must write tests before implementing!

📝 **Initial Test Template**:

\`\`\`typescript
${testTemplate}
\`\`\`

💡 Next steps:
1. Copy the test template and create your first failing test
2. Run the test to see it fail (RED phase)
3. Implement minimal code to make it pass (GREEN phase)
4. Refactor while keeping tests green`,
                                        },
                                    ],
                                    structured: {
                                        feature,
                                        featureData,
                                        testTemplate,
                                        created: true,
                                        createdVia: 'interactive-wizard',
                                    },
                                };
                            }
                        }
                        // Continue to next step
                        const currentStep = featureWizard.formatCurrentStep(workflowId);
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: currentStep,
                                },
                            ],
                            structured: {
                                workflowId,
                                action: 'waiting_for_response',
                            },
                        };
                    }
                    if (action === 'cancel' && workflowId) {
                        featureWizard.cancelWorkflow(workflowId);
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: `❌ Feature discovery wizard cancelled.`,
                                },
                            ],
                            structured: {
                                cancelled: true,
                            },
                        };
                    }
                    throw new Error('Invalid action or missing required parameters');
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Feature discovery wizard error: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'write_test': {
                const { featureName, testName, description, expectedBehavior, type = 'unit', generateTemplate = true } = args;
                const testCase = devStore.addTestCase(featureName, {
                    name: testName,
                    description,
                    type,
                    status: 'failing',
                    expectedBehavior,
                });
                if (!testCase) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Feature "${featureName}" not found`,
                            },
                        ],
                    };
                }
                await devStore.save();
                let response = `🔴 Test "${testCase.name}" created in FAILING state\n`;
                response += `📋 Expected: ${expectedBehavior}\n\n`;
                if (generateTemplate) {
                    const template = devStore.generateTestTemplate(featureName, testName);
                    response += `📝 Test Template:\n\n\`\`\`typescript\n${template}\n\`\`\`\n\n`;
                }
                response += `✅ You can now implement code to make this test pass!`;
                return {
                    content: [
                        {
                            type: 'text',
                            text: response,
                        },
                    ],
                };
            }
            case 'start_tdd_session': {
                const { featureName } = args;
                const feature = devStore.getFeature(featureName);
                if (!feature) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Feature "${featureName}" not found`,
                            },
                        ],
                    };
                }
                try {
                    const session = tddEnforcer.startTDDSession(feature);
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `🚀 TDD Session started for "${feature.name}"\n${tddEnforcer.getSessionReport(session.id)}`,
                            },
                        ],
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: error.message,
                            },
                        ],
                    };
                }
            }
            case 'check_tdd_status': {
                const { sessionId } = args;
                return {
                    content: [
                        {
                            type: 'text',
                            text: tddEnforcer.getSessionReport(sessionId),
                        },
                    ],
                };
            }
            case 'run_tests': {
                const { featureName, testIds } = args;
                const feature = devStore.getFeature(featureName);
                if (!feature) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Feature "${featureName}" not found`,
                            },
                        ],
                    };
                }
                // Simulate test execution (in real implementation, this would run actual tests)
                const testsToRun = testIds
                    ? feature.testCases.filter(t => testIds.includes(t.id))
                    : feature.testCases;
                let results = `🧪 Running ${testsToRun.length} test(s) for "${feature.name}"\n\n`;
                testsToRun.forEach(test => {
                    // This is a simulation - in reality, you'd execute the actual test
                    const passed = Math.random() > 0.5; // Simulate test result
                    devStore.updateTestStatus(featureName, test.id, passed ? 'passing' : 'failing');
                    results += passed
                        ? `✅ ${test.name} - PASSED\n`
                        : `❌ ${test.name} - FAILED\n`;
                });
                await devStore.save();
                const summary = feature.testCases.filter(t => t.status === 'passing').length;
                results += `\n📊 Summary: ${summary}/${feature.testCases.length} tests passing (${feature.testCoverage.toFixed(0)}% coverage)`;
                return {
                    content: [
                        {
                            type: 'text',
                            text: results,
                        },
                    ],
                };
            }
            case 'enforce_tdd': {
                const config = devStore.getConfig();
                return {
                    content: [
                        {
                            type: 'text',
                            text: `🛡️ TDD Enforcement Status:\n\n` +
                                `✅ Test-First Development: ${config.enforceTestFirst ? 'ENFORCED' : 'DISABLED'}\n` +
                                `📊 Minimum Coverage: ${config.minimumTestCoverage}%\n` +
                                `🚦 Require Tests Before Code: ${config.requireTestsBeforeImplementation ? 'YES' : 'NO'}\n` +
                                `📝 Auto-Generate Templates: ${config.autoGenerateTestTemplates ? 'YES' : 'NO'}`,
                        },
                    ],
                };
            }
            default:
                // Not a development tool, let other handlers process it
                return null;
        }
    });
    return {
        tools: [
            {
                name: 'create_feature',
                description: 'Create a new feature for TDD development',
                inputSchema: {
                    type: 'object',
                    properties: {
                        name: { type: 'string' },
                        description: { type: 'string' },
                    },
                    required: ['name', 'description'],
                },
            },
            {
                name: 'create_feature_interactive',
                description: 'Define a feature through an interactive wizard that explores user needs, technical approach, and testing strategy',
                inputSchema: {
                    type: 'object',
                    properties: {
                        action: {
                            type: 'string',
                            enum: ['start', 'continue', 'cancel'],
                            description: 'Action to perform: start new wizard, continue existing, or cancel'
                        },
                        workflowId: {
                            type: 'string',
                            description: 'Workflow ID (required for continue/cancel actions)'
                        },
                        response: {
                            description: 'Your response to the current question'
                        },
                    },
                    required: ['action'],
                },
            },
            {
                name: 'write_test',
                description: 'Write a test case (TDD: always write tests first!)',
                inputSchema: {
                    type: 'object',
                    properties: {
                        featureName: { type: 'string' },
                        testName: { type: 'string' },
                        description: { type: 'string' },
                        expectedBehavior: { type: 'string' },
                        type: {
                            type: 'string',
                            enum: ['unit', 'integration', 'e2e'],
                            default: 'unit'
                        },
                        generateTemplate: { type: 'boolean', default: true },
                    },
                    required: ['featureName', 'testName', 'description', 'expectedBehavior'],
                },
            },
            {
                name: 'start_tdd_session',
                description: 'Start a TDD session for a feature',
                inputSchema: {
                    type: 'object',
                    properties: {
                        featureName: { type: 'string' },
                    },
                    required: ['featureName'],
                },
            },
            {
                name: 'run_tests',
                description: 'Run tests for a feature',
                inputSchema: {
                    type: 'object',
                    properties: {
                        featureName: { type: 'string' },
                        testIds: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Specific test IDs to run (runs all if not specified)'
                        },
                    },
                    required: ['featureName'],
                },
            },
            {
                name: 'check_tdd_status',
                description: 'Check the status of a TDD session',
                inputSchema: {
                    type: 'object',
                    properties: {
                        sessionId: { type: 'string' },
                    },
                    required: ['sessionId'],
                },
            },
            {
                name: 'enforce_tdd',
                description: 'Show TDD enforcement configuration',
                inputSchema: {
                    type: 'object',
                    properties: {},
                    required: []
                },
            },
        ],
        resources: [],
    };
}
//# sourceMappingURL=index.js.map