import { ADRManager } from './adr-manager.js';
export class ADRWizard {
    sessions = new Map();
    manager;
    sessionTimeout = 30 * 60 * 1000; // 30 minutes
    constructor(configManager) {
        this.manager = new ADRManager(configManager);
        // Clean up stale sessions periodically
        setInterval(() => this.cleanupStaleSessions(), 5 * 60 * 1000); // Every 5 minutes
    }
    async startInteractiveADR(server, request, sendProgress) {
        const sessionId = request.sessionId || 'default';
        // Initialize session
        this.sessions.set(sessionId, {
            currentStep: 1,
            totalSteps: 8, // Base steps, will adjust based on template
            data: {},
            lastActivity: Date.now()
        });
        sendProgress({
            progress: 10,
            total: 100,
            message: 'Starting ADR creation wizard...'
        });
        return {
            content: [{
                    type: 'text',
                    text: `🎯 ADR Creation Wizard\n\n` +
                        `I'll guide you through creating an Architecture Decision Record step by step.\n\n` +
                        `**Step 1 of 8: ADR Title**\n\n` +
                        `What is the title of this decision? (e.g., "Use React for Frontend Framework")\n\n` +
                        `💡 Tip: Use a clear, action-oriented title that describes the decision.`
                }],
            structured: {
                step: 1,
                totalSteps: 8,
                currentField: 'title'
            }
        };
    }
    async continueInteractiveADR(server, request, sendProgress, args) {
        const sessionId = request.sessionId || 'default';
        const session = this.sessions.get(sessionId);
        if (!session) {
            throw new Error('No active ADR creation session found');
        }
        session.lastActivity = Date.now();
        const input = args.userInput.trim();
        // Handle cancellation
        if (input.toLowerCase() === 'cancel') {
            this.sessions.delete(sessionId);
            return {
                content: [{
                        type: 'text',
                        text: '❌ ADR creation cancelled.'
                    }]
            };
        }
        // Process input based on current step
        switch (session.currentStep) {
            case 1: // Title
                if (!input) {
                    return {
                        content: [{
                                type: 'text',
                                text: '❌ Title cannot be empty. Please provide a title for the ADR.'
                            }]
                    };
                }
                session.data.title = input;
                session.currentStep++;
                sendProgress({
                    progress: 25,
                    total: 100,
                    message: 'Title recorded, selecting template...'
                });
                return {
                    content: [{
                            type: 'text',
                            text: `✅ Title: "${input}"\n\n` +
                                `**Step 2 of ${session.totalSteps}: Template Selection**\n\n` +
                                `Which template would you like to use?\n\n` +
                                `1. **Nygard** - Simple and effective for most decisions\n` +
                                `2. **MADR** - Comprehensive with structured options and decision drivers\n` +
                                `3. **Y-statement** - Minimal format focusing on why\n\n` +
                                `Enter 1, 2, or 3:`
                        }]
                };
            case 2: // Template
                const templateChoice = parseInt(input);
                if (![1, 2, 3].includes(templateChoice)) {
                    return {
                        content: [{
                                type: 'text',
                                text: '❌ Please enter 1, 2, or 3 to select a template.'
                            }]
                    };
                }
                const templates = ['nygard', 'madr', 'y-statement'];
                session.data.template = templates[templateChoice - 1];
                // Adjust total steps based on template
                if (session.data.template === 'madr') {
                    session.totalSteps = 12; // Additional steps for MADR
                }
                else if (session.data.template === 'y-statement') {
                    session.totalSteps = 7; // Fewer steps for Y-statement
                }
                session.currentStep++;
                sendProgress({
                    progress: 35,
                    total: 100,
                    message: 'Template selected, gathering context...'
                });
                return {
                    content: [{
                            type: 'text',
                            text: `✅ Template: ${session.data.template}\n\n` +
                                `**Step 3 of ${session.totalSteps}: Context**\n\n` +
                                `What is the context that motivates this decision?\n` +
                                `Describe the issue, problem, or situation that requires a decision.\n\n` +
                                `💡 Tip: Include relevant background, constraints, and forces at play.`
                        }]
                };
            case 3: // Context
                if (!input) {
                    return {
                        content: [{
                                type: 'text',
                                text: '❌ Context cannot be empty. Please describe the context.'
                            }]
                    };
                }
                session.data.context = input;
                session.currentStep++;
                sendProgress({
                    progress: 45,
                    total: 100,
                    message: 'Context recorded...'
                });
                return {
                    content: [{
                            type: 'text',
                            text: `✅ Context recorded\n\n` +
                                `**Step 4 of ${session.totalSteps}: Decision**\n\n` +
                                `What is the decision you've made?\n` +
                                `State it clearly and concisely.\n\n` +
                                `💡 Tip: Use active voice (e.g., "We will use..." not "It was decided...")`
                        }]
                };
            case 4: // Decision
                if (!input) {
                    return {
                        content: [{
                                type: 'text',
                                text: '❌ Decision cannot be empty. Please state the decision.'
                            }]
                    };
                }
                session.data.decision = input;
                session.currentStep++;
                sendProgress({
                    progress: 55,
                    total: 100,
                    message: 'Decision recorded...'
                });
                return {
                    content: [{
                            type: 'text',
                            text: `✅ Decision recorded\n\n` +
                                `**Step 5 of ${session.totalSteps}: Consequences**\n\n` +
                                `What are the consequences of this decision?\n` +
                                `Include both positive and negative outcomes.\n\n` +
                                `💡 Tip: Think about immediate and long-term impacts.`
                        }]
                };
            case 5: // Consequences
                if (!input) {
                    return {
                        content: [{
                                type: 'text',
                                text: '❌ Consequences cannot be empty. Please describe the consequences.'
                            }]
                    };
                }
                session.data.consequences = input;
                // Handle MADR-specific fields
                if (session.data.template === 'madr') {
                    session.currentStep = 6;
                    sendProgress({
                        progress: 60,
                        total: 100,
                        message: 'Gathering decision drivers...'
                    });
                    return {
                        content: [{
                                type: 'text',
                                text: `✅ Consequences recorded\n\n` +
                                    `**Step 6 of ${session.totalSteps}: Decision Drivers**\n\n` +
                                    `What are the key factors that influenced this decision?\n` +
                                    `Enter them as a comma-separated list.\n\n` +
                                    `Example: Performance, Cost, Developer Experience, Time to Market`
                            }]
                    };
                }
                // Skip to deciders for non-MADR templates
                session.currentStep++;
                return this.askForDeciders(session, sendProgress);
            case 6: // Decision Drivers (MADR) or Deciders
                if (session.data.template === 'madr') {
                    session.data.decisionDrivers = input.split(',').map(d => d.trim()).filter(Boolean);
                    session.currentStep = 7;
                    sendProgress({
                        progress: 65,
                        total: 100,
                        message: 'Gathering considered options...'
                    });
                    return {
                        content: [{
                                type: 'text',
                                text: `✅ Decision drivers recorded\n\n` +
                                    `**Step 7 of ${session.totalSteps}: Considered Options**\n\n` +
                                    `Would you like to document alternative options that were considered?\n` +
                                    `Enter 'yes' to add options, or 'no' to skip.`
                            }]
                    };
                }
                // This is deciders for non-MADR
                return this.processDeciders(session, input, sendProgress);
            case 7: // Considered Options prompt (MADR) or Tags
                if (session.data.template === 'madr' && !session.data.consideredOptions) {
                    if (input.toLowerCase() === 'yes') {
                        session.data.consideredOptions = [];
                        return this.askForOption(session, sendProgress);
                    }
                    else {
                        session.currentStep = 10; // Skip to deciders
                        return this.askForDeciders(session, sendProgress);
                    }
                }
                // This is tags for non-MADR
                return this.processTags(session, input, sendProgress);
            case 8: // Option Title (MADR)
            case 9: // Option fields (MADR)
                return this.processOption(session, input, sendProgress);
            case 10: // Deciders (MADR)
                return this.processDeciders(session, input, sendProgress);
            case 11: // Tags (MADR)
                return this.processTags(session, input, sendProgress);
            case 12: // Related ADRs
                if (input) {
                    session.data.relatedTo = input.split(',').map(id => id.trim()).filter(Boolean);
                }
                return this.processRelatedADRs(session, input, sendProgress);
            case 13: // Supersedes
                if (input) {
                    session.data.supersedes = input.split(',').map(id => id.trim()).filter(Boolean);
                }
                return this.processSupersedes(session, input, sendProgress);
            case 14: // Summary and confirmation
                return this.processSummary(session, input, sendProgress, server, request);
            default:
                // Handle edit mode
                if (session.currentStep > 100) {
                    return this.handleEdit(session, input, sendProgress);
                }
                throw new Error(`Invalid wizard step: ${session.currentStep}`);
        }
    }
    askForDeciders(session, sendProgress) {
        const stepNum = session.data.template === 'madr' ? 10 : 6;
        session.currentStep = stepNum;
        sendProgress({
            progress: 70,
            total: 100,
            message: 'Almost done...'
        });
        return {
            content: [{
                    type: 'text',
                    text: `✅ Previous step completed\n\n` +
                        `**Step ${stepNum} of ${session.totalSteps}: Deciders**\n\n` +
                        `Who are the people involved in this decision?\n` +
                        `Enter names as a comma-separated list.\n\n` +
                        `Example: John Doe, Jane Smith, Architecture Team`
                }]
        };
    }
    processDeciders(session, input, sendProgress) {
        if (!input) {
            return {
                content: [{
                        type: 'text',
                        text: '❌ Deciders cannot be empty. Please provide at least one decider.'
                    }]
            };
        }
        session.data.deciders = input.split(',').map(d => d.trim()).filter(Boolean);
        session.currentStep++;
        sendProgress({
            progress: 80,
            total: 100,
            message: 'Gathering tags...'
        });
        const stepNum = session.currentStep;
        return {
            content: [{
                    type: 'text',
                    text: `✅ Deciders recorded\n\n` +
                        `**Step ${stepNum} of ${session.totalSteps}: Tags**\n\n` +
                        `Add tags to categorize this ADR (optional).\n` +
                        `Enter as comma-separated values or press Enter to skip.\n\n` +
                        `Example: frontend, architecture, performance`
                }]
        };
    }
    processTags(session, input, sendProgress) {
        if (input) {
            session.data.tags = input.split(',').map(t => t.trim()).filter(Boolean);
        }
        // Always ask about related ADRs after tags
        return this.askForRelatedADRs(session, sendProgress);
    }
    async askForRelatedADRs(session, sendProgress) {
        await this.manager.initialize();
        const existingADRs = await this.manager.listADRs();
        if (existingADRs.length === 0) {
            // Skip to summary if no existing ADRs
            return this.showSummary(session, sendProgress);
        }
        sendProgress({
            progress: 85,
            total: 100,
            message: 'Checking relationships...'
        });
        const stepNum = session.currentStep;
        session.currentStep = 12; // Fixed step for related ADRs
        const adrList = existingADRs.slice(0, 10).map(adr => `  • ${adr.id}: ${adr.title} (${adr.status})`).join('\n');
        return {
            content: [{
                    type: 'text',
                    text: `✅ Tags recorded\n\n` +
                        `**Step ${stepNum} of ${session.totalSteps}: Related ADRs**\n\n` +
                        `Are there any existing ADRs related to this decision?\n\n` +
                        `Recent ADRs:\n${adrList}\n\n` +
                        `Enter ADR IDs separated by commas (e.g., ADR-0001, ADR-0002) or press Enter to skip.`
                }]
        };
    }
    processRelatedADRs(session, input, sendProgress) {
        // We're being called from case 12 which already set the data
        session.currentStep = 13;
        sendProgress({
            progress: 90,
            total: 100,
            message: 'Checking superseded decisions...'
        });
        return {
            content: [{
                    type: 'text',
                    text: `✅ Related ADRs recorded\n\n` +
                        `**Step ${session.currentStep} of ${session.totalSteps}: Superseded Decisions**\n\n` +
                        `Does this decision supersede any existing ADRs?\n` +
                        `If so, those ADRs will be marked as superseded.\n\n` +
                        `Enter ADR IDs separated by commas or press Enter to skip.`
                }]
        };
    }
    processSupersedes(session, input, sendProgress) {
        // We're being called from case 13 which already set the data
        return this.showSummary(session, sendProgress);
    }
    showSummary(session, sendProgress) {
        session.currentStep = 14;
        sendProgress({
            progress: 95,
            total: 100,
            message: 'Preparing summary...'
        });
        let summary = `📋 **ADR Summary**\n\n`;
        summary += `**Title**: ${session.data.title}\n`;
        summary += `**Template**: ${session.data.template}\n`;
        summary += `**Deciders**: ${session.data.deciders?.join(', ')}\n\n`;
        summary += `**Context**:\n${session.data.context}\n\n`;
        summary += `**Decision**:\n${session.data.decision}\n\n`;
        summary += `**Consequences**:\n${session.data.consequences}\n\n`;
        if (session.data.decisionDrivers?.length) {
            summary += `**Decision Drivers**: ${session.data.decisionDrivers.join(', ')}\n\n`;
        }
        if (session.data.consideredOptions?.length) {
            summary += `**Considered Options**: ${session.data.consideredOptions.length} options documented\n\n`;
        }
        if (session.data.tags?.length) {
            summary += `**Tags**: ${session.data.tags.join(', ')}\n`;
        }
        if (session.data.relatedTo?.length) {
            summary += `**Related to**: ${session.data.relatedTo.join(', ')}\n`;
        }
        if (session.data.supersedes?.length) {
            summary += `**Supersedes**: ${session.data.supersedes.join(', ')}\n`;
        }
        summary += `\n---\n\n`;
        summary += `Ready to create this ADR?\n\n`;
        summary += `• Type 'yes' to create the ADR\n`;
        summary += `• Type 'edit' to modify any field\n`;
        summary += `• Type 'cancel' to abort`;
        return {
            content: [{
                    type: 'text',
                    text: summary
                }],
            structured: {
                step: 'summary',
                data: session.data
            }
        };
    }
    async processSummary(session, input, sendProgress, server, request) {
        const choice = input.toLowerCase();
        if (choice === 'cancel') {
            const sessionId = request?.sessionId || 'default';
            this.sessions.delete(sessionId);
            return {
                content: [{
                        type: 'text',
                        text: '❌ ADR creation cancelled.'
                    }]
            };
        }
        if (choice === 'edit') {
            return {
                content: [{
                        type: 'text',
                        text: `Which field would you like to edit?\n\n` +
                            `• title\n• context\n• decision\n• consequences\n` +
                            (session.data.decisionDrivers ? `• drivers\n` : '') +
                            (session.data.consideredOptions ? `• options\n` : '') +
                            `• deciders\n• tags\n• related\n• supersedes`
                    }]
            };
        }
        if (choice === 'yes') {
            sendProgress({
                progress: 98,
                total: 100,
                message: 'Creating ADR...'
            });
            try {
                await this.manager.initialize();
                const adr = await this.manager.createADR(session.data);
                const sessionId = server.request?.sessionId || request?.sessionId || 'default';
                this.sessions.delete(sessionId);
                sendProgress({
                    progress: 100,
                    total: 100,
                    message: 'ADR created successfully!'
                });
                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\n` +
                                `The ADR has been saved and indexed. You can now:\n` +
                                `• View it with: \`get_adr id:"${adr.id}"\`\n` +
                                `• Update its status as the decision progresses\n` +
                                `• Link it to other ADRs as relationships develop`
                        }],
                    structured: {
                        success: true,
                        adr
                    }
                };
            }
            catch (error) {
                return {
                    content: [{
                            type: 'text',
                            text: `❌ Error creating ADR: ${error.message}`
                        }]
                };
            }
        }
        return {
            content: [{
                    type: 'text',
                    text: `❌ Please type 'yes', 'edit', or 'cancel'.`
                }]
        };
    }
    askForOption(session, sendProgress) {
        const optionNum = (session.data.consideredOptions?.length || 0) + 1;
        session.currentStep = 8;
        return {
            content: [{
                    type: 'text',
                    text: `**Adding Option ${optionNum}**\n\n` +
                        `What is the title of this option? (or type 'done' to finish adding options)`
                }]
        };
    }
    processOption(session, input, sendProgress) {
        if (!session.data.consideredOptions) {
            session.data.consideredOptions = [];
        }
        if (session.currentStep === 8) {
            // Option title
            if (input.toLowerCase() === 'done') {
                session.currentStep = 10; // Go to deciders
                return this.askForDeciders(session, sendProgress);
            }
            session.data.consideredOptions.push({
                title: input,
                description: '',
                pros: [],
                cons: []
            });
            session.currentStep = 9;
            return {
                content: [{
                        type: 'text',
                        text: `✅ Option: "${input}"\n\n` +
                            `Provide a brief description of this option:`
                    }]
            };
        }
        const option = session.data.consideredOptions[session.data.consideredOptions.length - 1];
        if (!option.description) {
            option.description = input;
            return {
                content: [{
                        type: 'text',
                        text: `✅ Description recorded\n\n` +
                            `What are the pros of this option? (comma-separated)`
                    }]
            };
        }
        if (option.pros.length === 0) {
            option.pros = input.split(',').map(p => p.trim()).filter(Boolean);
            return {
                content: [{
                        type: 'text',
                        text: `✅ Pros recorded\n\n` +
                            `What are the cons of this option? (comma-separated)`
                    }]
            };
        }
        if (option.cons.length === 0) {
            option.cons = input.split(',').map(c => c.trim()).filter(Boolean);
            return this.askForOption(session, sendProgress);
        }
        return this.askForOption(session, sendProgress);
    }
    handleEdit(session, input, sendProgress) {
        // Reset from edit mode
        session.currentStep = 14;
        const field = input.toLowerCase();
        // Map field to appropriate step
        const fieldStepMap = {
            'title': { step: 1, prompt: 'Enter new title:' },
            'context': { step: 3, prompt: 'Enter new context:' },
            'decision': { step: 4, prompt: 'Enter new decision:' },
            'consequences': { step: 5, prompt: 'Enter new consequences:' },
            'drivers': { step: 6, prompt: 'Enter new decision drivers (comma-separated):' },
            'deciders': { step: 10, prompt: 'Enter new deciders (comma-separated):' },
            'tags': { step: 11, prompt: 'Enter new tags (comma-separated):' },
            'related': { step: 12, prompt: 'Enter related ADR IDs (comma-separated):' },
            'supersedes': { step: 13, prompt: 'Enter superseded ADR IDs (comma-separated):' }
        };
        const fieldInfo = fieldStepMap[field];
        if (!fieldInfo) {
            return {
                content: [{
                        type: 'text',
                        text: `❌ Unknown field: ${field}. Please choose from the list.`
                    }]
            };
        }
        session.currentStep = 100 + fieldInfo.step; // Mark as edit mode
        return {
            content: [{
                    type: 'text',
                    text: fieldInfo.prompt
                }]
        };
    }
    cleanupStaleSessions() {
        const now = Date.now();
        for (const [sessionId, session] of this.sessions.entries()) {
            if (now - session.lastActivity > this.sessionTimeout) {
                this.sessions.delete(sessionId);
            }
        }
    }
}
//# sourceMappingURL=adr-wizard.js.map