import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { ConfigManager } from '../../config/config-manager.js';
import { AgileManager } from './manager.js';
import { EpicCreationWizard } from './epic-wizard.js';
import { SprintPlanningWizard } from './sprint-planning-wizard.js';
let configManager;
let agileManager;
let epicWizard;
let sprintPlanningWizard;
export async function setupAgileManagementTools(server, config) {
    configManager = config || new ConfigManager();
    agileManager = new AgileManager(configManager);
    epicWizard = new EpicCreationWizard();
    sprintPlanningWizard = new SprintPlanningWizard();
    // Initialize agile management
    await agileManager.initialize();
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
        const { name, arguments: args } = request.params;
        if (!args) {
            throw new Error('No arguments provided');
        }
        switch (name) {
            case 'create_agile_sprint': {
                const { name: sprintName, goal, duration = 14, startDate, team = [], } = args;
                try {
                    const sprint = await agileManager.createSprint({
                        name: sprintName,
                        goal,
                        duration,
                        startDate: startDate ? new Date(startDate) : new Date(),
                        team,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `✅ Sprint created successfully!

📋 **Sprint**: ${sprint.name}
🎯 **Goal**: ${sprint.goal}
📅 **Duration**: ${sprint.duration} days
🗓️ **Start Date**: ${sprint.startDate.toLocaleDateString()}
🏁 **End Date**: ${sprint.endDate.toLocaleDateString()}
👥 **Team**: ${sprint.team.length > 0 ? sprint.team.join(', ') : 'Not assigned'}

**Status**: ${sprint.status}
**Sprint ID**: ${sprint.id}

💡 Next steps:
1. Add user stories to the sprint
2. Plan sprint backlog
3. Conduct sprint planning session`,
                            },
                        ],
                        structured: {
                            sprint,
                            created: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to create sprint: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'create_sprint_interactive': {
                const { action, workflowId, response } = args;
                try {
                    if (action === 'start') {
                        // Get existing stories for selection
                        const backlogStories = await agileManager.getBacklog({ status: 'todo' });
                        const workflow = sprintPlanningWizard.startSprintPlanning(backlogStories);
                        const currentStep = sprintPlanningWizard.formatCurrentStep(workflow.id);
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: `🚀 Starting Interactive Sprint Planning Wizard

This wizard will guide you through planning your sprint with proper capacity planning, goal setting, and story selection.

${currentStep}

💡 Use the tool with action='continue', workflowId='${workflow.id}', and your response to proceed.`,
                                },
                            ],
                            structured: {
                                workflowId: workflow.id,
                                action: 'waiting_for_response',
                                backlogCount: backlogStories.length,
                            },
                        };
                    }
                    if (action === 'continue' && workflowId) {
                        const result = await sprintPlanningWizard.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 planData = sprintPlanningWizard.completeWorkflow(workflowId);
                            if (planData) {
                                // Create the sprint
                                const sprint = await agileManager.createSprint({
                                    name: planData.name,
                                    goal: planData.goal,
                                    duration: planData.duration,
                                    startDate: new Date(planData.startDate),
                                    team: planData.team,
                                });
                                // Add selected stories to sprint if any
                                if (planData.selectedStoryIndices && planData.selectedStoryIndices.length > 0) {
                                    const backlogStories = await agileManager.getBacklog({ status: 'todo' });
                                    for (const index of planData.selectedStoryIndices) {
                                        if (index >= 0 && index < backlogStories.length) {
                                            const story = backlogStories[index];
                                            await agileManager.addStoryToSprint(story.id, sprint.id);
                                        }
                                    }
                                }
                                return {
                                    content: [
                                        {
                                            type: 'text',
                                            text: `✅ Sprint planned successfully through interactive wizard!

📋 **Sprint**: ${sprint.name}
🎯 **Goal**: ${sprint.goal}
📅 **Duration**: ${sprint.duration} days
🗓️ **Start Date**: ${sprint.startDate.toLocaleDateString()}
🏁 **End Date**: ${sprint.endDate.toLocaleDateString()}
👥 **Team**: ${sprint.team.join(', ')}

**Capacity**: ${planData.capacity}
**Velocity Estimate**: ${planData.velocityEstimate}

**Focus Areas**:
${planData.focusAreas.map((area) => `• ${area}`).join('\n')}

${planData.knownRisks ? `⚠️ **Risks**: ${planData.knownRisks}` : ''}
${planData.definitionOfDone.length > 0 ? `✅ **Definition of Done**:\n${planData.definitionOfDone.map((d) => `• ${d}`).join('\n')}` : ''}

**Sprint ID**: ${sprint.id}

💡 The sprint has been created and is ready to start. You can now:
- Track daily progress with standups
- Monitor the burndown chart
- Adjust as needed during the sprint`,
                                        },
                                    ],
                                    structured: {
                                        sprint,
                                        planData,
                                        created: true,
                                        createdVia: 'interactive-wizard',
                                    },
                                };
                            }
                        }
                        // Continue to next step
                        const currentStep = sprintPlanningWizard.formatCurrentStep(workflowId);
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: currentStep,
                                },
                            ],
                            structured: {
                                workflowId,
                                action: 'waiting_for_response',
                            },
                        };
                    }
                    if (action === 'cancel' && workflowId) {
                        sprintPlanningWizard.cancelWorkflow(workflowId);
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: `❌ Sprint planning wizard cancelled.`,
                                },
                            ],
                            structured: {
                                cancelled: true,
                            },
                        };
                    }
                    throw new Error('Invalid action or missing required parameters');
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Sprint planning wizard error: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'add_story': {
                const { title, description, storyPoints = 0, priority = 'medium', acceptanceCriteria = [], epic, assignee, sprintId, } = args;
                try {
                    const story = await agileManager.addStory({
                        title,
                        description,
                        storyPoints,
                        priority,
                        acceptanceCriteria,
                        epic,
                        assignee,
                        sprintId,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `✅ User story created successfully!

📖 **Story**: ${story.title}
📝 **Description**: ${story.description}
⭐ **Story Points**: ${story.storyPoints}
🎯 **Priority**: ${story.priority}
👤 **Assignee**: ${story.assignee || 'Unassigned'}
🏃 **Sprint**: ${story.sprintId || 'Backlog'}
${story.epic ? `📚 **Epic**: ${story.epic}` : ''}

**Status**: ${story.status}
**Story ID**: ${story.id}

📋 **Acceptance Criteria** (${story.acceptanceCriteria.length}):
${story.acceptanceCriteria.map((criteria, i) => `${i + 1}. ${criteria}`).join('\n')}`,
                            },
                        ],
                        structured: {
                            story,
                            created: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to create story: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'create_epic': {
                const { title, description, goals = [], priority = 'medium', owner, } = args;
                try {
                    const epic = await agileManager.createEpic({
                        title,
                        description,
                        goals,
                        priority,
                        owner,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `✅ Epic created successfully!

📚 **Epic**: ${epic.title}
📝 **Description**: ${epic.description}
🎯 **Priority**: ${epic.priority}
👤 **Owner**: ${epic.owner || 'Unassigned'}

**Status**: ${epic.status}
**Epic ID**: ${epic.id}

🎯 **Goals** (${epic.goals.length}):
${epic.goals.map((goal, i) => `${i + 1}. ${goal}`).join('\n')}

💡 You can now add user stories to this epic using the epic ID.`,
                            },
                        ],
                        structured: {
                            epic,
                            created: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to create epic: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'create_epic_interactive': {
                const { action, workflowId, response } = args;
                try {
                    if (action === 'start') {
                        const workflow = epicWizard.startEpicCreation();
                        const currentStep = epicWizard.formatCurrentStep(workflow.id);
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: `🚀 Starting Interactive Epic Creation Wizard

${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 epicWizard.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 epic = epicWizard.completeWorkflow(workflowId);
                            if (epic) {
                                // Save the epic using agileManager
                                await agileManager.saveEpic(epic);
                                return {
                                    content: [
                                        {
                                            type: 'text',
                                            text: `✅ Epic created successfully through interactive wizard!

📚 **Epic**: ${epic.title}
🎯 **Priority**: ${epic.priority}
💼 **Business Value**: ${epic.metadata?.businessValue}
👥 **Target Users**: ${epic.metadata?.targetUsers}

**Epic ID**: ${epic.id}

🎯 **Success Criteria**:
${epic.goals.map((goal, i) => `${i + 1}. ${goal}`).join('\n')}

${epic.metadata?.risks ? `⚠️ **Risks**: ${epic.metadata.risks}` : ''}
${epic.metadata?.hasDependencies ? `🔗 **Dependencies**: ${epic.metadata.dependencyDetails}` : ''}

💡 The epic has been created and saved. You can now:
- Add user stories to break down the work
- Assign the epic to a product owner
- Start planning sprints`,
                                        },
                                    ],
                                    structured: {
                                        epic,
                                        created: true,
                                        createdVia: 'interactive-wizard',
                                    },
                                };
                            }
                        }
                        // Continue to next step
                        const currentStep = epicWizard.formatCurrentStep(workflowId);
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: currentStep,
                                },
                            ],
                            structured: {
                                workflowId,
                                action: 'waiting_for_response',
                            },
                        };
                    }
                    if (action === 'cancel' && workflowId) {
                        epicWizard.cancelWorkflow(workflowId);
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: `❌ Epic creation wizard cancelled.`,
                                },
                            ],
                            structured: {
                                cancelled: true,
                            },
                        };
                    }
                    throw new Error('Invalid action or missing required parameters');
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Epic wizard error: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'conduct_sprint_planning': {
                const { sprintId, attendees = [], capacity, commitments = [], } = args;
                try {
                    const planning = await agileManager.conductSprintPlanning({
                        sprintId,
                        attendees,
                        capacity,
                        commitments,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: formatSprintPlanning(planning),
                            },
                        ],
                        structured: {
                            planning,
                            completed: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Sprint planning failed: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'record_daily_standup': {
                const { sprintId, attendee, yesterday = [], today = [], blockers = [], } = args;
                try {
                    const standup = await agileManager.recordStandup({
                        sprintId,
                        attendee,
                        yesterday,
                        today,
                        blockers,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: formatStandupReport(standup),
                            },
                        ],
                        structured: {
                            standup,
                            recorded: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to record standup: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'conduct_sprint_retrospective': {
                const { sprintId, attendees = [], whatWentWell = [], whatCanImprove = [], actionItems = [], } = args;
                try {
                    const retrospective = await agileManager.conductRetrospective({
                        sprintId,
                        attendees,
                        whatWentWell,
                        whatCanImprove,
                        actionItems,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: formatRetrospective(retrospective),
                            },
                        ],
                        structured: {
                            retrospective,
                            completed: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Retrospective failed: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'update_story_status': {
                const { storyId, status, hoursSpent, notes, groomedWithUserFeedback, } = args;
                try {
                    const story = await agileManager.updateStoryStatus(storyId, {
                        status,
                        hoursSpent,
                        notes,
                        groomedWithUserFeedback,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `✅ Story status updated!

📖 **Story**: ${story.title}
📊 **Status**: ${story.status}
⏱️ **Hours Spent**: ${story.hoursSpent || 0}
✅ **Groomed**: ${story.groomedWithUserFeedback ? 'Yes' : 'No'}
${notes ? `📝 **Notes**: ${notes}` : ''}

**Progress**: ${story.status === 'done' ? 'Complete!' : 'In progress...'}`,
                            },
                        ],
                        structured: {
                            story,
                            updated: true,
                        },
                    };
                }
                catch (error) {
                    const errorMessage = error.message;
                    const isGroomingError = errorMessage.includes('groomed with user feedback');
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to update story: ${errorMessage}${isGroomingError
                                    ? '\n\n💡 **Tip**: First set groomedWithUserFeedback to true, then move to in_progress.'
                                    : ''}`,
                            },
                        ],
                    };
                }
            }
            case 'assign_story_to_sprint': {
                const { storyId, sprintId } = args;
                try {
                    await agileManager.addStoryToSprint(storyId, sprintId);
                    const story = await agileManager.getStory(storyId);
                    const sprint = await agileManager.getSprint(sprintId);
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `✅ Story assigned to sprint successfully!

📖 **Story**: ${story?.title || storyId}
🏃 **Sprint**: ${sprint?.name || sprintId}
${story?.epic ? `📚 **Epic**: ${story.epic}` : ''}

The story has been added to the sprint and can now be tracked in sprint planning and burndown charts.`,
                            },
                        ],
                        structured: {
                            storyId,
                            sprintId,
                            assigned: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to assign story to sprint: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'generate_burndown_chart': {
                const { sprintId } = args;
                try {
                    const burndown = await agileManager.generateBurndownChart(sprintId);
                    return {
                        content: [
                            {
                                type: 'text',
                                text: formatBurndownChart(burndown),
                            },
                        ],
                        structured: {
                            burndown,
                            generated: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to generate burndown chart: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'generate_velocity_report': {
                const { teamName, lastNSprints = 5, } = args;
                try {
                    const velocityReport = await agileManager.generateVelocityReport({
                        teamName,
                        lastNSprints,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: formatVelocityReport(velocityReport),
                            },
                        ],
                        structured: {
                            velocityReport,
                            generated: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to generate velocity report: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'get_sprint_status': {
                const { sprintId } = args;
                try {
                    const status = await agileManager.getSprintStatus(sprintId);
                    return {
                        content: [
                            {
                                type: 'text',
                                text: formatSprintStatus(status),
                            },
                        ],
                        structured: {
                            status,
                            retrieved: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to get sprint status: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'list_agile_backlog': {
                const { epic, priority, assignee, status = 'todo', } = args;
                try {
                    const backlog = await agileManager.getBacklog({
                        epic,
                        priority,
                        assignee,
                        status,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: formatBacklog(backlog),
                            },
                        ],
                        structured: {
                            backlog,
                            retrieved: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to retrieve backlog: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'update_epic': {
                const { epicId, title, description, status, priority, goals, owner, metadata, } = args;
                try {
                    const epic = await agileManager.updateEpic(epicId, {
                        title,
                        description,
                        status,
                        priority,
                        goals,
                        owner,
                        metadata,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `✅ Epic updated successfully!

📋 **Epic**: ${epic.title}
📊 **Status**: ${epic.status}
🎯 **Priority**: ${epic.priority}
👤 **Owner**: ${epic.owner || 'Unassigned'}
📈 **Progress**: ${epic.progress}%

**Goals**:
${epic.goals.map((goal, i) => `${i + 1}. ${goal}`).join('\n')}

**Epic ID**: ${epic.id}
**Updated**: ${new Date(epic.updatedAt).toLocaleString()}`,
                            },
                        ],
                        structured: {
                            epic,
                            updated: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to update epic: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'update_sprint': {
                const { sprintId, name, goal, status, endDate, team, capacity, } = args;
                try {
                    const sprint = await agileManager.updateSprint(sprintId, {
                        name,
                        goal,
                        status,
                        endDate: endDate ? new Date(endDate) : undefined,
                        team,
                        capacity,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `✅ Sprint updated successfully!

📋 **Sprint**: ${sprint.name}
🎯 **Goal**: ${sprint.goal}
📊 **Status**: ${sprint.status}
📅 **Duration**: ${sprint.duration} days
🗓️ **Start Date**: ${sprint.startDate.toLocaleDateString()}
🏁 **End Date**: ${sprint.endDate.toLocaleDateString()}
👥 **Team**: ${sprint.team.length > 0 ? sprint.team.join(', ') : 'Not assigned'}
🎨 **Capacity**: ${sprint.capacity} story points
⚡ **Velocity**: ${sprint.velocity} story points

**Sprint ID**: ${sprint.id}`,
                            },
                        ],
                        structured: {
                            sprint,
                            updated: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to update sprint: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'list_agile_sprints': {
                const { status, includeCompleted = true, } = args;
                try {
                    const sprints = await agileManager.getSprints({ status, includeCompleted });
                    if (sprints.length === 0) {
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: '📋 No sprints found\n\nCreate your first sprint with `create_sprint` or `create_sprint_interactive`',
                                },
                            ],
                            structured: {
                                sprints: [],
                                count: 0,
                            },
                        };
                    }
                    const sprintsList = sprints.map((sprint) => {
                        const dateRange = `${sprint.startDate.toLocaleDateString()} - ${sprint.endDate.toLocaleDateString()}`;
                        return `Sprint ID: ${sprint.id} | ${sprint.name} (${sprint.status}) | ${sprint.goal} | ${dateRange} | Team: ${sprint.team.length} | Stories: ${sprint.storyIds.length}`;
                    }).join('\n');
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `📋 **Sprints** (${sprints.length} total)\n\n${sprintsList}`,
                            },
                        ],
                        structured: {
                            sprints,
                            count: sprints.length,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to list sprints: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'get_sprint': {
                const { sprintId } = args;
                try {
                    const sprint = await agileManager.getSprint(sprintId);
                    if (!sprint) {
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: `❌ Sprint not found: ${sprintId}`,
                                },
                            ],
                            structured: {
                                found: false,
                            },
                        };
                    }
                    const daysElapsed = Math.ceil((new Date().getTime() - sprint.startDate.getTime()) / (1000 * 60 * 60 * 24));
                    const daysRemaining = Math.max(0, Math.ceil((sprint.endDate.getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24)));
                    const progress = sprint.velocity > 0 && sprint.capacity > 0 ? Math.round((sprint.velocity / sprint.capacity) * 100) : 0;
                    // Get epic IDs for stories in this sprint
                    const epicIds = [];
                    if (sprint.storyIds.length > 0) {
                        for (const storyId of sprint.storyIds) {
                            const story = await agileManager.getStory(storyId);
                            if (story && story.epic && !epicIds.includes(story.epic)) {
                                epicIds.push(story.epic);
                            }
                        }
                    }
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `📋 **Sprint Details**

**Name**: ${sprint.name}
**ID**: ${sprint.id}
**Status**: ${sprint.status}
**Goal**: ${sprint.goal}

📅 **Timeline**
• Start: ${sprint.startDate.toLocaleDateString()}
• End: ${sprint.endDate.toLocaleDateString()}
• Duration: ${sprint.duration} days
• Days elapsed: ${daysElapsed}
• Days remaining: ${daysRemaining}

👥 **Team** (${sprint.team.length} members)
${sprint.team.length > 0 ? sprint.team.map(member => `• ${member}`).join('\n') : '• No team assigned'}

📊 **Metrics**
• Capacity: ${sprint.capacity} story points
• Velocity: ${sprint.velocity} story points
• Progress: ${progress}%
• Stories: ${sprint.storyIds.length}
• Epics: ${epicIds.length}

🔗 **Attached Epic IDs** (${epicIds.length})
${epicIds.length > 0 ? epicIds.map(epicId => `• ${epicId}`).join('\n') : '• No epics attached'}

📖 **Story IDs** (${sprint.storyIds.length})
${sprint.storyIds.length > 0 ? sprint.storyIds.map(storyId => `• ${storyId}`).join('\n') : '• No stories assigned'}

🏃 **Status**: ${sprint.status === 'active' ? '🟢 Active' : sprint.status === 'completed' ? '✅ Completed' : sprint.status === 'planning' ? '📝 Planning' : '❌ Cancelled'}`,
                            },
                        ],
                        structured: {
                            sprint,
                            epicIds,
                            found: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to get sprint: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'list_epics': {
                const { status, owner, } = args;
                try {
                    const epics = await agileManager.getEpics({ status, owner });
                    if (epics.length === 0) {
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: '📚 No epics found\n\nCreate your first epic with `create_epic` or `create_epic_interactive`',
                                },
                            ],
                            structured: {
                                epics: [],
                                count: 0,
                            },
                        };
                    }
                    const epicsList = epics.map((epic) => {
                        const owner = epic.owner || 'Unassigned';
                        return `Epic ID: ${epic.id} | ${epic.title} (${epic.status}) | ${epic.priority} | ${owner} | Progress: ${epic.progress}% | Stories: ${epic.storyIds.length}`;
                    }).join('\n');
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `📚 **Epics** (${epics.length} total)\n\n${epicsList}`,
                            },
                        ],
                        structured: {
                            epics,
                            count: epics.length,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to list epics: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'get_epic': {
                const { epicId } = args;
                try {
                    const epic = await agileManager.getEpic(epicId);
                    if (!epic) {
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: `❌ Epic not found: ${epicId}`,
                                },
                            ],
                            structured: {
                                found: false,
                            },
                        };
                    }
                    const daysSinceCreation = Math.ceil((new Date().getTime() - epic.createdAt.getTime()) / (1000 * 60 * 60 * 24));
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `📚 **Epic Details**

**Title**: ${epic.title}
**ID**: ${epic.id}
**Status**: ${epic.status}
**Priority**: ${epic.priority}

📝 **Description**
${epic.description}

🎯 **Goals** (${epic.goals.length})
${epic.goals.length > 0 ? epic.goals.map((goal, i) => `${i + 1}. ${goal}`).join('\n') : 'No goals defined'}

👤 **Owner**: ${epic.owner || 'Unassigned'}
📊 **Progress**: ${epic.progress}%
📖 **Stories**: ${epic.storyIds.length}

📖 **Attached Story IDs** (${epic.storyIds.length})
${epic.storyIds.length > 0 ? epic.storyIds.map(storyId => `• ${storyId}`).join('\n') : '• No stories attached'}

📅 **Timeline**
• Created: ${epic.createdAt.toLocaleDateString()} (${daysSinceCreation} days ago)
• Updated: ${epic.updatedAt.toLocaleDateString()}

${epic.metadata ? `📋 **Metadata**
• Estimated Effort: ${epic.metadata.estimatedEffort || 'Not estimated'}
• Business Value: ${epic.metadata.businessValue || 'Not defined'}
• Target Users: ${epic.metadata.targetUsers || 'Not defined'}
• Risks: ${epic.metadata.risks || 'None identified'}
${epic.metadata.hasDependencies ? `• Dependencies: ${epic.metadata.dependencyDetails || 'Yes'}` : ''}` : ''}

🏷️ **Status**: ${epic.status === 'active' ? '🟢 Active' : epic.status === 'completed' ? '✅ Completed' : epic.status === 'planned' ? '📝 Planned' : '❌ Cancelled'}`,
                            },
                        ],
                        structured: {
                            epic,
                            storyIds: epic.storyIds,
                            found: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to get epic: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'get_story': {
                const { storyId } = args;
                try {
                    const story = await agileManager.getStory(storyId);
                    if (!story) {
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: `❌ Story not found: ${storyId}`,
                                },
                            ],
                            structured: {
                                found: false,
                            },
                        };
                    }
                    const daysSinceCreation = Math.ceil((new Date().getTime() - story.createdAt.getTime()) / (1000 * 60 * 60 * 24));
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `📖 **Story Details**

**Title**: ${story.title}
**ID**: ${story.id}
**Status**: ${story.status}
**Priority**: ${story.priority}

📝 **Description**
${story.description}

📊 **Metrics**
• Story Points: ${story.storyPoints}
• Hours Spent: ${story.hoursSpent}
${story.timeTracking ? `• Estimated: ${story.timeTracking.estimated}h | Actual: ${story.timeTracking.actual}h | Remaining: ${story.timeTracking.remaining}h` : ''}

✅ **Acceptance Criteria** (${story.acceptanceCriteria?.length || 0})
${story.acceptanceCriteria && story.acceptanceCriteria.length > 0 ? story.acceptanceCriteria.map((ac, i) => typeof ac === 'string' ? `${i + 1}. ${ac}` : `${i + 1}. ${ac.description} [${ac.status}]`).join('\n') : 'No acceptance criteria defined'}

📋 **Assignment**
• Assignee: ${story.assignee || 'Unassigned'}
• Epic: ${story.epic || 'No epic'}
• Sprint: ${story.sprintId || 'Backlog'}

🏷️ **Tags**: ${story.tags && story.tags.length > 0 ? story.tags.join(', ') : 'No tags'}

📅 **Timeline**
• Created: ${story.createdAt.toLocaleDateString()} (${daysSinceCreation} days ago)
• Updated: ${story.updatedAt.toLocaleDateString()}
${story.dueDate ? `• Due: ${story.dueDate.toLocaleDateString()}` : ''}
${story.completedAt ? `• Completed: ${story.completedAt.toLocaleDateString()}` : ''}

${story.dependencies && story.dependencies.length > 0 ? `🔗 **Dependencies** (${story.dependencies.length})
${story.dependencies.map(dep => `• ${dep.type}: ${dep.targetId}`).join('\n')}` : ''}

${story.blockedReason ? `🚧 **Blocked**: ${story.blockedReason}` : ''}

📊 **Status**: ${story.status === 'done' ? '✅ Done' : story.status === 'in_progress' ? '🔄 In Progress' : story.status === 'blocked' ? '🚧 Blocked' : story.status === 'todo' ? '📝 To Do' : `📋 ${story.status}`}`,
                            },
                        ],
                        structured: {
                            story,
                            found: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to get story: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'get_agile_sprint': {
                // Alias for get_sprint - redirect to the same logic
                const { sprintId } = args;
                // Copy the same logic from get_sprint case
                try {
                    const sprint = await agileManager.getSprint(sprintId);
                    if (!sprint) {
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: `❌ Sprint not found: ${sprintId}`,
                                },
                            ],
                            structured: {
                                found: false,
                            },
                        };
                    }
                    const daysElapsed = Math.ceil((new Date().getTime() - sprint.startDate.getTime()) / (1000 * 60 * 60 * 24));
                    const daysRemaining = Math.max(0, Math.ceil((sprint.endDate.getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24)));
                    const progress = sprint.velocity > 0 && sprint.capacity > 0 ? Math.round((sprint.velocity / sprint.capacity) * 100) : 0;
                    // Get epic IDs for stories in this sprint
                    const epicIds = [];
                    if (sprint.storyIds.length > 0) {
                        for (const storyId of sprint.storyIds) {
                            const story = await agileManager.getStory(storyId);
                            if (story && story.epic && !epicIds.includes(story.epic)) {
                                epicIds.push(story.epic);
                            }
                        }
                    }
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `📋 **Sprint Details**

**Name**: ${sprint.name}
**ID**: ${sprint.id}
**Status**: ${sprint.status}
**Goal**: ${sprint.goal}

📅 **Timeline**
• Start: ${sprint.startDate.toLocaleDateString()}
• End: ${sprint.endDate.toLocaleDateString()}
• Duration: ${sprint.duration} days
• Days elapsed: ${daysElapsed}
• Days remaining: ${daysRemaining}

👥 **Team** (${sprint.team.length} members)
${sprint.team.length > 0 ? sprint.team.map(member => `• ${member}`).join('\n') : '• No team assigned'}

📊 **Metrics**
• Capacity: ${sprint.capacity} story points
• Velocity: ${sprint.velocity} story points
• Progress: ${progress}%
• Stories: ${sprint.storyIds.length}
• Epics: ${epicIds.length}

🔗 **Attached Epic IDs** (${epicIds.length})
${epicIds.length > 0 ? epicIds.map(epicId => `• ${epicId}`).join('\n') : '• No epics attached'}

📖 **Story IDs** (${sprint.storyIds.length})
${sprint.storyIds.length > 0 ? sprint.storyIds.map(storyId => `• ${storyId}`).join('\n') : '• No stories assigned'}

🏃 **Status**: ${sprint.status === 'active' ? '🟢 Active' : sprint.status === 'completed' ? '✅ Completed' : sprint.status === 'planning' ? '📝 Planning' : '❌ Cancelled'}`,
                            },
                        ],
                        structured: {
                            sprint,
                            epicIds,
                            found: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to get sprint: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'get_agile_epic': {
                // Alias for get_epic - redirect to the same logic
                const { epicId } = args;
                // Copy the same logic from get_epic case
                try {
                    const epic = await agileManager.getEpic(epicId);
                    if (!epic) {
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: `❌ Epic not found: ${epicId}`,
                                },
                            ],
                            structured: {
                                found: false,
                            },
                        };
                    }
                    const daysSinceCreation = Math.ceil((new Date().getTime() - epic.createdAt.getTime()) / (1000 * 60 * 60 * 24));
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `📚 **Epic Details**

**Title**: ${epic.title}
**ID**: ${epic.id}
**Status**: ${epic.status}
**Priority**: ${epic.priority}

📝 **Description**
${epic.description}

🎯 **Goals** (${epic.goals.length})
${epic.goals.length > 0 ? epic.goals.map((goal, i) => `${i + 1}. ${goal}`).join('\n') : 'No goals defined'}

👤 **Owner**: ${epic.owner || 'Unassigned'}
📊 **Progress**: ${epic.progress}%
📖 **Stories**: ${epic.storyIds.length}

📖 **Attached Story IDs** (${epic.storyIds.length})
${epic.storyIds.length > 0 ? epic.storyIds.map(storyId => `• ${storyId}`).join('\n') : '• No stories attached'}

📅 **Timeline**
• Created: ${epic.createdAt.toLocaleDateString()} (${daysSinceCreation} days ago)
• Updated: ${epic.updatedAt.toLocaleDateString()}

${epic.metadata ? `📋 **Metadata**
• Estimated Effort: ${epic.metadata.estimatedEffort || 'Not estimated'}
• Business Value: ${epic.metadata.businessValue || 'Not defined'}
• Target Users: ${epic.metadata.targetUsers || 'Not defined'}
• Risks: ${epic.metadata.risks || 'None identified'}
${epic.metadata.hasDependencies ? `• Dependencies: ${epic.metadata.dependencyDetails || 'Yes'}` : ''}` : ''}

🏷️ **Status**: ${epic.status === 'active' ? '🟢 Active' : epic.status === 'completed' ? '✅ Completed' : epic.status === 'planned' ? '📝 Planned' : '❌ Cancelled'}`,
                            },
                        ],
                        structured: {
                            epic,
                            storyIds: epic.storyIds,
                            found: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to get epic: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            default:
                return null;
        }
    });
    return {
        agileManager, // Return the manager instance for dashboard integration
        tools: [
            {
                name: 'create_agile_sprint',
                description: 'Create a new agile sprint with specified goals and timeline. Use this when starting a new development iteration with defined scope and timeframe. Requires active project with backlog items. Returns sprint details with unique ID for tracking.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        name: {
                            type: 'string',
                            description: 'Sprint name or identifier',
                            minLength: 1,
                            maxLength: 100,
                            pattern: '^[a-zA-Z0-9 _-]+$'
                        },
                        goal: {
                            type: 'string',
                            description: 'Sprint goal or objective',
                            minLength: 10,
                            maxLength: 500
                        },
                        duration: {
                            type: 'number',
                            default: 14,
                            description: 'Sprint duration in days',
                            minimum: 1,
                            maximum: 30
                        },
                        startDate: {
                            type: 'string',
                            description: 'Sprint start date in ISO format (YYYY-MM-DD)',
                            format: 'date'
                        },
                        team: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Team members assigned to sprint'
                        },
                    },
                    required: ['name', 'goal'],
                },
            },
            {
                name: 'create_sprint_interactive',
                description: 'Plan a sprint through an interactive wizard that guides you through capacity planning, goal setting, and story selection',
                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: 'add_story',
                description: 'Add a user story to the backlog or sprint',
                inputSchema: {
                    type: 'object',
                    properties: {
                        title: {
                            type: 'string',
                            description: 'Story title or summary',
                            minLength: 5,
                            maxLength: 150
                        },
                        description: {
                            type: 'string',
                            description: 'Detailed story description with user story format recommended (As a... I want... So that...)',
                            minLength: 20,
                            maxLength: 1000
                        },
                        storyPoints: {
                            type: 'number',
                            default: 0,
                            description: 'Story complexity in Fibonacci points (0, 1, 2, 3, 5, 8, 13, 21)',
                            enum: [0, 1, 2, 3, 5, 8, 13, 21]
                        },
                        priority: {
                            type: 'string',
                            enum: ['low', 'medium', 'high', 'critical'],
                            default: 'medium',
                            description: 'Story priority'
                        },
                        acceptanceCriteria: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Acceptance criteria for the story'
                        },
                        epic: {
                            type: 'string',
                            description: 'Epic this story belongs to'
                        },
                        assignee: {
                            type: 'string',
                            description: 'Team member assigned to the story'
                        },
                        sprintId: {
                            type: 'string',
                            description: 'Sprint to add the story to (optional)'
                        },
                    },
                    required: ['title', 'description'],
                },
            },
            {
                name: 'create_epic',
                description: 'Create an epic to group related user stories',
                inputSchema: {
                    type: 'object',
                    properties: {
                        title: {
                            type: 'string',
                            description: 'Epic title'
                        },
                        description: {
                            type: 'string',
                            description: 'Epic description and scope'
                        },
                        goals: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Epic goals and objectives'
                        },
                        priority: {
                            type: 'string',
                            enum: ['low', 'medium', 'high', 'critical'],
                            default: 'medium',
                            description: 'Epic priority'
                        },
                        owner: {
                            type: 'string',
                            description: 'Epic owner or product manager'
                        },
                    },
                    required: ['title', 'description'],
                },
            },
            {
                name: 'create_epic_interactive',
                description: 'Create an epic through an interactive wizard that guides you through business context, success criteria, and planning',
                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: 'conduct_sprint_planning',
                description: 'Conduct an interactive sprint planning session to select and estimate backlog items. Use this at the beginning of each sprint cycle to establish sprint goals and commitment. Requires existing product backlog and defined team capacity.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        sprintId: {
                            type: 'string',
                            description: 'Sprint ID for planning session'
                        },
                        attendees: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Planning session attendees'
                        },
                        capacity: {
                            type: 'number',
                            description: 'Team capacity in story points'
                        },
                        commitments: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Story IDs committed to the sprint'
                        },
                    },
                    required: ['sprintId'],
                },
            },
            {
                name: 'record_daily_standup',
                description: 'Record daily standup meeting outcomes including progress, blockers, and next steps. Use this daily during active sprints to track team progress and identify impediments. Requires active sprint.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        sprintId: {
                            type: 'string',
                            description: 'Current sprint ID'
                        },
                        attendee: {
                            type: 'string',
                            description: 'Team member providing update'
                        },
                        yesterday: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'What was accomplished yesterday'
                        },
                        today: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'What will be worked on today'
                        },
                        blockers: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Current blockers or impediments'
                        },
                    },
                    required: ['sprintId', 'attendee'],
                },
            },
            {
                name: 'conduct_sprint_retrospective',
                description: 'Conduct sprint retrospective to analyze what went well, what could be improved, and identify actionable improvements. Use this at the end of each sprint to drive continuous improvement. Requires completed sprint.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        sprintId: {
                            type: 'string',
                            description: 'Sprint ID for retrospective'
                        },
                        attendees: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Retrospective attendees'
                        },
                        whatWentWell: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'What went well during the sprint'
                        },
                        whatCanImprove: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'What can be improved'
                        },
                        actionItems: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Action items for next sprint'
                        },
                    },
                    required: ['sprintId'],
                },
            },
            {
                name: 'update_story_status',
                description: 'Update the status of a user story',
                inputSchema: {
                    type: 'object',
                    properties: {
                        storyId: {
                            type: 'string',
                            description: 'Story ID to update'
                        },
                        status: {
                            type: 'string',
                            enum: ['todo', 'in_progress', 'review', 'testing', 'done'],
                            description: 'New story status'
                        },
                        hoursSpent: {
                            type: 'number',
                            description: 'Hours spent on the story'
                        },
                        notes: {
                            type: 'string',
                            description: 'Update notes or comments'
                        },
                        groomedWithUserFeedback: {
                            type: 'boolean',
                            description: 'Whether the story has been groomed with user feedback'
                        },
                    },
                    required: ['storyId', 'status'],
                },
            },
            {
                name: 'assign_story_to_sprint',
                description: 'Assign a user story to a sprint. Use this to add stories to sprints after creation or move stories between sprints.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        storyId: {
                            type: 'string',
                            description: 'ID of the story to assign'
                        },
                        sprintId: {
                            type: 'string',
                            description: 'ID of the sprint to assign the story to'
                        },
                    },
                    required: ['storyId', 'sprintId'],
                },
            },
            {
                name: 'generate_burndown_chart',
                description: 'Generate burndown chart for a sprint',
                inputSchema: {
                    type: 'object',
                    properties: {
                        sprintId: {
                            type: 'string',
                            description: 'Sprint ID for burndown chart'
                        },
                    },
                    required: ['sprintId'],
                },
            },
            {
                name: 'generate_velocity_report',
                description: 'Generate team velocity report showing story points completed over time and trend analysis. Use this to track team performance and aid in future sprint planning. Requires multiple completed sprints for meaningful metrics.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        teamName: {
                            type: 'string',
                            description: 'Team name for velocity report'
                        },
                        lastNSprints: {
                            type: 'number',
                            default: 5,
                            description: 'Number of recent sprints to analyze'
                        },
                    },
                    required: [],
                },
            },
            {
                name: 'get_sprint_status',
                description: 'Get current sprint status and progress',
                inputSchema: {
                    type: 'object',
                    properties: {
                        sprintId: {
                            type: 'string',
                            description: 'Sprint ID (optional - gets current sprint if not provided)'
                        },
                    },
                    required: [],
                },
            },
            {
                name: 'list_agile_backlog',
                description: 'List all product backlog items with priorities, estimates, and acceptance criteria. Use this to review and manage the product backlog during planning activities. Returns prioritized list of user stories with filtering options.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        epic: {
                            type: 'string',
                            description: 'Filter by epic'
                        },
                        priority: {
                            type: 'string',
                            enum: ['low', 'medium', 'high', 'critical'],
                            description: 'Filter by priority'
                        },
                        assignee: {
                            type: 'string',
                            description: 'Filter by assignee'
                        },
                        status: {
                            type: 'string',
                            enum: ['todo', 'in_progress', 'review', 'testing', 'done'],
                            default: 'todo',
                            description: 'Filter by status'
                        },
                    },
                    required: [],
                },
            },
            {
                name: 'update_epic',
                description: 'Update an existing epic\'s details',
                inputSchema: {
                    type: 'object',
                    properties: {
                        epicId: {
                            type: 'string',
                            description: 'ID of the epic to update'
                        },
                        title: {
                            type: 'string',
                            description: 'New epic title'
                        },
                        description: {
                            type: 'string',
                            description: 'New epic description'
                        },
                        status: {
                            type: 'string',
                            enum: ['planned', 'active', 'completed', 'cancelled'],
                            description: 'New epic status'
                        },
                        priority: {
                            type: 'string',
                            enum: ['low', 'medium', 'high', 'critical'],
                            description: 'New epic priority'
                        },
                        goals: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Updated epic goals'
                        },
                        owner: {
                            type: 'string',
                            description: 'New epic owner'
                        },
                        metadata: {
                            type: 'object',
                            description: 'Additional metadata for the epic',
                            properties: {
                                estimatedEffort: { type: 'string' },
                                hasDependencies: { type: 'boolean' },
                                dependencyDetails: { type: 'string' },
                                risks: { type: 'string' },
                                targetUsers: { type: 'string' },
                                businessValue: { type: 'string' },
                            }
                        },
                    },
                    required: ['epicId'],
                },
            },
            {
                name: 'update_sprint',
                description: 'Update an existing sprint\'s details',
                inputSchema: {
                    type: 'object',
                    properties: {
                        sprintId: {
                            type: 'string',
                            description: 'ID of the sprint to update'
                        },
                        name: {
                            type: 'string',
                            description: 'New sprint name'
                        },
                        goal: {
                            type: 'string',
                            description: 'New sprint goal'
                        },
                        status: {
                            type: 'string',
                            enum: ['planning', 'active', 'completed', 'cancelled'],
                            description: 'New sprint status'
                        },
                        endDate: {
                            type: 'string',
                            description: 'New sprint end date (ISO format)'
                        },
                        team: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Updated team members'
                        },
                        capacity: {
                            type: 'number',
                            description: 'Updated team capacity in story points'
                        },
                    },
                    required: ['sprintId'],
                },
            },
            {
                name: 'list_agile_sprints',
                description: 'List all sprints with their status, goals, and key metrics. Use this to review sprint history and analyze team performance trends. Returns chronological list of sprints with completion data and filtering options.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        status: {
                            type: 'string',
                            enum: ['planning', 'active', 'completed', 'cancelled'],
                            description: 'Filter by sprint status'
                        },
                        includeCompleted: {
                            type: 'boolean',
                            default: true,
                            description: 'Include completed sprints in results'
                        },
                    },
                    required: [],
                },
            },
            {
                name: 'get_sprint',
                description: 'Get detailed information about a specific sprint',
                inputSchema: {
                    type: 'object',
                    properties: {
                        sprintId: {
                            type: 'string',
                            description: 'ID of the sprint to retrieve'
                        },
                    },
                    required: ['sprintId'],
                },
            },
            {
                name: 'list_epics',
                description: 'List all epics with optional filtering',
                inputSchema: {
                    type: 'object',
                    properties: {
                        status: {
                            type: 'string',
                            enum: ['planned', 'active', 'completed', 'cancelled'],
                            description: 'Filter by epic status'
                        },
                        owner: {
                            type: 'string',
                            description: 'Filter by epic owner'
                        },
                    },
                    required: [],
                },
            },
            {
                name: 'get_epic',
                description: 'Get detailed information about a specific epic',
                inputSchema: {
                    type: 'object',
                    properties: {
                        epicId: {
                            type: 'string',
                            description: 'ID of the epic to retrieve'
                        },
                    },
                    required: ['epicId'],
                },
            },
            {
                name: 'get_story',
                description: 'Get detailed information about a specific user story',
                inputSchema: {
                    type: 'object',
                    properties: {
                        storyId: {
                            type: 'string',
                            description: 'ID of the story to retrieve'
                        },
                    },
                    required: ['storyId'],
                },
            },
            {
                name: 'get_agile_sprint',
                description: 'Get detailed information about a specific sprint including attached epic IDs',
                inputSchema: {
                    type: 'object',
                    properties: {
                        sprintId: {
                            type: 'string',
                            description: 'ID of the sprint to retrieve'
                        },
                    },
                    required: ['sprintId'],
                },
            },
            {
                name: 'get_agile_epic',
                description: 'Get detailed information about a specific epic including attached story IDs',
                inputSchema: {
                    type: 'object',
                    properties: {
                        epicId: {
                            type: 'string',
                            description: 'ID of the epic to retrieve'
                        },
                    },
                    required: ['epicId'],
                },
            },
        ],
        resources: [
            {
                uri: 'agile://sprints/current',
                name: 'Current Sprint',
                description: 'Information about the current active sprint',
                mimeType: 'application/json',
            },
            {
                uri: 'agile://backlog/items',
                name: 'Product Backlog',
                description: 'Current product backlog items',
                mimeType: 'application/json',
            },
            {
                uri: 'agile://reports/velocity',
                name: 'Team Velocity',
                description: 'Team velocity metrics and trends',
                mimeType: 'application/json',
            },
        ],
    };
}
function formatSprintPlanning(planning) {
    return `📋 Sprint Planning Session

🏃 **Sprint**: ${planning.sprintId}
📅 **Date**: ${planning.date.toLocaleDateString()}
👥 **Attendees**: ${planning.attendees.join(', ')}

⚡ **Team Capacity**: ${planning.capacity} story points
📊 **Stories Committed**: ${planning.commitments.length}

🎯 **Sprint Commitments**:
${planning.commitments.map((commitment, i) => `${i + 1}. ${commitment}`).join('\n')}

📝 **Planning Notes**:
${planning.notes || 'No additional notes'}

✅ **Planning Outcome**: Ready to start sprint!`;
}
function formatStandupReport(standup) {
    return `🕘 Daily Standup Report

👤 **Team Member**: ${standup.attendee}
📅 **Date**: ${standup.date.toLocaleDateString()}
🏃 **Sprint**: ${standup.sprintId}

✅ **Yesterday's Accomplishments**:
${standup.yesterday.length > 0 ? standup.yesterday.map(item => `• ${item}`).join('\n') : '• No items reported'}

🎯 **Today's Plan**:
${standup.today.length > 0 ? standup.today.map(item => `• ${item}`).join('\n') : '• No items planned'}

🚧 **Blockers/Impediments**:
${standup.blockers.length > 0 ? standup.blockers.map(blocker => `• ${blocker}`).join('\n') : '• No blockers reported'}`;
}
function formatRetrospective(retro) {
    return `🔄 Sprint Retrospective

🏃 **Sprint**: ${retro.sprintId}
📅 **Date**: ${retro.date.toLocaleDateString()}
👥 **Attendees**: ${retro.attendees.join(', ')}

✅ **What Went Well**:
${retro.whatWentWell.map(item => `• ${item}`).join('\n')}

⚠️ **What Can Be Improved**:
${retro.whatCanImprove.map(item => `• ${item}`).join('\n')}

🎯 **Action Items**:
${retro.actionItems.map((item, i) => `${i + 1}. ${item}`).join('\n')}

📊 **Overall Sprint Rating**: ${retro.sprintRating || 'Not rated'}/10`;
}
function formatBurndownChart(burndown) {
    return `📈 Sprint Burndown Chart

🏃 **Sprint**: ${burndown.sprintId}
📊 **Total Story Points**: ${burndown.totalStoryPoints}
📅 **Sprint Days**: ${burndown.sprintDays}

📉 **Daily Progress**:
${burndown.dailyData.map(day => `Day ${day.day}: ${day.remainingPoints} points remaining (${day.completedPoints} completed)`).join('\n')}

🎯 **Current Status**:
• Progress: ${Math.round((burndown.completedPoints / burndown.totalStoryPoints) * 100)}%
• On Track: ${burndown.onTrack ? '✅' : '⚠️'}
• Days Remaining: ${burndown.daysRemaining}

${burndown.trend ? `📊 **Trend**: ${burndown.trend}` : ''}`;
}
function formatVelocityReport(report) {
    return `⚡ Team Velocity Report

👥 **Team**: ${report.teamName || 'Default Team'}
📊 **Sprints Analyzed**: ${report.sprintsAnalyzed}
📅 **Period**: ${report.periodStart.toLocaleDateString()} - ${report.periodEnd.toLocaleDateString()}

📈 **Velocity Metrics**:
• Average Velocity: ${report.averageVelocity} story points
• Highest Velocity: ${report.highestVelocity} points
• Lowest Velocity: ${report.lowestVelocity} points
• Velocity Trend: ${report.trend}

📊 **Sprint-by-Sprint Breakdown**:
${report.sprintData.map(sprint => `Sprint ${sprint.sprintName}: ${sprint.velocity} points (${sprint.completionRate}% completion)`).join('\n')}

🎯 **Insights**:
${report.insights.map(insight => `• ${insight}`).join('\n')}

💡 **Recommendations**:
${report.recommendations.map(rec => `• ${rec}`).join('\n')}`;
}
function formatSprintStatus(status) {
    return `🏃 Sprint Status Report

📋 **Sprint**: ${status.sprint.name}
🎯 **Goal**: ${status.sprint.goal}
📅 **Timeline**: ${status.sprint.startDate.toLocaleDateString()} - ${status.sprint.endDate.toLocaleDateString()}
📊 **Status**: ${status.sprint.status}

📈 **Progress Overview**:
• Total Stories: ${status.totalStories}
• Completed: ${status.completedStories} (${Math.round((status.completedStories / status.totalStories) * 100)}%)
• In Progress: ${status.inProgressStories}
• Remaining: ${status.remainingStories}

⭐ **Story Points**:
• Total: ${status.totalStoryPoints}
• Completed: ${status.completedStoryPoints}
• Remaining: ${status.remainingStoryPoints}

🎯 **Sprint Health**: ${status.sprintHealth}
${status.blockers.length > 0 ? `🚧 **Active Blockers**: ${status.blockers.length}` : '✅ No blockers reported'}

🔥 **Team Velocity**: ${status.currentVelocity} points/day`;
}
function formatBacklog(backlog) {
    if (backlog.length === 0) {
        return '📋 Product Backlog is empty\n\nStart by adding user stories to build your product roadmap.';
    }
    const storiesList = backlog.map((story) => {
        const assignee = story.assignee || 'Unassigned';
        const epicRef = story.epic || 'No epic';
        return `Story ID: ${story.id} | ${story.title} (${story.storyPoints} pts) | ${story.priority} | ${story.status} | ${assignee} | ${epicRef}`;
    }).join('\n');
    const totalPoints = backlog.reduce((sum, story) => sum + story.storyPoints, 0);
    const highPriorityCount = backlog.filter(s => s.priority === 'high' || s.priority === 'critical').length;
    const unassignedCount = backlog.filter(s => !s.assignee).length;
    return `📋 Product Backlog (${backlog.length} items)

${storiesList}

💡 **Backlog Health**: Total Points: ${totalPoints} | High Priority: ${highPriorityCount} | Unassigned: ${unassignedCount}`;
}
//# sourceMappingURL=index.js.map