import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { ConfigManager } from '../../config/config-manager.js';
import { BusinessAnalyzer } from './analyzer.js';
import { BusinessPlanWizard } from './business-plan-wizard.js';
import { promises as fs } from 'fs';
import path from 'path';
let configManager;
let businessAnalyzer;
let businessPlanWizard;
export async function setupBusinessGuidanceTools(server, config) {
    configManager = config || new ConfigManager();
    businessAnalyzer = new BusinessAnalyzer(configManager);
    await businessAnalyzer.init();
    businessPlanWizard = new BusinessPlanWizard();
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
        const { name, arguments: args } = request.params;
        if (!args) {
            throw new Error('No arguments provided');
        }
        switch (name) {
            case 'generate_business_plan': {
                const { businessIdea, targetMarket, businessModel = 'saas', timeline = '12', includeFinancials = true, template = 'lean_canvas', } = args;
                try {
                    const businessPlan = await businessAnalyzer.generateBusinessPlan({
                        businessIdea,
                        targetMarket,
                        businessModel,
                        timeline: parseInt(timeline),
                        includeFinancials,
                        template,
                    });
                    // Save business plan to project
                    const planPath = path.join(process.cwd(), 'docs', 'business-plan.md');
                    await fs.mkdir(path.dirname(planPath), { recursive: true });
                    await fs.writeFile(planPath, businessPlan.markdown);
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `✅ Business plan generated successfully!

📋 **Business Idea**: ${businessIdea}
🎯 **Target Market**: ${targetMarket}
💼 **Business Model**: ${businessModel}
📅 **Timeline**: ${timeline} months
💰 **Financials**: ${includeFinancials ? 'Included' : 'Not included'}
📄 **Template**: ${template}

📁 **Saved to**: docs/business-plan.md

## Key Sections Generated:
${businessPlan.sections.map(section => `• ${section.title}`).join('\n')}

💡 **Next Steps**:
${businessPlan.nextSteps.map((step, i) => `${i + 1}. ${step}`).join('\n')}`,
                            },
                        ],
                        structured: {
                            businessPlan,
                            filePath: 'docs/business-plan.md',
                            generated: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to generate business plan: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'generate_business_plan_interactive': {
                const { action, workflowId, response } = args;
                try {
                    if (action === 'start') {
                        const workflow = businessPlanWizard.startBusinessPlanCreation();
                        const currentStep = businessPlanWizard.formatCurrentStep(workflow.id);
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: `🚀 Starting Interactive Business Plan Creation Wizard

This wizard will guide you through creating a comprehensive business plan by asking key questions about your business idea, market, and strategy.

${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 businessPlanWizard.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 = businessPlanWizard.completeWorkflow(workflowId);
                            if (planData) {
                                // Generate the business plan using the collected data
                                const businessPlan = await businessAnalyzer.generateBusinessPlan({
                                    businessIdea: planData.businessIdea,
                                    targetMarket: planData.targetMarket,
                                    businessModel: planData.businessModel,
                                    timeline: 12, // Default to 12 months
                                    includeFinancials: planData.includeFinancials,
                                    template: planData.template,
                                });
                                // Save business plan to project
                                const planPath = path.join(process.cwd(), 'docs', 'business-plan.md');
                                await fs.mkdir(path.dirname(planPath), { recursive: true });
                                await fs.writeFile(planPath, businessPlan.markdown);
                                return {
                                    content: [
                                        {
                                            type: 'text',
                                            text: `✅ Business plan created successfully through interactive wizard!

📋 **Business**: ${planData.businessIdea}
🎯 **Target Market**: ${planData.targetMarket}
💼 **Business Model**: ${planData.businessModel}
📊 **Market Size**: ${planData.marketSize}
⏱️ **Timeline**: ${planData.timeline}

**Key Differentiator**: ${planData.competitiveAdvantage}

**Revenue Streams**:
${planData.revenueStreams.map((stream) => `• ${stream}`).join('\n')}

**Success Metrics**:
${planData.keyMetrics.map((metric) => `• ${metric}`).join('\n')}

📁 **Saved to**: docs/business-plan.md

💡 Your business plan has been generated based on your inputs. You can now:
- Review and refine the plan
- Share with potential investors or partners
- Use it as a roadmap for execution`,
                                        },
                                    ],
                                    structured: {
                                        businessPlan,
                                        planData,
                                        filePath: 'docs/business-plan.md',
                                        generated: true,
                                        createdVia: 'interactive-wizard',
                                    },
                                };
                            }
                        }
                        // Continue to next step
                        const currentStep = businessPlanWizard.formatCurrentStep(workflowId);
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: currentStep,
                                },
                            ],
                            structured: {
                                workflowId,
                                action: 'waiting_for_response',
                            },
                        };
                    }
                    if (action === 'cancel' && workflowId) {
                        businessPlanWizard.cancelWorkflow(workflowId);
                        return {
                            content: [
                                {
                                    type: 'text',
                                    text: `❌ Business plan creation wizard cancelled.`,
                                },
                            ],
                            structured: {
                                cancelled: true,
                            },
                        };
                    }
                    throw new Error('Invalid action or missing required parameters');
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Business plan wizard error: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'analyze_market': {
                const { industry, targetAudience, geographicScope = 'global', includeCompetitors = true, depth = 'comprehensive', } = args;
                try {
                    const marketAnalysis = await businessAnalyzer.analyzeMarket({
                        industry,
                        targetMarket: targetAudience,
                        geographicScope,
                        includeCompetitors,
                        depth,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: formatMarketAnalysis(marketAnalysis),
                            },
                        ],
                        structured: {
                            marketAnalysis,
                            analyzed: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Market analysis failed: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'competitor_research': {
                const { businessIdea, industry, competitors = [], analysisDepth = 'standard', includeStrengthWeakness = true, } = args;
                try {
                    const competitorAnalysis = await businessAnalyzer.analyzeCompetitors({
                        businessIdea,
                        industry,
                        competitors,
                        analysisDepth,
                        includeStrengthWeakness,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: formatCompetitorAnalysis(competitorAnalysis),
                            },
                        ],
                        structured: {
                            competitorAnalysis,
                            analyzed: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Competitor research failed: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'financial_projections': {
                const { businessModel, revenue, expenses, timeline = 36, includeScenarios = true, currency = 'USD', } = args;
                try {
                    const projections = await businessAnalyzer.generateFinancialProjections({
                        businessModel,
                        revenue,
                        expenses,
                        timeline,
                        includeScenarios,
                        currency,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: formatFinancialProjections(projections),
                            },
                        ],
                        structured: {
                            projections,
                            generated: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Financial projections failed: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'startup_assessment': {
                const { stage = 'idea', hasProduct = false, hasRevenue = false, teamSize = 1, hasCustomers = false, hasFunding = false, } = args;
                try {
                    const assessment = await businessAnalyzer.assessStartup({
                        stage,
                        hasProduct,
                        hasRevenue,
                        teamSize,
                        hasCustomers,
                        hasFunding,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: formatStartupAssessment(assessment),
                            },
                        ],
                        structured: {
                            assessment,
                            completed: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Startup assessment failed: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'generate_pitch_deck': {
                const { businessIdea, problemStatement, solution, targetMarket, businessModel, competitiveAdvantage, fundingAsk, template = 'standard', } = args;
                try {
                    const pitchDeck = await businessAnalyzer.generatePitchDeck({
                        businessIdea,
                        problemStatement,
                        solution,
                        targetMarket,
                        businessModel,
                        competitiveAdvantage,
                        fundingAsk,
                        template,
                    });
                    // Save pitch deck
                    const deckPath = path.join(process.cwd(), 'docs', 'pitch-deck.md');
                    await fs.mkdir(path.dirname(deckPath), { recursive: true });
                    await fs.writeFile(deckPath, pitchDeck.markdown);
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `✅ Pitch deck generated successfully!

📊 **Template**: ${template}
📄 **Saved to**: docs/pitch-deck.md

## Slides Generated (${pitchDeck.slides.length}):
${pitchDeck.slides.map((slide, i) => `${i + 1}. ${slide.title}`).join('\n')}

🎯 **Key Highlights**:
• Problem: ${problemStatement.substring(0, 100)}...
• Solution: ${solution.substring(0, 100)}...
• Market: ${targetMarket}
${fundingAsk ? `• Funding Ask: ${fundingAsk}` : ''}

💡 **Presentation Tips**:
${pitchDeck.presentationTips.map(tip => `• ${tip}`).join('\n')}`,
                            },
                        ],
                        structured: {
                            pitchDeck,
                            filePath: 'docs/pitch-deck.md',
                            generated: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Pitch deck generation failed: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'track_startup_metrics': {
                const { metricsType = 'saas', currentMetrics = {}, goals = {}, timeframe = 'monthly', } = args;
                try {
                    const metrics = await businessAnalyzer.trackMetrics({
                        metricsType,
                        currentMetrics,
                        goals,
                        timeframe,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: formatStartupMetrics(metrics),
                            },
                        ],
                        structured: {
                            metrics,
                            tracked: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Metrics tracking failed: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'business_guidance': {
                const { question, context = '', stage = 'idea', industry = 'technology', } = args;
                try {
                    const guidance = await businessAnalyzer.provideGuidance({
                        question,
                        context,
                        stage,
                        industry,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `💡 Business Guidance

**Question**: ${question}

**Answer**: ${guidance.answer}

**Key Recommendations**:
${guidance.recommendations.map(rec => `• ${rec}`).join('\n')}

**Next Steps**:
${guidance.nextSteps.map((step, i) => `${i + 1}. ${step}`).join('\n')}

${guidance.resources.length > 0 ? `**Additional Resources**:
${guidance.resources.map(resource => `• ${resource}`).join('\n')}` : ''}

**Confidence Level**: ${Math.round(guidance.confidence * 100)}%`,
                            },
                        ],
                        structured: {
                            guidance,
                            answered: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Business guidance failed: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'perform_business_review': {
                const { businessName, includeProductAnalysis = true, includeMarketAnalysis = true, includeFinancialAnalysis = true, includeTeamAnalysis = true, includeTechnicalAnalysis = true, includeCustomerAnalysis = true, generateStrategicPaths = true, } = args;
                try {
                    const review = await businessAnalyzer.performComprehensiveReview({
                        businessName,
                        includeProductAnalysis,
                        includeMarketAnalysis,
                        includeFinancialAnalysis,
                        includeTeamAnalysis,
                        includeTechnicalAnalysis,
                        includeCustomerAnalysis,
                        generateStrategicPaths,
                    });
                    // Save review to file
                    const reviewPath = path.join(process.cwd(), 'docs', 'business-review.md');
                    await fs.mkdir(path.dirname(reviewPath), { recursive: true });
                    await fs.writeFile(reviewPath, formatBusinessReviewMarkdown(review));
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `📊 Comprehensive Business Review

**Business**: ${review.businessName}
**Stage**: ${review.currentStage.toUpperCase()}
**Overall Health Score**: ${review.overallHealthScore}/100
**Review Date**: ${new Date(review.reviewDate).toLocaleDateString()}

## ✅ Key Strengths (${review.strengths.length})
${review.strengths.slice(0, 3).map(strength => `• **${strength.area}**: ${strength.description}`).join('\n')}

## ⚠️ Critical Gaps (${review.gaps.filter(g => g.severity === 'critical').length})
${review.gaps.filter(g => g.severity === 'critical').slice(0, 3).map(gap => `• **${gap.area}**: ${gap.description} (${gap.severity})`).join('\n')}

## 🎯 Three Strategic Paths

${review.strategicPaths.map((path, i) => `### Path ${i + 1}: ${path.name}
**Focus**: ${path.focus}
**Timeline**: ${path.timeline}
**Risk Level**: ${path.riskLevel.toUpperCase()}
**Expected Outcome**: ${path.expectedOutcome}

**Key Actions**:
${path.keyActions.slice(0, 5).map(action => `• ${action.action} (${action.priority})`).join('\n')}
`).join('\n')}

## 📋 Immediate Next Steps
${review.immediateActions.map((action, i) => `${i + 1}. **${action.action}**
   - Rationale: ${action.rationale}
   - Expected Impact: ${action.expectedImpact}
   - Timeframe: ${action.timeframe}`).join('\n')}

📄 **Full report saved to**: docs/business-review.md
📅 **Next review recommended**: ${new Date(review.nextReviewDate).toLocaleDateString()}`,
                            },
                        ],
                        structured: {
                            review,
                            filePath: 'docs/business-review.md',
                            generated: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Business review failed: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            default:
                // Not a business guidance tool, throw to let other handlers try
                throw new Error(`Tool ${name} not handled by business guidance module`);
        }
    });
    return {
        tools: [
            {
                name: 'generate_business_plan',
                description: 'Generate a comprehensive business plan for your startup',
                inputSchema: {
                    type: 'object',
                    properties: {
                        businessIdea: {
                            type: 'string',
                            description: 'Description of your business idea'
                        },
                        targetMarket: {
                            type: 'string',
                            description: 'Description of your target market'
                        },
                        businessModel: {
                            type: 'string',
                            enum: ['saas', 'marketplace', 'e-commerce', 'subscription', 'freemium', 'advertising', 'consulting', 'product'],
                            default: 'saas',
                            description: 'Primary business model'
                        },
                        timeline: {
                            type: 'string',
                            default: '12',
                            description: 'Planning timeline in months'
                        },
                        includeFinancials: {
                            type: 'boolean',
                            default: true,
                            description: 'Include financial projections'
                        },
                        template: {
                            type: 'string',
                            enum: ['lean_canvas', 'traditional', 'one_page', 'investor'],
                            default: 'lean_canvas',
                            description: 'Business plan template to use'
                        },
                    },
                    required: ['businessIdea', 'targetMarket'],
                },
            },
            {
                name: 'generate_business_plan_interactive',
                description: 'Create a business plan through an interactive wizard that guides you through market analysis, business model, and strategic 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: 'analyze_market',
                description: 'Perform market analysis for your business idea',
                inputSchema: {
                    type: 'object',
                    properties: {
                        industry: {
                            type: 'string',
                            description: 'Industry or sector for analysis'
                        },
                        targetAudience: {
                            type: 'string',
                            description: 'Description of target audience'
                        },
                        geographicScope: {
                            type: 'string',
                            enum: ['local', 'national', 'global'],
                            default: 'global',
                            description: 'Geographic scope of analysis'
                        },
                        includeCompetitors: {
                            type: 'boolean',
                            default: true,
                            description: 'Include competitor analysis'
                        },
                        depth: {
                            type: 'string',
                            enum: ['basic', 'standard', 'comprehensive'],
                            default: 'comprehensive',
                            description: 'Depth of analysis'
                        },
                    },
                    required: ['industry', 'targetAudience'],
                },
            },
            {
                name: 'competitor_research',
                description: 'Research and analyze competitors in your market',
                inputSchema: {
                    type: 'object',
                    properties: {
                        businessIdea: {
                            type: 'string',
                            description: 'Your business idea for comparison'
                        },
                        industry: {
                            type: 'string',
                            description: 'Industry to research'
                        },
                        competitors: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Known competitors (optional)'
                        },
                        analysisDepth: {
                            type: 'string',
                            enum: ['basic', 'standard', 'comprehensive'],
                            default: 'standard',
                            description: 'Depth of competitor analysis'
                        },
                        includeStrengthWeakness: {
                            type: 'boolean',
                            default: true,
                            description: 'Include SWOT analysis'
                        },
                    },
                    required: ['businessIdea', 'industry'],
                },
            },
            {
                name: 'financial_projections',
                description: 'Generate financial projections and scenarios',
                inputSchema: {
                    type: 'object',
                    properties: {
                        businessModel: {
                            type: 'string',
                            description: 'Business model type'
                        },
                        revenue: {
                            type: 'object',
                            description: 'Revenue streams and amounts',
                            additionalProperties: { type: 'number' }
                        },
                        expenses: {
                            type: 'object',
                            description: 'Expense categories and amounts',
                            additionalProperties: { type: 'number' }
                        },
                        timeline: {
                            type: 'number',
                            default: 36,
                            description: 'Projection timeline in months'
                        },
                        includeScenarios: {
                            type: 'boolean',
                            default: true,
                            description: 'Include best/worst case scenarios'
                        },
                        currency: {
                            type: 'string',
                            default: 'USD',
                            description: 'Currency for projections'
                        },
                    },
                    required: ['businessModel', 'revenue', 'expenses'],
                },
            },
            {
                name: 'startup_assessment',
                description: 'Assess your startup stage and get recommendations',
                inputSchema: {
                    type: 'object',
                    properties: {
                        stage: {
                            type: 'string',
                            enum: ['idea', 'mvp', 'early_stage', 'growth', 'scale'],
                            default: 'idea',
                            description: 'Current startup stage'
                        },
                        hasProduct: {
                            type: 'boolean',
                            default: false,
                            description: 'Do you have a working product?'
                        },
                        hasRevenue: {
                            type: 'boolean',
                            default: false,
                            description: 'Are you generating revenue?'
                        },
                        teamSize: {
                            type: 'number',
                            default: 1,
                            description: 'Current team size'
                        },
                        hasCustomers: {
                            type: 'boolean',
                            default: false,
                            description: 'Do you have paying customers?'
                        },
                        hasFunding: {
                            type: 'boolean',
                            default: false,
                            description: 'Have you raised funding?'
                        },
                    },
                    required: [],
                },
            },
            {
                name: 'generate_pitch_deck',
                description: 'Create a professional pitch deck for investors',
                inputSchema: {
                    type: 'object',
                    properties: {
                        businessIdea: {
                            type: 'string',
                            description: 'Core business idea'
                        },
                        problemStatement: {
                            type: 'string',
                            description: 'Problem you are solving'
                        },
                        solution: {
                            type: 'string',
                            description: 'Your solution to the problem'
                        },
                        targetMarket: {
                            type: 'string',
                            description: 'Target market description'
                        },
                        businessModel: {
                            type: 'string',
                            description: 'How you make money'
                        },
                        competitiveAdvantage: {
                            type: 'string',
                            description: 'What makes you different/better'
                        },
                        fundingAsk: {
                            type: 'string',
                            description: 'Funding amount requested (optional)'
                        },
                        template: {
                            type: 'string',
                            enum: ['standard', 'investor', 'demo_day', 'one_slide'],
                            default: 'standard',
                            description: 'Pitch deck template'
                        },
                    },
                    required: ['businessIdea', 'problemStatement', 'solution', 'targetMarket', 'businessModel', 'competitiveAdvantage'],
                },
            },
            {
                name: 'track_startup_metrics',
                description: 'Track and analyze key startup metrics',
                inputSchema: {
                    type: 'object',
                    properties: {
                        metricsType: {
                            type: 'string',
                            enum: ['saas', 'e-commerce', 'marketplace', 'mobile_app', 'content'],
                            default: 'saas',
                            description: 'Type of business metrics'
                        },
                        currentMetrics: {
                            type: 'object',
                            description: 'Current metric values',
                            additionalProperties: { type: 'number' }
                        },
                        goals: {
                            type: 'object',
                            description: 'Target metric values',
                            additionalProperties: { type: 'number' }
                        },
                        timeframe: {
                            type: 'string',
                            enum: ['daily', 'weekly', 'monthly', 'quarterly'],
                            default: 'monthly',
                            description: 'Tracking timeframe'
                        },
                    },
                    required: [],
                },
            },
            {
                name: 'business_guidance',
                description: 'Get personalized business advice and guidance',
                inputSchema: {
                    type: 'object',
                    properties: {
                        question: {
                            type: 'string',
                            description: 'Your business question or challenge'
                        },
                        context: {
                            type: 'string',
                            description: 'Additional context about your situation'
                        },
                        stage: {
                            type: 'string',
                            enum: ['idea', 'mvp', 'early_stage', 'growth', 'scale'],
                            default: 'idea',
                            description: 'Current business stage'
                        },
                        industry: {
                            type: 'string',
                            default: 'technology',
                            description: 'Your industry or sector'
                        },
                    },
                    required: ['question'],
                },
            },
            {
                name: 'perform_business_review',
                description: 'Perform a comprehensive business review with gap analysis and strategic recommendations',
                inputSchema: {
                    type: 'object',
                    properties: {
                        businessName: {
                            type: 'string',
                            description: 'Name of your business (optional, will use project name if not provided)'
                        },
                        includeProductAnalysis: {
                            type: 'boolean',
                            default: true,
                            description: 'Analyze product development status and roadmap'
                        },
                        includeMarketAnalysis: {
                            type: 'boolean',
                            default: true,
                            description: 'Analyze market position and competition'
                        },
                        includeFinancialAnalysis: {
                            type: 'boolean',
                            default: true,
                            description: 'Analyze financial health and projections'
                        },
                        includeTeamAnalysis: {
                            type: 'boolean',
                            default: true,
                            description: 'Analyze team structure and capabilities'
                        },
                        includeTechnicalAnalysis: {
                            type: 'boolean',
                            default: true,
                            description: 'Analyze technical infrastructure and debt'
                        },
                        includeCustomerAnalysis: {
                            type: 'boolean',
                            default: true,
                            description: 'Analyze customer satisfaction and feedback'
                        },
                        generateStrategicPaths: {
                            type: 'boolean',
                            default: true,
                            description: 'Generate three strategic paths forward'
                        },
                    },
                    required: [],
                },
            },
        ],
        resources: [
            {
                uri: 'business://templates/all',
                name: 'Business Plan Templates',
                description: 'All available business plan templates',
                mimeType: 'application/json',
            },
            {
                uri: 'business://guidance/knowledge',
                name: 'Business Knowledge Base',
                description: 'Startup and business knowledge database',
                mimeType: 'text/markdown',
            },
        ],
    };
}
function formatMarketAnalysis(analysis) {
    return `📈 Market Analysis Results

## Market Overview
**Size**: ${analysis.marketSize}
**Growth Rate**: ${analysis.growthRate}
**Key Trends**: ${analysis.trends.join(', ')}

## Target Audience Insights
${analysis.targetAudience.map(audience => `• **${audience.segment}**: ${audience.description} (${audience.size})`).join('\n')}

## Market Opportunities
${analysis.opportunities.map((opp, i) => `${i + 1}. **${opp.title}**: ${opp.description} (${opp.potential})`).join('\n')}

## Challenges & Risks
${analysis.challenges.map((challenge, i) => `${i + 1}. ${challenge}`).join('\n')}

${analysis.competitors ? `## Key Competitors
${analysis.competitors.map(comp => `• **${comp.name}**: ${comp.description}`).join('\n')}` : ''}

## Recommendations
${analysis.recommendations.map((rec, i) => `${i + 1}. ${rec}`).join('\n')}`;
}
function formatCompetitorAnalysis(analysis) {
    return `🏆 Competitor Analysis

## Market Landscape
**Industry**: ${analysis.industry}
**Competition Level**: ${analysis.competitionLevel}

## Key Competitors (${analysis.competitors.length})
${analysis.competitors.map(comp => `### ${comp.name}
**Strengths**: ${comp.strengths.join(', ')}
**Weaknesses**: ${comp.weaknesses.join(', ')}
**Market Share**: ${comp.marketShare || 'Unknown'}
**Strategy**: ${comp.strategy}`).join('\n\n')}

## Competitive Gaps
${analysis.gaps.map((gap, i) => `${i + 1}. ${gap}`).join('\n')}

## Differentiation Opportunities
${analysis.opportunities.map((opp, i) => `${i + 1}. ${opp}`).join('\n')}

## Strategic Recommendations
${analysis.recommendations.map((rec, i) => `${i + 1}. ${rec}`).join('\n')}`;
}
function formatFinancialProjections(projections) {
    return `💰 Financial Projections (${projections.timeline} months)

## Revenue Projections
${Object.entries(projections.revenue).map(([period, amount]) => `• ${period}: ${projections.currency}${amount.toLocaleString()}`).join('\n')}

## Expense Breakdown
${Object.entries(projections.expenses).map(([category, amount]) => `• ${category}: ${projections.currency}${amount.toLocaleString()}`).join('\n')}

## Key Financial Metrics
• **Break-even Point**: Month ${projections.breakEvenMonth}
• **Total Investment Needed**: ${projections.currency}${projections.totalInvestmentNeeded.toLocaleString()}
• **ROI at ${projections.timeline} months**: ${projections.roi}%

${projections.scenarios ? `## Scenario Analysis
**Best Case**: ${projections.currency}${projections.scenarios.best.toLocaleString()}
**Base Case**: ${projections.currency}${projections.scenarios.base.toLocaleString()}
**Worst Case**: ${projections.currency}${projections.scenarios.worst.toLocaleString()}` : ''}

## Financial Recommendations
${projections.recommendations.map((rec, i) => `${i + 1}. ${rec}`).join('\n')}`;
}
function formatStartupAssessment(assessment) {
    return `🚀 Startup Assessment

## Current Stage: ${assessment.stage.toUpperCase()}
**Score**: ${assessment.score}/100

## Assessment Breakdown
${assessment.categories.map(cat => `• **${cat.name}**: ${cat.score}/10 - ${cat.feedback}`).join('\n')}

## Strengths
${assessment.strengths.map(strength => `✅ ${strength}`).join('\n')}

## Areas for Improvement
${assessment.weaknesses.map(weakness => `⚠️ ${weakness}`).join('\n')}

## Priority Actions
${assessment.nextSteps.map((step, i) => `${i + 1}. ${step.action} (${step.priority} priority)`).join('\n')}

## Recommendations by Stage
${assessment.stageRecommendations.map((rec, i) => `${i + 1}. ${rec}`).join('\n')}

**Overall Assessment**: ${assessment.overall}`;
}
function formatStartupMetrics(metrics) {
    return `📊 Startup Metrics Dashboard

## Key Performance Indicators
${Object.entries(metrics.current).map(([metric, value]) => {
        const goal = metrics.goals[metric];
        const progress = goal ? `(${Math.round((value / goal) * 100)}% of goal)` : '';
        return `• **${metric}**: ${value} ${progress}`;
    }).join('\n')}

## Growth Trends
${metrics.trends.map(trend => `• ${trend.metric}: ${trend.direction} ${trend.percentage}% (${trend.period})`).join('\n')}

## Benchmarks
${metrics.benchmarks.map(benchmark => `• ${benchmark.metric}: Your ${benchmark.yourValue} vs Industry ${benchmark.industryAverage}`).join('\n')}

## Recommendations
${metrics.recommendations.map((rec, i) => `${i + 1}. ${rec}`).join('\n')}

**Health Score**: ${metrics.healthScore}/100`;
}
function formatBusinessReviewMarkdown(review) {
    return `# Comprehensive Business Review

**Business**: ${review.businessName}  
**Review Date**: ${new Date(review.reviewDate).toLocaleDateString()}  
**Next Review**: ${new Date(review.nextReviewDate).toLocaleDateString()}

## Executive Summary

- **Current Stage**: ${review.currentStage.toUpperCase()}
- **Overall Health Score**: ${review.overallHealthScore}/100
- **Critical Gaps**: ${review.gaps.filter(g => g.severity === 'critical').length}
- **Major Strengths**: ${review.strengths.filter(s => s.impact === 'high').length}

## Business Health Analysis

### ✅ Strengths
${review.strengths.map(strength => `
#### ${strength.area}
- **Description**: ${strength.description}
- **Impact**: ${strength.impact}
- **Evidence**: 
${strength.evidence.map(e => `  - ${e}`).join('\n')}
`).join('\n')}

### ⚠️ Gaps and Weaknesses
${review.gaps.map(gap => `
#### ${gap.area} (${gap.severity})
- **Description**: ${gap.description}
- **Impact**: ${gap.impact}
- **Recommended Actions**:
${gap.recommendedActions.map(a => `  - ${a}`).join('\n')}
`).join('\n')}

## Strategic Paths Forward

${review.strategicPaths.map((path, i) => `
### Path ${i + 1}: ${path.name}

**Focus**: ${path.focus}  
**Timeline**: ${path.timeline}  
**Risk Level**: ${path.riskLevel.toUpperCase()}  
**Investment Required**: ${path.investmentRequired}

**Description**: ${path.description}

**Expected Outcome**: ${path.expectedOutcome}

**Key Actions**:
${path.keyActions.map(action => `
- **${action.action}**
  - Priority: ${action.priority}
  - Owner: ${action.owner}
  - Deadline: ${action.deadline}
  - Resources: ${action.resources.join(', ')}
`).join('\n')}

**Success Metrics**:
${path.successMetrics.map(m => `- ${m}`).join('\n')}
`).join('\n')}

## Immediate Action Plan

${review.immediateActions.map((action, i) => `
### ${i + 1}. ${action.action}

- **Rationale**: ${action.rationale}
- **Expected Impact**: ${action.expectedImpact}
- **Timeframe**: ${action.timeframe}
- **Dependencies**: ${action.dependencies.length > 0 ? action.dependencies.join(', ') : 'None'}
`).join('\n')}

## Data Sources

### Product Status
- Development Stage: ${review.dataCollected.productStatus.developmentStage}
- Features Completed: ${review.dataCollected.productStatus.featuresCompleted}/${review.dataCollected.productStatus.featuresPlanned}
- Quality Score: ${review.dataCollected.productStatus.qualityScore}/100
- User Satisfaction: ${review.dataCollected.productStatus.userSatisfaction}/100
- Technical Debt: ${review.dataCollected.productStatus.technicalDebt}

### Market Position
- Market Share: ${review.dataCollected.marketPosition.marketShare}
- Competitors: ${review.dataCollected.marketPosition.competitorCount}
- Growth Rate: ${review.dataCollected.marketPosition.marketGrowthRate}
- CAC: $${review.dataCollected.marketPosition.customerAcquisitionCost}
- LTV: $${review.dataCollected.marketPosition.lifetimeValue}

### Financial Health
- Revenue: $${review.dataCollected.financialHealth.revenue}
- Expenses: $${review.dataCollected.financialHealth.expenses}
- Runway: ${review.dataCollected.financialHealth.runway}
- Burn Rate: $${review.dataCollected.financialHealth.burnRate}/month
- Profitability: ${review.dataCollected.financialHealth.profitability}

### Team Resources
- Team Size: ${review.dataCollected.teamResources.teamSize}
- Key Roles: ${review.dataCollected.teamResources.keyRoles.join(', ')}
- Missing Roles: ${review.dataCollected.teamResources.missingRoles.join(', ')}
- Team Health: ${review.dataCollected.teamResources.teamHealth}/100

### Technical Status
- Code Quality: ${review.dataCollected.technicalStatus.codeQuality}/100
- Test Coverage: ${review.dataCollected.technicalStatus.testCoverage}%
- Deployment Frequency: ${review.dataCollected.technicalStatus.deploymentFrequency}
- System Reliability: ${review.dataCollected.technicalStatus.systemReliability}%

### Customer Insights
- Customer Count: ${review.dataCollected.customerInsights.customerCount}
- NPS Score: ${review.dataCollected.customerInsights.nps}
- Churn Rate: ${review.dataCollected.customerInsights.churnRate}%
- Support Tickets: ${review.dataCollected.customerInsights.supportTickets}

---

*This review provides a comprehensive assessment of your business. Regular reviews help track progress and adjust strategy.*`;
}
//# sourceMappingURL=index.js.map