import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { ConfigManager } from '../../config/config-manager.js';
import { promises as fs } from 'fs';
import path from 'path';
import { exec } from 'child_process';
import { promisify } from 'util';
const execAsync = promisify(exec);
let configManager;
let workflowContext = {};
export async function setupDeveloperWorkflowTools(server, config) {
    configManager = config || new ConfigManager();
    // Add developer workflow tool handlers
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
        const { name, arguments: args } = request.params;
        if (!args) {
            throw new Error('No arguments provided');
        }
        switch (name) {
            case 'start_feature': {
                const { featureName, branchFrom = 'main' } = args;
                try {
                    // Check for uncommitted changes
                    const { stdout: status } = await execAsync('git status --porcelain');
                    if (status.trim()) {
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: `⚠️  You have uncommitted changes. Please commit or stash them before starting a new feature.`,
                                },
                            ],
                        };
                    }
                    // Create and checkout new branch
                    await execAsync(`git checkout -b feature/${featureName} ${branchFrom}`);
                    // Update workflow context
                    workflowContext.currentBranch = `feature/${featureName}`;
                    workflowContext.activeFeature = featureName;
                    // Create feature tracking file
                    const featureDir = path.join('.atlas', 'features');
                    await fs.mkdir(featureDir, { recursive: true });
                    const featureConfig = {
                        name: featureName,
                        branch: `feature/${featureName}`,
                        startedAt: new Date().toISOString(),
                        tasks: [],
                        tests: [],
                    };
                    await fs.writeFile(path.join(featureDir, `${featureName}.json`), JSON.stringify(featureConfig, null, 2));
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `🚀 Started feature: ${featureName}\n\n` +
                                    `📍 Branch: feature/${featureName}\n` +
                                    `🎯 Ready for TDD development!\n\n` +
                                    `Next steps:\n` +
                                    `1. Write your first test with 'write_test'\n` +
                                    `2. Run tests to see them fail\n` +
                                    `3. Implement the feature\n` +
                                    `4. Refactor with confidence`,
                            },
                        ],
                        structured: {
                            feature: featureName,
                            branch: `feature/${featureName}`,
                            status: 'started',
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Error starting feature: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'check_workflow_status': {
                try {
                    // Get current branch
                    const { stdout: branch } = await execAsync('git branch --show-current');
                    workflowContext.currentBranch = branch.trim();
                    // Check for uncommitted changes
                    const { stdout: status } = await execAsync('git status --porcelain');
                    workflowContext.uncommittedChanges = status
                        .split('\n')
                        .filter(line => line.trim())
                        .map(line => line.substring(3));
                    // Check test status (assuming npm test)
                    try {
                        await execAsync('npm test -- --passWithNoTests');
                        workflowContext.testStatus = 'passing';
                    }
                    catch {
                        workflowContext.testStatus = 'failing';
                    }
                    workflowContext.lastTestRun = new Date();
                    // Build status message
                    const statusEmoji = {
                        passing: '✅',
                        failing: '❌',
                        unknown: '❓',
                    };
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `📊 Workflow Status\n\n` +
                                    `📍 Branch: ${workflowContext.currentBranch}\n` +
                                    `${statusEmoji[workflowContext.testStatus || 'unknown']} Tests: ${workflowContext.testStatus}\n` +
                                    `📝 Uncommitted changes: ${workflowContext.uncommittedChanges?.length || 0}\n` +
                                    (workflowContext.uncommittedChanges?.length ?
                                        `\nChanged files:\n${workflowContext.uncommittedChanges.map(f => `  • ${f}`).join('\n')}` : '') +
                                    (workflowContext.activeFeature ?
                                        `\n\n🎯 Active feature: ${workflowContext.activeFeature}` : ''),
                            },
                        ],
                        structured: workflowContext,
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Error checking status: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'suggest_next_action': {
                const suggestions = [];
                // Check context and suggest appropriate actions
                if (!workflowContext.currentBranch || workflowContext.currentBranch === 'main') {
                    suggestions.push('Start a new feature with `start_feature`');
                }
                if (workflowContext.testStatus === 'failing') {
                    suggestions.push('Fix failing tests before continuing');
                }
                else if (workflowContext.testStatus === 'passing' && workflowContext.uncommittedChanges?.length) {
                    suggestions.push('Commit your changes to save progress');
                }
                if (workflowContext.activeFeature && workflowContext.testStatus === 'passing') {
                    suggestions.push('Write more tests for edge cases');
                    suggestions.push('Refactor code while tests are green');
                }
                if (!workflowContext.uncommittedChanges?.length && workflowContext.currentBranch?.startsWith('feature/')) {
                    suggestions.push('Consider creating a pull request');
                }
                return {
                    content: [
                        {
                            type: 'text',
                            text: `💡 Suggested Next Actions:\n\n${suggestions.map((s, i) => `${i + 1}. ${s}`).join('\n')}\n\n` +
                                `Use 'check_workflow_status' to update current state.`,
                        },
                    ],
                    structured: {
                        suggestions,
                        context: workflowContext,
                    },
                };
            }
            case 'run_tdd_cycle': {
                const { testCommand = 'npm test', testFile } = args;
                try {
                    const steps = [];
                    // Step 1: Run tests (RED phase)
                    steps.push('🔴 RED: Running tests...');
                    let testFailed = false;
                    try {
                        const testCmd = testFile ? `${testCommand} ${testFile}` : testCommand;
                        await execAsync(testCmd);
                        steps.push('⚠️  Tests are passing - write a failing test first!');
                    }
                    catch (error) {
                        testFailed = true;
                        steps.push('✅ Good! Tests are failing as expected');
                    }
                    if (!testFailed) {
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: steps.join('\n') + '\n\n💡 TDD requires writing failing tests first!',
                                },
                            ],
                        };
                    }
                    // Step 2: Prompt for implementation (GREEN phase)
                    steps.push('\n🟢 GREEN: Now implement the minimal code to pass the test');
                    steps.push('📝 Focus on making the test pass, not perfect code');
                    // Step 3: Refactor reminder (REFACTOR phase)
                    steps.push('\n🔵 REFACTOR: Once tests pass, improve the code');
                    steps.push('♻️  Keep running tests to ensure nothing breaks');
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `🔄 TDD Cycle Started!\n\n${steps.join('\n')}\n\n` +
                                    `Commands:\n` +
                                    `• Run tests: ${testCommand}\n` +
                                    `• Run specific test: ${testCommand} <test-file>\n` +
                                    `• Watch mode: ${testCommand} --watch`,
                            },
                        ],
                        structured: {
                            phase: 'red',
                            testsFailing: true,
                            nextStep: 'implement',
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Error running TDD cycle: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'setup_commit_hooks': {
                const { preCommit = true, prePush = true } = args;
                try {
                    // Create hooks directory
                    const hooksDir = path.join('.git', 'hooks');
                    if (preCommit) {
                        const preCommitHook = `#!/bin/sh
# Pre-commit hook: Run tests before committing

echo "🧪 Running tests before commit..."
npm test -- --passWithNoTests

if [ $? -ne 0 ]; then
  echo "❌ Tests failed! Fix them before committing."
  exit 1
fi

echo "✅ All tests pass! Proceeding with commit..."
`;
                        await fs.writeFile(path.join(hooksDir, 'pre-commit'), preCommitHook);
                        await fs.chmod(path.join(hooksDir, 'pre-commit'), '755');
                    }
                    if (prePush) {
                        const prePushHook = `#!/bin/sh
# Pre-push hook: Ensure all tests pass and code is linted

echo "🔍 Running full test suite before push..."
npm test

if [ $? -ne 0 ]; then
  echo "❌ Tests failed! Cannot push."
  exit 1
fi

echo "🎨 Running linter..."
npm run lint 2>/dev/null || true

echo "✅ All checks passed! Pushing to remote..."
`;
                        await fs.writeFile(path.join(hooksDir, 'pre-push'), prePushHook);
                        await fs.chmod(path.join(hooksDir, 'pre-push'), '755');
                    }
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `✅ Git hooks configured!\n\n` +
                                    (preCommit ? '🪝 Pre-commit: Tests run before every commit\n' : '') +
                                    (prePush ? '🪝 Pre-push: Full test suite runs before push\n' : '') +
                                    `\n💡 This enforces TDD practices in your workflow`,
                            },
                        ],
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Error setting up hooks: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            default:
                // Not a developer workflow tool
                return null;
        }
    });
    return {
        tools: [
            {
                name: 'start_feature',
                description: 'Start a new feature with TDD workflow',
                inputSchema: {
                    type: 'object',
                    properties: {
                        featureName: { type: 'string', description: 'Name of the feature' },
                        branchFrom: { type: 'string', default: 'main', description: 'Base branch' },
                    },
                    required: ['featureName'],
                },
            },
            {
                name: 'check_workflow_status',
                description: 'Check current development workflow status',
                inputSchema: {
                    type: 'object',
                    properties: {},
                    required: []
                },
            },
            {
                name: 'suggest_next_action',
                description: 'Get AI suggestions for next development steps',
                inputSchema: {
                    type: 'object',
                    properties: {},
                    required: []
                },
            },
            {
                name: 'run_tdd_cycle',
                description: 'Guide through a TDD red-green-refactor cycle',
                inputSchema: {
                    type: 'object',
                    properties: {
                        testCommand: { type: 'string', default: 'npm test', description: 'Test command to run' },
                        testFile: { type: 'string', description: 'Specific test file to run' },
                    },
                    required: []
                },
            },
            {
                name: 'setup_commit_hooks',
                description: 'Setup git hooks to enforce TDD practices',
                inputSchema: {
                    type: 'object',
                    properties: {
                        preCommit: { type: 'boolean', default: true, description: 'Run tests before commit' },
                        prePush: { type: 'boolean', default: true, description: 'Run full suite before push' },
                    },
                    required: []
                },
            },
        ],
        resources: [],
    };
}
//# sourceMappingURL=index.js.map