import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { ConfigManager } from '../../config/config-manager.js';
import { ADRManager } from './adr-manager.js';
import { ADRWizard } from './adr-wizard.js';
import { renderADRTemplate } from './templates.js';
let adrManager;
let adrWizard;
export async function setupADRManagementModule(server, configManager) {
    const config = configManager || new ConfigManager();
    adrManager = new ADRManager(config);
    adrWizard = new ADRWizard(config);
    await adrManager.initialize();
    // Add ADR 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_adr': {
                const { title, template = 'nygard', deciders, context, decision, consequences, tags, decisionDrivers, consideredOptions, prosAndCons, supersedes, relatedTo } = args;
                const adr = await adrManager.createADR({
                    title,
                    template,
                    deciders: Array.isArray(deciders) ? deciders : deciders.split(',').map((d) => d.trim()),
                    context,
                    decision,
                    consequences,
                    tags: tags ? (Array.isArray(tags) ? tags : tags.split(',').map((t) => t.trim())) : undefined,
                    decisionDrivers,
                    consideredOptions,
                    prosAndCons,
                    supersedes,
                    relatedTo
                });
                const markdown = renderADRTemplate(adr);
                return {
                    content: [{
                            type: 'text',
                            text: `✅ ADR created successfully!\n\n` +
                                `📄 **ID**: ${adr.id}\n` +
                                `📝 **Title**: ${adr.title}\n` +
                                `📊 **Status**: ${adr.status}\n` +
                                `🏷️ **Template**: ${adr.template}\n` +
                                `👥 **Deciders**: ${adr.deciders.join(', ')}\n\n` +
                                `---\n\n${markdown}`
                        }],
                    structured: {
                        success: true,
                        adr
                    }
                };
            }
            case 'create_adr_interactive': {
                const sendProgress = (progress) => {
                    // Progress tracking if needed
                };
                if (args.userInput) {
                    return await adrWizard.continueInteractiveADR(server, request, sendProgress, args);
                }
                else {
                    return await adrWizard.startInteractiveADR(server, request, sendProgress);
                }
            }
            case 'update_adr': {
                const { id, status, statusChangeReason, statusChangedBy, title, consequences, tags, supersedes, supersededBy, relatedTo, decisionDrivers, consideredOptions, prosAndCons } = args;
                const updated = await adrManager.updateADR(id, {
                    status,
                    statusChangeReason,
                    statusChangedBy,
                    title,
                    consequences,
                    tags: tags ? (Array.isArray(tags) ? tags : tags.split(',').map((t) => t.trim())) : undefined,
                    supersedes,
                    supersededBy,
                    relatedTo,
                    decisionDrivers,
                    consideredOptions,
                    prosAndCons
                });
                return {
                    content: [{
                            type: 'text',
                            text: `✅ ADR updated successfully!\n\n` +
                                `📄 **ID**: ${updated.id}\n` +
                                `📝 **Title**: ${updated.title}\n` +
                                `📊 **Status**: ${updated.status}\n` +
                                `🔄 **Updated**: ${updated.updatedAt.toISOString()}\n\n` +
                                (updated.statusHistory.length > 0
                                    ? `📜 **Status History**:\n${updated.statusHistory.map(h => `  • ${h.from} → ${h.to} (${h.date.toISOString().split('T')[0]})${h.reason ? `: ${h.reason}` : ''}`).join('\n')}`
                                    : '')
                        }],
                    structured: {
                        success: true,
                        adr: updated
                    }
                };
            }
            case 'link_adrs': {
                const { fromId, toId, relationship = 'related-to' } = args;
                await adrManager.linkADRs(fromId, toId, relationship);
                return {
                    content: [{
                            type: 'text',
                            text: `✅ ADRs linked successfully!\n\n` +
                                `🔗 **Link created**: ${fromId} ${relationship} ${toId}\n\n` +
                                (relationship === 'supersedes'
                                    ? `⚠️ Note: ${toId} has been marked as superseded.`
                                    : '')
                        }],
                    structured: {
                        success: true,
                        from: fromId,
                        to: toId,
                        relationship
                    }
                };
            }
            case 'get_adr': {
                const { id } = args;
                const result = await adrManager.getADR(id);
                if (!result) {
                    return {
                        content: [{
                                type: 'text',
                                text: `❌ ADR not found: ${id}`
                            }],
                        structured: {
                            success: false,
                            error: 'ADR not found'
                        }
                    };
                }
                const { adr, markdown, relationships } = result;
                return {
                    content: [{
                            type: 'text',
                            text: `📄 **${adr.id}: ${adr.title}**\n\n` +
                                `📊 **Status**: ${adr.status}\n` +
                                `📅 **Date**: ${adr.date.toISOString().split('T')[0]}\n` +
                                `👥 **Deciders**: ${adr.deciders.join(', ')}\n` +
                                (adr.tags?.length ? `🏷️ **Tags**: ${adr.tags.join(', ')}\n` : '') +
                                '\n' +
                                (relationships.length > 0
                                    ? `🔗 **Relationships**:\n${relationships.map(r => `  • ${r.type === 'related-to' ? 'Related to' :
                                        r.type === 'supersedes' ? 'Supersedes' :
                                            r.type === 'superseded-by' ? 'Superseded by' : r.type}: ${r.to}`).join('\n')}\n\n`
                                    : '') +
                                `---\n\n${markdown}`
                        }],
                    structured: {
                        success: true,
                        adr,
                        relationships
                    }
                };
            }
            case 'list_adrs': {
                const { status } = args;
                const filter = status ? { status: status } : {};
                const adrs = await adrManager.listADRs(filter);
                if (adrs.length === 0) {
                    return {
                        content: [{
                                type: 'text',
                                text: `No ADRs found${status ? ` with status: ${status}` : ''}.`
                            }],
                        structured: {
                            success: true,
                            adrs: []
                        }
                    };
                }
                const statusEmoji = {
                    proposed: '💡',
                    accepted: '✅',
                    rejected: '❌',
                    deprecated: '⚠️',
                    superseded: '🔄'
                };
                return {
                    content: [{
                            type: 'text',
                            text: `📋 Found ${adrs.length} ADR${adrs.length !== 1 ? 's' : ''}${status ? ` with status: ${status}` : ''}:\n\n` +
                                adrs.map(adr => `${statusEmoji[adr.status]} **${adr.id}**: ${adr.title}\n` +
                                    `   📅 ${adr.date.toISOString().split('T')[0]} | 👥 ${adr.deciders.join(', ')}` +
                                    (adr.tags?.length ? ` | 🏷️ ${adr.tags.join(', ')}` : '')).join('\n\n')
                        }],
                    structured: {
                        success: true,
                        adrs
                    }
                };
            }
            case 'search_adrs': {
                const { query, status, tags, template, dateRange, deciders } = args;
                const searchOptions = {
                    query,
                    status: status ? (Array.isArray(status) ? status : [status]) : undefined,
                    tags: tags ? (Array.isArray(tags) ? tags : tags.split(',').map((t) => t.trim())) : undefined,
                    template,
                    deciders: deciders ? (Array.isArray(deciders) ? deciders : deciders.split(',').map((d) => d.trim())) : undefined
                };
                if (dateRange?.from) {
                    searchOptions.dateRange = {
                        from: new Date(dateRange.from),
                        to: dateRange.to ? new Date(dateRange.to) : new Date()
                    };
                }
                const results = await adrManager.searchADRs(searchOptions);
                if (results.length === 0) {
                    return {
                        content: [{
                                type: 'text',
                                text: `🔍 No ADRs found matching your search criteria.`
                            }],
                        structured: {
                            success: true,
                            results: []
                        }
                    };
                }
                return {
                    content: [{
                            type: 'text',
                            text: `🔍 Found ${results.length} ADR${results.length !== 1 ? 's' : ''} matching your search:\n\n` +
                                results.map(adr => `📄 **${adr.id}**: ${adr.title}\n` +
                                    `   📊 ${adr.status} | 📅 ${adr.date.toISOString().split('T')[0]}` +
                                    (query ? `\n   📝 Matches in: ${getMatchLocations(adr, query)}` : '')).join('\n\n')
                        }],
                    structured: {
                        success: true,
                        results
                    }
                };
            }
            case 'delete_adr': {
                const { id } = args;
                await adrManager.deleteADR(id);
                return {
                    content: [{
                            type: 'text',
                            text: `✅ ADR deleted successfully: ${id}`
                        }],
                    structured: {
                        success: true,
                        deleted: id
                    }
                };
            }
            case 'adr_metrics': {
                const metrics = await adrManager.getMetrics();
                return {
                    content: [{
                            type: 'text',
                            text: `📊 **ADR Metrics**\n\n` +
                                `📈 **Total ADRs**: ${metrics.total}\n\n` +
                                `**By Status**:\n` +
                                `  • 💡 Proposed: ${metrics.byStatus.proposed}\n` +
                                `  • ✅ Accepted: ${metrics.byStatus.accepted}\n` +
                                `  • ❌ Rejected: ${metrics.byStatus.rejected}\n` +
                                `  • ⚠️ Deprecated: ${metrics.byStatus.deprecated}\n` +
                                `  • 🔄 Superseded: ${metrics.byStatus.superseded}\n\n` +
                                `**By Template**:\n` +
                                `  • Nygard: ${metrics.byTemplate.nygard}\n` +
                                `  • MADR: ${metrics.byTemplate.madr}\n` +
                                `  • Y-statement: ${metrics.byTemplate['y-statement']}\n\n` +
                                (metrics.averageDecisionTime > 0
                                    ? `⏱️ **Average decision time**: ${metrics.averageDecisionTime.toFixed(1)} days\n\n`
                                    : '') +
                                (metrics.mostActiveDeciders.length > 0
                                    ? `👥 **Most active deciders**:\n${metrics.mostActiveDeciders.slice(0, 5).map(d => `  • ${d.name}: ${d.count} decisions`).join('\n')}`
                                    : '')
                        }],
                    structured: {
                        success: true,
                        metrics
                    }
                };
            }
            case 'validate_adr_references': {
                const validation = await adrManager.validateReferences();
                if (validation.valid) {
                    return {
                        content: [{
                                type: 'text',
                                text: `✅ All ADR references are valid!`
                            }],
                        structured: {
                            success: true,
                            validation
                        }
                    };
                }
                return {
                    content: [{
                            type: 'text',
                            text: `❌ Found ${validation.errors.length} broken reference${validation.errors.length !== 1 ? 's' : ''}:\n\n` +
                                validation.errors.map(err => `• **${err.adrId}** ${err.type} **${err.targetId}**: ${err.error}`).join('\n')
                        }],
                    structured: {
                        success: false,
                        validation
                    }
                };
            }
            case 'generate_adr_log': {
                const log = await adrManager.generateDecisionLog();
                return {
                    content: [{
                            type: 'text',
                            text: `📄 Architecture Decision Log Generated\n\n` +
                                `Use this log to track all architectural decisions in your project.\n\n` +
                                `---\n\n${log}`
                        }],
                    structured: {
                        success: true,
                        markdown: log
                    }
                };
            }
            default:
                // Not an ADR management tool
                return null;
        }
    });
    return {
        tools: [
            {
                name: 'create_adr',
                description: 'Create a new Architecture Decision Record',
                inputSchema: {
                    type: 'object',
                    properties: {
                        title: { type: 'string', description: 'Title of the decision' },
                        template: {
                            type: 'string',
                            enum: ['nygard', 'madr', 'y-statement'],
                            default: 'nygard',
                            description: 'ADR template to use'
                        },
                        deciders: {
                            type: 'string',
                            description: 'Comma-separated list of people involved in the decision'
                        },
                        context: { type: 'string', description: 'Context and problem statement' },
                        decision: { type: 'string', description: 'The decision that was made' },
                        consequences: { type: 'string', description: 'Positive and negative consequences' },
                        tags: { type: 'string', description: 'Optional comma-separated tags' },
                        decisionDrivers: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Key factors that influenced the decision (MADR template)'
                        },
                        consideredOptions: {
                            type: 'array',
                            items: {
                                type: 'object',
                                properties: {
                                    title: { type: 'string' },
                                    description: { type: 'string' },
                                    pros: { type: 'array', items: { type: 'string' } },
                                    cons: { type: 'array', items: { type: 'string' } }
                                }
                            },
                            description: 'Alternative options that were considered (MADR template)'
                        },
                        supersedes: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'ADR IDs that this decision supersedes'
                        },
                        relatedTo: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'ADR IDs that this decision relates to'
                        }
                    },
                    required: ['title', 'deciders', 'context', 'decision', 'consequences']
                }
            },
            {
                name: 'create_adr_interactive',
                description: 'Create an ADR through an interactive wizard',
                inputSchema: {
                    type: 'object',
                    properties: {
                        userInput: { type: 'string', description: 'User input for the current wizard step' }
                    },
                    required: []
                }
            },
            {
                name: 'update_adr',
                description: 'Update an existing ADR',
                inputSchema: {
                    type: 'object',
                    properties: {
                        id: { type: 'string', description: 'ADR ID (e.g., ADR-0001)' },
                        status: {
                            type: 'string',
                            enum: ['proposed', 'accepted', 'rejected', 'deprecated', 'superseded'],
                            description: 'New status'
                        },
                        statusChangeReason: { type: 'string', description: 'Reason for status change' },
                        statusChangedBy: { type: 'string', description: 'Person making the status change' },
                        title: { type: 'string', description: 'Updated title' },
                        consequences: { type: 'string', description: 'Updated consequences' },
                        tags: { type: 'string', description: 'Updated comma-separated tags' },
                        supersedes: { type: 'array', items: { type: 'string' } },
                        supersededBy: { type: 'string' },
                        relatedTo: { type: 'array', items: { type: 'string' } }
                    },
                    required: ['id']
                }
            },
            {
                name: 'link_adrs',
                description: 'Create a relationship between two ADRs',
                inputSchema: {
                    type: 'object',
                    properties: {
                        fromId: { type: 'string', description: 'Source ADR ID' },
                        toId: { type: 'string', description: 'Target ADR ID' },
                        relationship: {
                            type: 'string',
                            enum: ['related-to', 'supersedes'],
                            default: 'related-to',
                            description: 'Type of relationship'
                        }
                    },
                    required: ['fromId', 'toId']
                }
            },
            {
                name: 'get_adr',
                description: 'Get details of a specific ADR',
                inputSchema: {
                    type: 'object',
                    properties: {
                        id: { type: 'string', description: 'ADR ID (e.g., ADR-0001)' }
                    },
                    required: ['id']
                }
            },
            {
                name: 'list_adrs',
                description: 'List all ADRs with optional status filter',
                inputSchema: {
                    type: 'object',
                    properties: {
                        status: {
                            type: 'string',
                            enum: ['proposed', 'accepted', 'rejected', 'deprecated', 'superseded'],
                            description: 'Filter by status'
                        }
                    },
                    required: []
                }
            },
            {
                name: 'search_adrs',
                description: 'Search ADRs by various criteria',
                inputSchema: {
                    type: 'object',
                    properties: {
                        query: { type: 'string', description: 'Text to search for' },
                        status: {
                            type: 'array',
                            items: { type: 'string', enum: ['proposed', 'accepted', 'rejected', 'deprecated', 'superseded'] },
                            description: 'Filter by status'
                        },
                        tags: { type: 'string', description: 'Comma-separated tags to filter by' },
                        template: {
                            type: 'string',
                            enum: ['nygard', 'madr', 'y-statement'],
                            description: 'Filter by template'
                        },
                        dateRange: {
                            type: 'object',
                            properties: {
                                from: { type: 'string', format: 'date', description: 'Start date (YYYY-MM-DD)' },
                                to: { type: 'string', format: 'date', description: 'End date (YYYY-MM-DD)' }
                            }
                        },
                        deciders: { type: 'string', description: 'Comma-separated list of deciders' }
                    },
                    required: []
                }
            },
            {
                name: 'delete_adr',
                description: 'Delete an ADR',
                inputSchema: {
                    type: 'object',
                    properties: {
                        id: { type: 'string', description: 'ADR ID to delete' }
                    },
                    required: ['id']
                }
            },
            {
                name: 'adr_metrics',
                description: 'Get metrics and statistics about ADRs',
                inputSchema: {
                    type: 'object',
                    properties: {},
                    required: []
                }
            },
            {
                name: 'validate_adr_references',
                description: 'Validate all ADR cross-references',
                inputSchema: {
                    type: 'object',
                    properties: {},
                    required: []
                }
            },
            {
                name: 'generate_adr_log',
                description: 'Generate a comprehensive ADR log document',
                inputSchema: {
                    type: 'object',
                    properties: {},
                    required: []
                }
            }
        ],
        resources: []
    };
}
function getMatchLocations(adr, query) {
    const locations = [];
    const q = query.toLowerCase();
    if (adr.title.toLowerCase().includes(q))
        locations.push('title');
    if (adr.context.toLowerCase().includes(q))
        locations.push('context');
    if (adr.decision.toLowerCase().includes(q))
        locations.push('decision');
    if (adr.consequences.toLowerCase().includes(q))
        locations.push('consequences');
    if (adr.tags?.some((t) => t.toLowerCase().includes(q)))
        locations.push('tags');
    return locations.join(', ');
}
//# sourceMappingURL=index.js.map