import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { ConfigManager } from '../../config/config-manager.js';
import { GitManager } from './git-manager.js';
let configManager;
let gitManager;
export async function setupGitWorkflowTools(server, config) {
    configManager = config || new ConfigManager();
    gitManager = new GitManager();
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
        const { name, arguments: args } = request.params;
        if (!args) {
            throw new Error('No arguments provided');
        }
        switch (name) {
            case 'create_feature_branch': {
                const { name: branchName, from } = args;
                try {
                    const branch = await gitManager.createBranch(`feature/${branchName}`, from);
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `✅ Feature branch created\n\n**Branch**: ${branch.name}\n**Current**: ${branch.current ? 'Yes' : 'No'}\n\nYou can now start working on this feature. Remember to make atomic commits!`,
                            },
                        ],
                        structured: {
                            branch,
                            timestamp: new Date().toISOString(),
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to create feature branch\n\n**Error**: ${error.message}`,
                            },
                        ],
                        structured: {
                            error: error.message,
                            timestamp: new Date().toISOString(),
                        },
                    };
                }
            }
            case 'start_git_workflow': {
                const { type, name: workflowName } = args;
                try {
                    const workflow = await gitManager.startWorkflow(type, workflowName);
                    let output = `🚀 ${type.charAt(0).toUpperCase() + type.slice(1)} workflow started\n\n`;
                    output += `**Name**: ${workflow.name}\n`;
                    output += `**Type**: ${workflow.type}\n`;
                    output += `**Source Branch**: ${workflow.sourceBranch}\n`;
                    output += `**Target Branch**: ${workflow.targetBranch}\n\n`;
                    output += `**Steps**:\n`;
                    workflow.steps.forEach((step, index) => {
                        const icon = step.completed ? '✅' : index === workflow.currentStep ? '🔄' : '⏳';
                        output += `${icon} ${step.name}\n`;
                        if (step.description) {
                            output += `   ${step.description}\n`;
                        }
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: output,
                            },
                        ],
                        structured: {
                            workflow,
                            timestamp: new Date().toISOString(),
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to start workflow\n\n**Error**: ${error.message}`,
                            },
                        ],
                        structured: {
                            error: error.message,
                            timestamp: new Date().toISOString(),
                        },
                    };
                }
            }
            case 'list_branches': {
                const { includeRemote = false } = args;
                try {
                    const branches = await gitManager.getBranches();
                    const localBranches = branches.filter(b => !b.name.includes('origin/'));
                    const remoteBranches = branches.filter(b => b.name.includes('origin/'));
                    let output = `📋 Git Branches\n\n`;
                    output += `**Local Branches** (${localBranches.length})\n`;
                    localBranches.forEach(branch => {
                        const icon = branch.current ? '➡️' : '  ';
                        output += `${icon} ${branch.name}`;
                        if (branch.ahead > 0 || branch.behind > 0) {
                            output += ` [ahead ${branch.ahead}, behind ${branch.behind}]`;
                        }
                        output += '\n';
                    });
                    if (includeRemote && remoteBranches.length > 0) {
                        output += `\n**Remote Branches** (${remoteBranches.length})\n`;
                        remoteBranches.slice(0, 10).forEach(branch => {
                            output += `   ${branch.name}\n`;
                        });
                        if (remoteBranches.length > 10) {
                            output += `   ... and ${remoteBranches.length - 10} more\n`;
                        }
                    }
                    return {
                        content: [
                            {
                                type: 'text',
                                text: output,
                            },
                        ],
                        structured: {
                            branches: includeRemote ? branches : localBranches,
                            timestamp: new Date().toISOString(),
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to list branches\n\n**Error**: ${error.message}`,
                            },
                        ],
                        structured: {
                            error: error.message,
                            timestamp: new Date().toISOString(),
                        },
                    };
                }
            }
            case 'get_commit_history': {
                const { branch, limit = 10, since, until, author } = args;
                try {
                    const commits = await gitManager.getCommits({ branch, limit, since, until, author });
                    let output = `📜 Commit History\n\n`;
                    if (branch)
                        output += `**Branch**: ${branch}\n`;
                    if (author)
                        output += `**Author**: ${author}\n`;
                    if (since || until)
                        output += `**Period**: ${since || 'beginning'} to ${until || 'now'}\n`;
                    output += '\n';
                    commits.forEach(commit => {
                        const date = new Date(commit.date);
                        output += `• ${commit.shortHash} - ${commit.message}\n`;
                        output += `  by ${commit.author} on ${date.toLocaleDateString()}\n\n`;
                    });
                    if (commits.length === limit) {
                        output += `Showing ${limit} most recent commits. Use a higher limit to see more.`;
                    }
                    return {
                        content: [
                            {
                                type: 'text',
                                text: output,
                            },
                        ],
                        structured: {
                            commits,
                            timestamp: new Date().toISOString(),
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to get commit history\n\n**Error**: ${error.message}`,
                            },
                        ],
                        structured: {
                            error: error.message,
                            timestamp: new Date().toISOString(),
                        },
                    };
                }
            }
            case 'create_pull_request': {
                const { title, description, sourceBranch, targetBranch, labels, reviewers } = args;
                try {
                    const pr = await gitManager.createPullRequest({
                        title,
                        description,
                        sourceBranch,
                        targetBranch,
                        labels,
                        reviewers,
                    });
                    let output = `✅ Pull Request created\n\n`;
                    output += `**Number**: #${pr.number}\n`;
                    output += `**Title**: ${pr.title}\n`;
                    output += `**Branch**: ${pr.sourceBranch} → ${pr.targetBranch}\n`;
                    if (pr.labels?.length) {
                        output += `**Labels**: ${pr.labels.join(', ')}\n`;
                    }
                    output += `\nThe pull request is now open for review.`;
                    return {
                        content: [
                            {
                                type: 'text',
                                text: output,
                            },
                        ],
                        structured: {
                            pullRequest: pr,
                            timestamp: new Date().toISOString(),
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to create pull request\n\n**Error**: ${error.message}`,
                            },
                        ],
                        structured: {
                            error: error.message,
                            timestamp: new Date().toISOString(),
                        },
                    };
                }
            }
            case 'manage_tags': {
                const { action, name: tagName, message, commit, force } = args;
                try {
                    if (action === 'create') {
                        if (!tagName)
                            throw new Error('Tag name is required for create action');
                        const tag = await gitManager.createTag(tagName, { message, commit, force });
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: `✅ Tag created\n\n**Name**: ${tag.name}\n**Commit**: ${tag.commit}\n${tag.message ? `**Message**: ${tag.message}\n` : ''}\nTag has been created successfully.`,
                                },
                            ],
                            structured: {
                                tag,
                                timestamp: new Date().toISOString(),
                            },
                        };
                    }
                    else if (action === 'list') {
                        const tags = await gitManager.getTags();
                        let output = `📌 Git Tags (${tags.length})\n\n`;
                        tags.forEach(tag => {
                            output += `• ${tag.name}`;
                            if (tag.message) {
                                output += ` - ${tag.message}`;
                            }
                            output += '\n';
                            if (tag.date) {
                                const date = new Date(tag.date);
                                output += `  ${date.toLocaleDateString()}\n`;
                            }
                            output += '\n';
                        });
                        if (tags.length === 0) {
                            output = 'No tags found in this repository.';
                        }
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: output,
                                },
                            ],
                            structured: {
                                tags,
                                timestamp: new Date().toISOString(),
                            },
                        };
                    }
                    else {
                        throw new Error(`Unsupported action: ${action}`);
                    }
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to manage tags\n\n**Error**: ${error.message}`,
                            },
                        ],
                        structured: {
                            error: error.message,
                            timestamp: new Date().toISOString(),
                        },
                    };
                }
            }
            case 'get_git_status': {
                try {
                    const status = await gitManager.getStatus();
                    let output = `📊 Git Status\n\n`;
                    output += `**Branch**: ${status.branch}`;
                    if (status.upstream) {
                        output += ` → ${status.upstream}`;
                        if (status.ahead > 0 || status.behind > 0) {
                            output += ` [ahead ${status.ahead}, behind ${status.behind}]`;
                        }
                    }
                    output += '\n\n';
                    if (status.staged.length > 0) {
                        output += `**Staged Changes** (${status.staged.length})\n`;
                        status.staged.forEach(file => {
                            output += `✅ ${file}\n`;
                        });
                        output += '\n';
                    }
                    if (status.unstaged.length > 0) {
                        output += `**Unstaged Changes** (${status.unstaged.length})\n`;
                        status.unstaged.forEach(file => {
                            output += `⚠️ ${file}\n`;
                        });
                        output += '\n';
                    }
                    if (status.untracked.length > 0) {
                        output += `**Untracked Files** (${status.untracked.length})\n`;
                        status.untracked.forEach(file => {
                            output += `❓ ${file}\n`;
                        });
                    }
                    if (status.staged.length === 0 && status.unstaged.length === 0 && status.untracked.length === 0) {
                        output += 'Working tree is clean.';
                    }
                    return {
                        content: [
                            {
                                type: 'text',
                                text: output,
                            },
                        ],
                        structured: {
                            status,
                            timestamp: new Date().toISOString(),
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to get git status\n\n**Error**: ${error.message}`,
                            },
                        ],
                        structured: {
                            error: error.message,
                            timestamp: new Date().toISOString(),
                        },
                    };
                }
            }
            case 'setup_git_hooks': {
                const { hooks } = args;
                try {
                    await gitManager.setupGitHooks(hooks);
                    let output = `✅ Git hooks configured\n\n`;
                    hooks.forEach(hook => {
                        const icon = hook.enabled ? '✅' : '❌';
                        output += `${icon} **${hook.name}**\n`;
                    });
                    output += `\n${hooks.filter(h => h.enabled).length} hook(s) enabled.`;
                    return {
                        content: [
                            {
                                type: 'text',
                                text: output,
                            },
                        ],
                        structured: {
                            hooks,
                            timestamp: new Date().toISOString(),
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to setup git hooks\n\n**Error**: ${error.message}`,
                            },
                        ],
                        structured: {
                            error: error.message,
                            timestamp: new Date().toISOString(),
                        },
                    };
                }
            }
            case 'get_git_stats': {
                try {
                    const stats = await gitManager.getStats();
                    let output = `📈 Git Repository Statistics\n\n`;
                    output += `**Total Commits**: ${stats.totalCommits}\n`;
                    output += `**Branches**: ${stats.branches}\n`;
                    output += `**Tags**: ${stats.tags}\n\n`;
                    output += `**Top Contributors**\n`;
                    stats.contributors.slice(0, 5).forEach((contributor, index) => {
                        output += `${index + 1}. ${contributor.name} - ${contributor.commits} commits\n`;
                    });
                    if (stats.contributors.length > 5) {
                        output += `... and ${stats.contributors.length - 5} more contributors\n`;
                    }
                    return {
                        content: [
                            {
                                type: 'text',
                                text: output,
                            },
                        ],
                        structured: {
                            stats,
                            timestamp: new Date().toISOString(),
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to get git stats\n\n**Error**: ${error.message}`,
                            },
                        ],
                        structured: {
                            error: error.message,
                            timestamp: new Date().toISOString(),
                        },
                    };
                }
            }
            case 'validate_commit_message': {
                const { message, convention = { type: 'conventional' } } = args;
                try {
                    const result = await gitManager.validateCommitMessage(message, convention);
                    if (result.valid) {
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: `✅ Commit message is valid\n\n**Message**: ${message}\n**Convention**: ${convention.type}\n\nThe commit message follows the specified convention.`,
                                },
                            ],
                            structured: {
                                valid: true,
                                message,
                                convention,
                                timestamp: new Date().toISOString(),
                            },
                        };
                    }
                    else {
                        let output = `❌ Invalid commit message\n\n**Message**: ${message}\n**Convention**: ${convention.type}\n\n**Errors**:\n`;
                        result.errors.forEach(error => {
                            output += `• ${error}\n`;
                        });
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: output,
                                },
                            ],
                            structured: {
                                valid: false,
                                message,
                                convention,
                                errors: result.errors,
                                timestamp: new Date().toISOString(),
                            },
                        };
                    }
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to validate commit message\n\n**Error**: ${error.message}`,
                            },
                        ],
                        structured: {
                            error: error.message,
                            timestamp: new Date().toISOString(),
                        },
                    };
                }
            }
            default:
                return null;
        }
    });
    return {
        tools: [
            {
                name: 'create_feature_branch',
                description: 'Create a new feature branch following Git Flow conventions',
                inputSchema: {
                    type: 'object',
                    properties: {
                        name: { type: 'string', description: 'Feature name (will be prefixed with feature/)' },
                        from: { type: 'string', description: 'Base branch to create from (default: current branch)' },
                    },
                    required: ['name'],
                },
            },
            {
                name: 'start_git_workflow',
                description: 'Start a structured git workflow (feature, release, hotfix)',
                inputSchema: {
                    type: 'object',
                    properties: {
                        type: {
                            type: 'string',
                            enum: ['feature', 'release', 'hotfix', 'custom'],
                            description: 'Type of workflow',
                        },
                        name: { type: 'string', description: 'Workflow name' },
                    },
                    required: ['type', 'name'],
                },
            },
            {
                name: 'list_branches',
                description: 'List all git branches with their status',
                inputSchema: {
                    type: 'object',
                    properties: {
                        includeRemote: { type: 'boolean', description: 'Include remote branches', default: false },
                    },
                    required: []
                },
            },
            {
                name: 'get_commit_history',
                description: 'Get commit history with filters',
                inputSchema: {
                    type: 'object',
                    properties: {
                        branch: { type: 'string', description: 'Specific branch (default: current)' },
                        limit: { type: 'number', description: 'Number of commits to retrieve', default: 10 },
                        since: { type: 'string', description: 'Start date (e.g., "2024-01-01")' },
                        until: { type: 'string', description: 'End date' },
                        author: { type: 'string', description: 'Filter by author' },
                    },
                    required: []
                },
            },
            {
                name: 'create_pull_request',
                description: 'Create a pull request on GitHub/GitLab/Bitbucket',
                inputSchema: {
                    type: 'object',
                    properties: {
                        title: { type: 'string', description: 'PR title' },
                        description: { type: 'string', description: 'PR description' },
                        sourceBranch: { type: 'string', description: 'Source branch' },
                        targetBranch: { type: 'string', description: 'Target branch (default: main)' },
                        labels: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Labels to add'
                        },
                        reviewers: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Reviewers to assign'
                        },
                    },
                    required: ['title', 'description', 'sourceBranch'],
                },
            },
            {
                name: 'manage_tags',
                description: 'Create, list, or delete git tags',
                inputSchema: {
                    type: 'object',
                    properties: {
                        action: {
                            type: 'string',
                            enum: ['create', 'list', 'delete'],
                            description: 'Action to perform',
                        },
                        name: { type: 'string', description: 'Tag name (for create/delete)' },
                        message: { type: 'string', description: 'Annotated tag message' },
                        commit: { type: 'string', description: 'Specific commit to tag (default: HEAD)' },
                        force: { type: 'boolean', description: 'Force create/delete', default: false },
                    },
                    required: ['action'],
                },
            },
            {
                name: 'get_git_status',
                description: 'Get current git repository status',
                inputSchema: {
                    type: 'object',
                    properties: {},
                    required: []
                },
            },
            {
                name: 'setup_git_hooks',
                description: 'Configure git hooks for the repository',
                inputSchema: {
                    type: 'object',
                    properties: {
                        hooks: {
                            type: 'array',
                            items: {
                                type: 'object',
                                properties: {
                                    name: {
                                        type: 'string',
                                        enum: ['pre-commit', 'commit-msg', 'pre-push', 'post-merge'],
                                    },
                                    script: { type: 'string', description: 'Hook script content' },
                                    enabled: { type: 'boolean', description: 'Whether to enable the hook' },
                                },
                                required: ['name', 'script', 'enabled'],
                            },
                            description: 'Git hooks to configure',
                        },
                    },
                    required: ['hooks'],
                },
            },
            {
                name: 'get_git_stats',
                description: 'Get repository statistics and analytics',
                inputSchema: {
                    type: 'object',
                    properties: {},
                    required: []
                },
            },
            {
                name: 'validate_commit_message',
                description: 'Validate commit message against conventions',
                inputSchema: {
                    type: 'object',
                    properties: {
                        message: { type: 'string', description: 'Commit message to validate' },
                        convention: {
                            type: 'object',
                            properties: {
                                type: {
                                    type: 'string',
                                    enum: ['conventional', 'gitmoji', 'custom'],
                                    description: 'Convention type',
                                },
                                types: {
                                    type: 'array',
                                    items: { type: 'string' },
                                    description: 'Allowed commit types',
                                },
                                scopes: {
                                    type: 'array',
                                    items: { type: 'string' },
                                    description: 'Allowed scopes',
                                },
                            },
                            description: 'Commit convention rules',
                        },
                    },
                    required: ['message'],
                },
            },
        ],
        resources: [],
    };
}
//# sourceMappingURL=index.js.map