import { KanbanDataStore } from './store.js';
import { BoardSetupWizard } from './board-setup-wizard.js';
import { CallToolRequestSchema, ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
let kanbanStore;
let boardSetupWizard;
export async function setupKanbanTools(server, configManager) {
    kanbanStore = new KanbanDataStore(configManager);
    boardSetupWizard = new BoardSetupWizard();
    await kanbanStore.init();
    // Add kanban-specific tool handlers
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
        const { name, arguments: args } = request.params;
        if (!args) {
            throw new Error('No arguments provided');
        }
        switch (name) {
            case 'create_kanban_board': {
                const { name: boardName, columns } = args;
                const board = kanbanStore.createBoard(boardName, columns);
                await kanbanStore.save();
                return {
                    content: [
                        {
                            type: 'text',
                            text: `✅ Kanban board "${board.name}" created with columns: ${board.columns.join(', ')}\nBoard ID: ${board.id}`,
                        },
                    ],
                    structured: {
                        board: {
                            id: board.id,
                            name: board.name,
                            columns: board.columns,
                            created: board.createdAt.toISOString(),
                        },
                        metadata: {
                            version: '1.0.0',
                            capabilities: ['tasks', 'columns', 'priorities'],
                        },
                    },
                };
            }
            case 'create_board_interactive': {
                const { action, workflowId, response } = args;
                try {
                    if (action === 'start') {
                        const workflow = boardSetupWizard.startBoardSetup();
                        const currentStep = boardSetupWizard.formatCurrentStep(workflow.id);
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: `🚀 Starting Interactive Kanban Board Setup Wizard

This wizard will help you create a Kanban board optimized for your team's workflow and needs.

${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 boardSetupWizard.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 boardData = boardSetupWizard.completeWorkflow(workflowId);
                            if (boardData) {
                                // Create the board
                                const board = kanbanStore.createBoard(boardData.name, boardData.columns);
                                // Add initial tags if specified
                                if (boardData.initialTags && boardData.initialTags.length > 0) {
                                    // Store tags in board metadata (would need to extend the Board type)
                                    // For now, we'll include them in the response
                                }
                                await kanbanStore.save();
                                return {
                                    content: [
                                        {
                                            type: 'text',
                                            text: `✅ Kanban board created successfully through interactive wizard!

📋 **Board**: ${board.name}
🔄 **Workflow Type**: ${boardData.workflowType}
👥 **Team Size**: ${boardData.teamSize}

**Columns**: ${board.columns.join(' → ')}

**Configuration**:
• Work Item Types: ${boardData.workItemTypes.join(', ')}
• Priority Levels: ${boardData.priorityLevels}
• WIP Limits: ${boardData.useWipLimits ? `${boardData.wipLimitPerPerson} items per person` : 'Disabled'}
• Tags: ${boardData.useTags ? 'Enabled' : 'Disabled'}
${boardData.initialTags.length > 0 ? `• Initial Tags: ${boardData.initialTags.join(', ')}` : ''}

**Automation**: ${boardData.automationPreference}

**Board ID**: ${board.id}

💡 Your Kanban board is ready! You can now:
- Add tasks to start tracking work
- Move tasks between columns
- Use tags to categorize items
- Monitor team workflow and bottlenecks`,
                                        },
                                    ],
                                    structured: {
                                        board,
                                        boardData,
                                        created: true,
                                        createdVia: 'interactive-wizard',
                                    },
                                };
                            }
                        }
                        // Continue to next step
                        const currentStep = boardSetupWizard.formatCurrentStep(workflowId);
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: currentStep,
                                },
                            ],
                            structured: {
                                workflowId,
                                action: 'waiting_for_response',
                            },
                        };
                    }
                    if (action === 'cancel' && workflowId) {
                        boardSetupWizard.cancelWorkflow(workflowId);
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: `❌ Board setup wizard cancelled.`,
                                },
                            ],
                            structured: {
                                cancelled: true,
                            },
                        };
                    }
                    throw new Error('Invalid action or missing required parameters');
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Board setup wizard error: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'add_kanban_task': {
                const { title, boardName, description, column, priority, assignee, labels, tags, acceptanceCriteria, dependencies, timeEstimate, watchers } = args;
                const task = kanbanStore.addTask(boardName, {
                    title,
                    description,
                    column: column || 'Backlog',
                    priority: priority || 'medium',
                    assignee,
                    tags: tags || labels || [], // Support both tags and labels for compatibility
                    acceptanceCriteria: acceptanceCriteria?.map((ac, index) => ({
                        id: `ac-${Date.now()}-${index}`,
                        description: ac.description,
                        status: 'pending',
                    })) || [],
                    dependencies: dependencies?.map((dep) => ({
                        id: `dep-${Date.now()}-${Math.random()}`,
                        type: dep.type || 'relates_to',
                        targetId: dep.taskId || dep.targetId,
                        targetType: 'task',
                        createdAt: new Date(),
                    })) || [],
                    timeTracking: timeEstimate ? {
                        estimated: timeEstimate,
                        actual: 0,
                        remaining: timeEstimate,
                        logs: []
                    } : undefined,
                    watchers: watchers || [],
                    attachments: [],
                    comments: [],
                    customFields: [],
                    subtasks: [],
                });
                if (!task) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Board "${boardName}" not found`,
                            },
                        ],
                    };
                }
                await kanbanStore.save();
                const board = kanbanStore.getBoard(boardName);
                return {
                    content: [
                        {
                            type: 'text',
                            text: `✅ Task "${task.title}" added to ${boardName} board in ${task.column} column\nTask ID: ${task.id}\nPriority: ${task.priority}`,
                        },
                    ],
                    structured: {
                        task: {
                            id: task.id,
                            title: task.title,
                            boardName: boardName,
                            column: task.column,
                            priority: task.priority,
                            created: task.createdAt.toISOString(),
                        },
                        board: {
                            id: board.id,
                            totalTasks: board.tasks.length,
                        },
                    },
                };
            }
            case 'move_kanban_task': {
                const { boardName, taskId, column } = args;
                const success = kanbanStore.moveTask(boardName, taskId, column);
                if (!success) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to move task. Check board name, task ID, and column name.`,
                            },
                        ],
                    };
                }
                await kanbanStore.save();
                return {
                    content: [
                        {
                            type: 'text',
                            text: `✅ Task moved to ${column} column`,
                        },
                    ],
                };
            }
            case 'list_kanban_boards': {
                const boards = kanbanStore.getAllBoards();
                if (boards.length === 0) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `No Kanban boards found. Create one with the 'create_board' tool.`,
                            },
                        ],
                    };
                }
                const boardList = boards.map(board => `📋 ${board.name} (${board.tasks.length} tasks)\n   Columns: ${board.columns.join(', ')}`).join('\n\n');
                return {
                    content: [
                        {
                            type: 'text',
                            text: `Kanban Boards:\n\n${boardList}`,
                        },
                    ],
                };
            }
            case 'update_kanban_task': {
                const { boardName, taskId, updates } = args;
                const updateObject = { ...updates };
                // Handle acceptance criteria updates
                if (updates.acceptanceCriteria) {
                    const board = kanbanStore.getBoard(boardName);
                    const task = board?.tasks.find(t => t.id === taskId);
                    if (task) {
                        // Merge existing and new acceptance criteria
                        const existingAC = task.acceptanceCriteria || [];
                        updateObject.acceptanceCriteria = updates.acceptanceCriteria.map(ac => {
                            if (ac.id) {
                                // Update existing criterion
                                const existing = existingAC.find(e => e.id === ac.id);
                                return existing ? { ...existing, ...ac } : ac;
                            }
                            else {
                                // New criterion
                                return {
                                    id: `ac-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
                                    description: ac.description,
                                    status: ac.status || 'pending',
                                };
                            }
                        });
                    }
                }
                const success = kanbanStore.updateTask(boardName, taskId, updateObject);
                if (!success) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to update task. Check board name and task ID.`,
                            },
                        ],
                    };
                }
                await kanbanStore.save();
                return {
                    content: [
                        {
                            type: 'text',
                            text: `✅ Task updated successfully`,
                        },
                    ],
                };
            }
            case 'update_kanban_acceptance_criterion': {
                const { boardName, taskId, criterionId, status, verifiedBy } = args;
                const board = kanbanStore.getBoard(boardName);
                const task = board?.tasks.find(t => t.id === taskId);
                if (!task) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Task not found`,
                            },
                        ],
                    };
                }
                const criterion = task.acceptanceCriteria?.find(ac => ac.id === criterionId);
                if (!criterion) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Acceptance criterion not found`,
                            },
                        ],
                    };
                }
                criterion.status = status;
                if (status === 'completed' && verifiedBy) {
                    criterion.verifiedBy = verifiedBy;
                    criterion.verifiedAt = new Date();
                }
                await kanbanStore.save();
                const completedCount = task.acceptanceCriteria?.filter(ac => ac.status === 'completed').length || 0;
                const totalCount = task.acceptanceCriteria?.length || 0;
                return {
                    content: [
                        {
                            type: 'text',
                            text: `✅ Acceptance criterion updated to ${status}\n\nProgress: ${completedCount}/${totalCount} criteria completed`,
                        },
                    ],
                };
            }
            case 'add_kanban_task_comment': {
                const { boardName, taskId, comment, author } = args;
                const board = kanbanStore.getBoard(boardName);
                const task = board?.tasks.find(t => t.id === taskId);
                if (!task) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Task not found`,
                            },
                        ],
                    };
                }
                if (!task.comments) {
                    task.comments = [];
                }
                task.comments.push({
                    id: `comment-${Date.now()}`,
                    userId: author,
                    content: comment,
                    createdAt: new Date(),
                });
                task.updatedAt = new Date();
                await kanbanStore.save();
                return {
                    content: [
                        {
                            type: 'text',
                            text: `✅ Comment added to task`,
                        },
                    ],
                };
            }
            case 'log_kanban_time': {
                const { boardName, taskId, hours, description } = args;
                const board = kanbanStore.getBoard(boardName);
                const task = board?.tasks.find(t => t.id === taskId);
                if (!task) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Task not found`,
                            },
                        ],
                    };
                }
                if (!task.timeTracking) {
                    task.timeTracking = {
                        estimated: 0,
                        actual: 0,
                        remaining: 0,
                        logs: []
                    };
                }
                task.timeTracking.actual = (task.timeTracking.actual || 0) + hours;
                task.timeTracking.remaining = Math.max(0, task.timeTracking.estimated - task.timeTracking.actual);
                if (!task.timeTracking.logs) {
                    task.timeTracking.logs = [];
                }
                task.timeTracking.logs.push({
                    id: `log-${Date.now()}`,
                    userId: 'system',
                    date: new Date(),
                    hours,
                    description,
                });
                task.updatedAt = new Date();
                await kanbanStore.save();
                const remaining = task.timeTracking.estimated
                    ? Math.max(0, task.timeTracking.estimated - task.timeTracking.actual)
                    : undefined;
                return {
                    content: [
                        {
                            type: 'text',
                            text: `✅ Logged ${hours} hours\n\nTime spent: ${task.timeTracking.actual} hours${task.timeTracking.estimated ? `\nTime remaining: ${remaining} hours` : ''}`,
                        },
                    ],
                };
            }
            default:
                // Not a kanban tool, throw to let other handlers try
                throw new Error(`Tool ${name} not handled by kanban module`);
        }
    });
    // Add resource handler for kanban resources
    server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
        const { uri } = request.params;
        if (uri === 'atlas://kanban/boards') {
            const boards = kanbanStore.getAllBoards();
            return {
                contents: [
                    {
                        uri,
                        mimeType: 'application/json',
                        text: JSON.stringify({ boards }, null, 2),
                    },
                ],
            };
        }
        // Match pattern for specific board resources
        const boardMatch = uri.match(/^atlas:\/\/kanban\/board\/(.+)$/);
        if (boardMatch) {
            const boardId = boardMatch[1];
            const board = kanbanStore.getBoard(boardId);
            if (!board) {
                throw new Error(`Board not found: ${boardId}`);
            }
            return {
                contents: [
                    {
                        uri,
                        mimeType: 'application/json',
                        text: JSON.stringify(board, null, 2),
                    },
                ],
            };
        }
        // Not a kanban resource, throw to let other handlers try
        throw new Error(`Resource ${uri} not handled by kanban module`);
    });
    return {
        tools: [
            {
                name: 'create_kanban_board',
                description: 'Create a new Kanban board with customizable columns for visual task management. Use this when setting up project workflows or organizing tasks visually. Returns board details with unique ID for task assignment.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        name: {
                            type: 'string',
                            minLength: 1,
                            maxLength: 50,
                            pattern: '^[a-zA-Z0-9 _-]+$',
                            description: 'Board name (alphanumeric, spaces, hyphens, underscores only)'
                        },
                        columns: {
                            type: 'array',
                            items: { type: 'string' },
                            default: ['Backlog', 'To Do', 'In Progress', 'Review', 'Done']
                        },
                    },
                    required: ['name'],
                },
                outputSchema: {
                    type: 'object',
                    properties: {
                        board: {
                            type: 'object',
                            properties: {
                                id: { type: 'string' },
                                name: { type: 'string' },
                                columns: { type: 'array', items: { type: 'string' } },
                                created: { type: 'string', format: 'date-time' },
                            },
                            required: ['id', 'name', 'columns', 'created'],
                        },
                        metadata: {
                            type: 'object',
                            properties: {
                                version: { type: 'string' },
                                capabilities: { type: 'array', items: { type: 'string' } },
                            },
                            required: ['version', 'capabilities'],
                        },
                    },
                    required: ['board', 'metadata'],
                },
            },
            {
                name: 'create_board_interactive',
                description: 'Create a Kanban board through an interactive wizard that helps you design the perfect workflow for your team',
                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_kanban_task',
                description: 'Add a task to a specific Kanban board with support for acceptance criteria, dependencies, and time tracking. Use this to create trackable work items with detailed requirements. Requires existing board and valid column name.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        boardName: {
                            type: 'string',
                            minLength: 1,
                            maxLength: 50,
                            description: 'Name of the target Kanban board'
                        },
                        title: {
                            type: 'string',
                            minLength: 1,
                            maxLength: 100,
                            description: 'Task title or summary'
                        },
                        description: {
                            type: 'string',
                            minLength: 5,
                            maxLength: 500,
                            description: 'Detailed task description'
                        },
                        column: { type: 'string', default: 'Backlog' },
                        priority: {
                            type: 'string',
                            enum: ['low', 'medium', 'high'],
                            default: 'medium'
                        },
                        assignee: { type: 'string' },
                        labels: { type: 'array', items: { type: 'string' }, description: 'Deprecated: use tags instead' },
                        tags: { type: 'array', items: { type: 'string' }, description: 'Tags to categorize the task' },
                        acceptanceCriteria: {
                            type: 'array',
                            items: {
                                type: 'object',
                                properties: {
                                    description: { type: 'string' }
                                },
                                required: ['description']
                            },
                            description: 'List of acceptance criteria for the task'
                        },
                        dependencies: {
                            type: 'array',
                            items: {
                                type: 'object',
                                properties: {
                                    taskId: { type: 'string' },
                                    type: { type: 'string', enum: ['blocks', 'depends_on'] }
                                },
                                required: ['taskId', 'type']
                            },
                            description: 'Task dependencies'
                        },
                        timeEstimate: { type: 'number', description: 'Estimated time in hours' },
                        watchers: { type: 'array', items: { type: 'string' }, description: 'Users watching this task' },
                    },
                    required: ['boardName', 'title'],
                },
                outputSchema: {
                    type: 'object',
                    properties: {
                        task: {
                            type: 'object',
                            properties: {
                                id: { type: 'string' },
                                title: { type: 'string' },
                                boardName: { type: 'string' },
                                column: { type: 'string' },
                                priority: { type: 'string' },
                                created: { type: 'string', format: 'date-time' },
                            },
                            required: ['id', 'title', 'boardName', 'column', 'priority', 'created'],
                        },
                        board: {
                            type: 'object',
                            properties: {
                                id: { type: 'string' },
                                totalTasks: { type: 'number' },
                            },
                            required: ['id', 'totalTasks'],
                        },
                    },
                    required: ['task', 'board'],
                },
            },
            {
                name: 'move_kanban_task',
                description: 'Move a task between columns on a Kanban board to reflect progress updates. Use this when task status changes or workflow progresses. Requires valid task ID and target column name.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        boardName: { type: 'string' },
                        taskId: { type: 'string' },
                        column: { type: 'string' },
                    },
                    required: ['boardName', 'taskId', 'column'],
                },
            },
            {
                name: 'list_kanban_boards',
                description: 'List all Kanban boards with their column structures and task counts. Use this to review available boards and their current state before adding or managing tasks. Returns comprehensive board overview.',
                inputSchema: {
                    type: 'object',
                    properties: {},
                    required: [],
                },
            },
            {
                name: 'update_kanban_task',
                description: 'Update task properties including tags, acceptance criteria, dependencies, and time tracking. Use this to modify existing tasks without changing their board position. Requires valid task ID and board reference.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        boardName: { type: 'string' },
                        taskId: { type: 'string' },
                        updates: {
                            type: 'object',
                            properties: {
                                title: { type: 'string' },
                                description: { type: 'string' },
                                priority: { type: 'string', enum: ['low', 'medium', 'high'] },
                                assignee: { type: 'string' },
                                tags: { type: 'array', items: { type: 'string' } },
                                acceptanceCriteria: {
                                    type: 'array',
                                    items: {
                                        type: 'object',
                                        properties: {
                                            id: { type: 'string', description: 'ID of existing criterion to update' },
                                            description: { type: 'string' },
                                            status: { type: 'string', enum: ['pending', 'in_progress', 'completed', 'failed'] }
                                        },
                                        required: ['description']
                                    }
                                },
                                dependencies: {
                                    type: 'array',
                                    items: {
                                        type: 'object',
                                        properties: {
                                            taskId: { type: 'string' },
                                            type: { type: 'string', enum: ['blocks', 'depends_on'] }
                                        },
                                        required: ['taskId', 'type']
                                    }
                                },
                                timeTracking: {
                                    type: 'object',
                                    properties: {
                                        estimated: { type: 'number', description: 'Estimated hours' },
                                        spent: { type: 'number', description: 'Hours spent' }
                                    }
                                }
                            }
                        }
                    },
                    required: ['boardName', 'taskId', 'updates'],
                },
            },
            {
                name: 'update_kanban_acceptance_criterion',
                description: 'Update the status of a specific acceptance criterion for a Kanban task. Use this to track completion progress of task requirements. Requires valid criterion ID and status value.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        boardName: { type: 'string' },
                        taskId: { type: 'string' },
                        criterionId: { type: 'string' },
                        status: { type: 'string', enum: ['pending', 'in_progress', 'completed', 'failed'] },
                        verifiedBy: { type: 'string', description: 'User who verified completion' }
                    },
                    required: ['boardName', 'taskId', 'criterionId', 'status'],
                },
            },
            {
                name: 'add_kanban_task_comment',
                description: 'Add a comment to a Kanban task for collaboration and status updates. Use this to document progress, blockers, or discussion points. Requires task identification and author details.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        boardName: { type: 'string' },
                        taskId: { type: 'string' },
                        comment: { type: 'string' },
                        author: { type: 'string' }
                    },
                    required: ['boardName', 'taskId', 'comment', 'author'],
                },
            },
            {
                name: 'log_kanban_time',
                description: 'Log time spent working on a Kanban task for tracking and reporting purposes. Use this to maintain accurate effort records and project estimation data. Requires hours and task identification.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        boardName: { type: 'string' },
                        taskId: { type: 'string' },
                        hours: { type: 'number', description: 'Hours spent' },
                        description: { type: 'string', description: 'Description of work done' }
                    },
                    required: ['boardName', 'taskId', 'hours'],
                },
            },
        ],
        resources: [
            {
                uri: 'atlas://kanban/boards',
                name: 'Kanban Boards',
                description: 'List of all kanban boards in the project',
                mimeType: 'application/json',
            },
        ],
    };
}
//# sourceMappingURL=index.js.map