import { ConfigManager } from '../../config/config-manager.js';
import { 
  BusinessPlan, 
  MarketAnalysis, 
  CompetitorAnalysis, 
  FinancialProjection,
  StartupMetrics,
  StartupAssessment,
  PitchDeck,
  BusinessGuidanceResponse,
  BusinessKnowledge,
  BusinessReview,
  ReviewStrength,
  ReviewGap,
  StrategicPath,
  ImmediateAction,
  ReviewDataSources,
  ProductReviewData,
  MarketReviewData,
  FinancialReviewData,
  TeamReviewData,
  TechnicalReviewData,
  CustomerReviewData,
  PathAction
} from './types.js';
import { StartupTemplates } from './templates.js';
import { promises as fs } from 'fs';
import path from 'path';

export class BusinessAnalyzer {
  private configManager: ConfigManager;
  private knowledgeBase: Map<string, BusinessKnowledge>;
  private knowledgePath: string;

  constructor(configManager: ConfigManager) {
    this.configManager = configManager;
    this.knowledgeBase = new Map();
    this.knowledgePath = '';
    // Don't call async method in constructor
  }
  
  async init(): Promise<void> {
    await this.initializeKnowledgeBase();
  }
  
  private generateId(): string {
    // Generate hex-only ID to match test expectations
    const hex = () => Math.floor(Math.random() * 0xf).toString(16);
    const segment = () => Array.from({ length: 8 }, hex).join('');
    return `${segment()}-${segment()}`;
  }
  

  async generateBusinessPlan(options: {
    businessIdea: string;
    targetMarket: string;
    businessModel: string;
    timeline: number;
    includeFinancials?: boolean;
    template: string;
  }): Promise<BusinessPlan> {
    // Validation
    if (!options.businessIdea || options.businessIdea.trim().length === 0) {
      throw new Error('Business idea is required');
    }
    if (!options.targetMarket || options.targetMarket.trim().length === 0) {
      throw new Error('Target market is required');
    }
    if (!options.businessModel || options.businessModel.trim().length === 0) {
      throw new Error('Business model is required');
    }
    if (!options.timeline || options.timeline <= 0) {
      throw new Error('Timeline must be positive');
    }
    if (!options.template) {
      throw new Error('Template is required');
    }
    const template = StartupTemplates.getBusinessPlanTemplate(options.template);
    const sections = await this.generatePlanSections(options, template);
    const markdown = this.formatBusinessPlanMarkdown(sections, options);
    const nextSteps = this.generateBusinessPlanNextSteps(options);
    const keyMetrics = this.getRelevantMetrics(options.businessModel);
    const now = new Date().toISOString();
    
    const plan: BusinessPlan = {
      id: `plan-${this.generateId()}`,
      businessIdea: options.businessIdea,
      targetMarket: options.targetMarket,
      businessModel: options.businessModel,
      timeline: options.timeline,
      template: options.template,
      markdown,
      sections,
      nextSteps,
      keyMetrics,
      createdAt: now,
      updatedAt: now,
    };
    
    if (options.includeFinancials) {
      // Create default financial data if not provided
      const financialOptions = {
        businessModel: options.businessModel,
        revenue: { 'product': 10000, 'service': 5000 },
        expenses: { 'operations': 8000, 'marketing': 3000 },
        timeline: options.timeline,
        includeScenarios: false,
        currency: 'USD'
      };
      plan.financials = await this.generateFinancialProjections(financialOptions);
    }
    
    return plan;
  }

  async analyzeMarket(options: {
    industry: string;
    targetMarket: string;
    geographicScope: string;
    includeCompetitors?: boolean;
    includeDemographics?: boolean;
    depth?: string;
  }): Promise<MarketAnalysis> {
    // Validation
    if (!options.industry || !options.targetMarket || !options.geographicScope) {
      throw new Error('Industry, target market, and geographic scope are required');
    }
    const marketData = await this.gatherMarketData(options);
    const opportunities = this.identifyMarketOpportunities(marketData, options);
    const challenges = this.identifyMarketChallenges(options.industry);
    const recommendations = this.generateMarketRecommendations(marketData, opportunities);

    const analysis: MarketAnalysis = {
      id: `market-${this.generateId()}`,
      industry: options.industry,
      targetMarket: options.targetMarket,
      geographicScope: options.geographicScope,
      marketSize: marketData.size,
      growthRate: marketData.growthRate,
      trends: marketData.trends,
      targetAudience: marketData.segments,
      opportunities,
      challenges,
      recommendations,
      competitors: options.includeCompetitors ? marketData.competitors : undefined,
      timeframe: new Date().toISOString(),
    };
    
    if (options.includeDemographics) {
      analysis.demographics = {
        ageRange: '25-45',
        income: '$50k-$150k',
        behavior: 'Tech-savvy early adopters who are problem-aware'
      } as any;
    }
    
    return analysis;
  }

  async analyzeCompetitors(options: {
    businessIdea: string;
    industry: string;
    competitors: string[];
    analysisDepth: string;
    includeStrengthWeakness: boolean;
  }): Promise<CompetitorAnalysis> {
    const competitors = await this.researchCompetitors(options);
    const gaps = this.identifyCompetitiveGaps(competitors, options.businessIdea);
    const opportunities = this.identifyCompetitiveOpportunities(gaps, competitors);
    const recommendations = this.generateCompetitiveRecommendations(competitors, gaps);

    const result: CompetitorAnalysis = {
      industry: options.industry,
      competitionLevel: this.assessCompetitionLevel(competitors),
      competitors,
      gaps,
      opportunities,
      recommendations,
    };
    
    // Add positioning analysis for comprehensive depth
    if (options.analysisDepth === 'comprehensive') {
      result.positioning = {
        marketGaps: gaps.slice(0, 3),
        differentiationOpportunities: opportunities.slice(0, 3),
        competitiveAdvantages: this.identifyCompetitiveAdvantages(options.businessIdea, competitors),
      };
    }
    
    return result;
  }

  async generateFinancialProjections(options: {
    businessModel: string;
    revenue: Record<string, number>;
    expenses: Record<string, number>;
    timeline: number;
    includeScenarios: boolean;
    currency: string;
  }): Promise<FinancialProjection> {
    const projections = this.calculateProjections(options);
    const scenarios = options.includeScenarios ? this.generateScenarios(projections) : undefined;
    const breakEvenMonth = this.calculateBreakEven(projections);
    const roi = this.calculateROI(projections, options.timeline);
    const assumptions = this.getFinancialAssumptions(options.businessModel);
    const recommendations = this.generateFinancialRecommendations(projections);

    // Create projections array from the monthly data
    const projectionsArray = Object.keys(projections.revenue).map(month => ({
      period: month,
      revenue: projections.revenue[month],
      expenses: projections.expenses[month],
      profit: projections.netIncome[month]
    }));
    
    return {
      businessModel: options.businessModel,
      timeline: options.timeline,
      currency: options.currency,
      revenue: projections.revenue,
      expenses: projections.expenses,
      netIncome: projections.netIncome,
      cashFlow: projections.cashFlow,
      breakEvenMonth,
      totalInvestmentNeeded: this.calculateInvestmentNeeded(projections),
      roi,
      scenarios,
      assumptions,
      recommendations,
      projections: projectionsArray
    } as any;
  }

  async assessStartup(options: {
    businessPlanId?: string;
    currentStage?: string;
    teamSize?: number;
    monthsInDevelopment?: number;
    hasCustomers?: boolean;
    monthlyRevenue?: number;
    stage?: string;
    hasProduct?: boolean;
    hasRevenue?: boolean;
    hasFunding?: boolean;
  }): Promise<StartupAssessment> {
    const categories = this.assessStartupCategories(options);
    const overallScore = categories.reduce((sum, cat) => sum + cat.score, 0) / categories.length * 10;
    const strengths = this.identifyStartupStrengths(categories);
    const weaknesses = this.identifyStartupWeaknesses(categories);
    const nextSteps = this.generateStartupNextSteps(options, weaknesses);
    const stageRecommendations = this.getStageSpecificRecommendations(options.stage);
    const overall = this.generateOverallAssessment(overallScore, options.stage);

    return {
      id: `assessment-${this.generateId()}`,
      businessPlanId: options.businessPlanId,
      stage: options.stage || options.currentStage || 'unknown',
      score: Math.round(overallScore),
      overallScore: Math.round(overallScore),
      maturityLevel: this.getMaturityLevel(overallScore),
      dimensions: {
        product: { score: 7, feedback: 'Product development on track' },
        market: { score: 6, feedback: 'Market validation needed' },
        team: { score: 8, feedback: 'Strong team composition' },
        financial: { score: 5, feedback: 'Revenue model needs refinement' },
        operations: { score: 6, feedback: 'Operations scaling required' }
      },
      categories,
      strengths,
      weaknesses,
      recommendations: nextSteps,
      nextSteps,
      stageRecommendations,
      overall,
    } as any;
  }

  async generatePitchDeck(options: {
    businessIdea: string;
    problemStatement: string;
    solution: string;
    targetMarket: string;
    businessModel: string;
    competitiveAdvantage: string;
    fundingAsk?: string;
    template: string;
  }): Promise<PitchDeck> {
    const template = StartupTemplates.getPitchDeckTemplate(options.template);
    const slides = this.generatePitchSlides(options, template);
    const markdown = this.formatPitchDeckMarkdown(slides, options);
    const presentationTips = this.getPresentationTips(options.template);
    const keyMessages = this.extractKeyMessages(options);

    return {
      businessIdea: options.businessIdea,
      template: options.template,
      markdown,
      slides,
      presentationTips,
      keyMessages,
    };
  }

  async trackMetrics(options: {
    metricsType: string;
    currentMetrics: Record<string, number>;
    goals: Record<string, number>;
    timeframe: string;
  }): Promise<StartupMetrics> {
    const trends = this.calculateMetricTrends(options.currentMetrics, options.timeframe);
    const benchmarks = this.getBenchmarks(options.metricsType, options.currentMetrics);
    const recommendations = this.generateMetricRecommendations(options, trends, benchmarks);
    const healthScore = this.calculateHealthScore(options.currentMetrics, options.goals, options.metricsType);
    const alerts = this.generateMetricAlerts(options.currentMetrics, options.goals, trends);

    return {
      metricsType: options.metricsType,
      current: options.currentMetrics,
      goals: options.goals,
      timeframe: options.timeframe,
      trends,
      benchmarks,
      recommendations,
      healthScore,
      alerts,
    };
  }

  async planFundingStrategy(options: {
    businessPlanId: string;
    fundingGoal: number;
    currentStage: string;
    useOfFunds?: string[];
    timeline: number;
  }): Promise<any> {
    const recommendedSources = this.recommendFundingSources(options.currentStage, options.fundingGoal);
    const timeline = this.createFundingTimeline(options.timeline);
    const milestones = this.generateFundingMilestones(options);
    
    return {
      id: `funding-${this.generateId()}`,
      businessPlanId: options.businessPlanId,
      fundingGoal: options.fundingGoal,
      recommendedSources,
      timeline,
      milestones,
      useOfFunds: options.useOfFunds || ['product-development', 'marketing', 'operations'],
      stage: options.currentStage,
    };
  }
  
  private recommendFundingSources(stage: string, amount: number): string[] {
    if (stage === 'idea' && amount < 200000) {
      return ['angel-investors', 'grants', 'friends-and-family', 'crowdfunding'];
    }
    if (stage === 'growth' && amount > 1000000) {
      return ['venture-capital', 'series-a', 'institutional-investors'];
    }
    return ['seed-funding', 'angel-investors', 'accelerators'];
  }
  
  private createFundingTimeline(months: number): any {
    return {
      preparation: Math.floor(months * 0.2),
      outreach: Math.floor(months * 0.3),
      negotiation: Math.floor(months * 0.3),
      closing: Math.floor(months * 0.2),
    };
  }
  
  private generateFundingMilestones(options: any): any[] {
    return [
      { month: 1, milestone: 'Complete pitch deck and financial projections' },
      { month: 2, milestone: 'Begin investor outreach' },
      { month: Math.floor(options.timeline / 2), milestone: 'First round of meetings' },
      { month: options.timeline - 1, milestone: 'Term sheet negotiations' },
      { month: options.timeline, milestone: 'Close funding round' },
    ];
  }

  async provideGuidance(request: {
    question: string;
    context?: string;
    stage?: string;
    industry?: string;
  }): Promise<BusinessGuidanceResponse> {
    const relevantKnowledge = this.findRelevantKnowledge(request);
    const answer = this.generateAnswer(request, relevantKnowledge);
    const recommendations = this.generateContextualRecommendations(request, relevantKnowledge);
    const nextSteps = this.generateActionableNextSteps(request, recommendations);
    const resources = this.findRelevantResources(request);
    const confidence = this.calculateConfidence(relevantKnowledge, request);
    const relatedTopics = this.findRelatedTopics(request);

    return {
      question: request.question,
      answer,
      recommendations,
      nextSteps,
      resources,
      confidence,
      relatedTopics,
    };
  }

  async performComprehensiveReview(options: {
    businessName?: string;
    includeProductAnalysis: boolean;
    includeMarketAnalysis: boolean;
    includeFinancialAnalysis: boolean;
    includeTeamAnalysis: boolean;
    includeTechnicalAnalysis: boolean;
    includeCustomerAnalysis: boolean;
    generateStrategicPaths: boolean;
  }): Promise<BusinessReview> {
    // Gather data from various sources
    const dataCollected = await this.gatherReviewData(options);
    
    // Determine current stage based on collected data
    const currentStage = this.determineBusinessStage(dataCollected);
    
    // Analyze strengths
    const strengths = this.analyzeStrengths(dataCollected);
    
    // Identify gaps
    const gaps = this.identifyGaps(dataCollected, currentStage);
    
    // Calculate overall health score
    const overallHealthScore = this.calculateOverallHealthScore(dataCollected, strengths, gaps);
    
    // Generate strategic paths
    const strategicPaths = options.generateStrategicPaths ? 
      this.generateStrategicPaths(dataCollected, gaps, currentStage) : [];
    
    // Determine immediate actions
    const immediateActions = this.determineImmediateActions(gaps, strategicPaths);
    
    // Set review dates
    const reviewDate = new Date().toISOString();
    const nextReviewDate = new Date();
    nextReviewDate.setMonth(nextReviewDate.getMonth() + 3); // Quarterly reviews
    
    return {
      businessName: options.businessName || await this.getProjectName(),
      currentStage,
      overallHealthScore,
      strengths,
      gaps,
      strategicPaths,
      immediateActions,
      dataCollected,
      reviewDate,
      nextReviewDate: nextReviewDate.toISOString(),
    };
  }

  private async initializeKnowledgeBase(): Promise<void> {
    const storageManager = this.configManager.getStorageManager();
    const location = await storageManager.getStorageLocation();
    this.knowledgePath = path.join(location.data, 'business', 'knowledge.json');

    await this.loadKnowledgeBase();
    await this.populateDefaultKnowledge();
  }

  private async loadKnowledgeBase(): Promise<void> {
    try {
      const data = await fs.readFile(this.knowledgePath, 'utf-8');
      const knowledgeArray: BusinessKnowledge[] = JSON.parse(data);
      
      this.knowledgeBase.clear();
      for (const knowledge of knowledgeArray) {
        this.knowledgeBase.set(knowledge.topic, knowledge);
      }
    } catch (error) {
      // File doesn't exist, start with empty knowledge base
      this.knowledgeBase.clear();
    }
  }

  private async saveKnowledgeBase(): Promise<void> {
    await fs.mkdir(path.dirname(this.knowledgePath), { recursive: true });
    const knowledgeArray = Array.from(this.knowledgeBase.values());
    await fs.writeFile(this.knowledgePath, JSON.stringify(knowledgeArray, null, 2));
  }

  private async populateDefaultKnowledge(): Promise<void> {
    const defaultKnowledge: BusinessKnowledge[] = [
      {
        topic: 'mvp_development',
        category: 'product',
        content: 'A Minimum Viable Product (MVP) is the simplest version of your product that allows you to test core assumptions with real users. Focus on essential features that solve the primary problem.',
        stage: ['idea', 'mvp'],
        industry: ['technology', 'saas', 'mobile'],
        confidence: 0.9,
        sources: ['Lean Startup', 'Product Management Best Practices'],
        lastUpdated: new Date().toISOString(),
      },
      {
        topic: 'funding_stages',
        category: 'finance',
        content: 'Startup funding typically progresses through stages: Pre-seed (idea validation), Seed (MVP and early traction), Series A (proven product-market fit), Series B+ (scaling and growth).',
        stage: ['idea', 'mvp', 'early_stage', 'growth'],
        industry: ['all'],
        confidence: 0.95,
        sources: ['Venture Capital Guidelines', 'Startup Finance'],
        lastUpdated: new Date().toISOString(),
      },
      {
        topic: 'customer_validation',
        category: 'marketing',
        content: 'Customer validation involves systematically testing your assumptions about customer problems and solutions through interviews, surveys, and behavioral data before building features.',
        stage: ['idea', 'mvp', 'early_stage'],
        industry: ['all'],
        confidence: 0.9,
        sources: ['Customer Development', 'Lean Startup'],
        lastUpdated: new Date().toISOString(),
      },
    ];

    for (const knowledge of defaultKnowledge) {
      if (!this.knowledgeBase.has(knowledge.topic)) {
        this.knowledgeBase.set(knowledge.topic, knowledge);
      }
    }

    await this.saveKnowledgeBase();
  }

  private async generatePlanSections(options: any, template: any): Promise<any[]> {
    const sections = [];

    // Executive Summary
    sections.push({
      title: 'Executive Summary',
      content: `${options.businessIdea}\n\nTarget Market: ${options.targetMarket}\nBusiness Model: ${options.businessModel}`,
      order: 1,
      template: options.template,
    });

    // Problem Statement
    sections.push({
      title: 'Problem Statement',
      content: 'Clearly define the problem your business solves and why it matters to your target customers.',
      order: 2,
      template: options.template,
    });

    // Solution
    sections.push({
      title: 'Solution',
      content: 'Describe your solution and how it uniquely addresses the identified problem.',
      order: 3,
      template: options.template,
    });

    // Market Analysis
    sections.push({
      title: 'Market Analysis',
      content: `Target Market: ${options.targetMarket}\n\nMarket research and analysis will be conducted to validate market size, growth trends, and customer segments.`,
      order: 4,
      template: options.template,
    });

    // Business Model
    sections.push({
      title: 'Business Model',
      content: `Revenue Model: ${options.businessModel}\n\nDetailed explanation of how the business will generate revenue and achieve profitability.`,
      order: 5,
      template: options.template,
    });

    return sections;
  }

  private formatBusinessPlanMarkdown(sections: any[], options: any): string {
    let markdown = `# ${options.businessIdea} - Business Plan\n\n`;
    markdown += `**Generated**: ${new Date().toLocaleDateString()}\n`;
    markdown += `**Timeline**: ${options.timeline} months\n`;
    markdown += `**Business Model**: ${options.businessModel}\n\n`;

    sections.forEach(section => {
      markdown += `## ${section.title}\n\n${section.content}\n\n`;
    });

    return markdown;
  }

  private generateBusinessPlanNextSteps(options: any): string[] {
    const steps = [
      'Validate core assumptions with target customers',
      'Develop minimum viable product (MVP)',
      'Conduct market research and competitive analysis',
      'Build founding team with complementary skills',
      'Create detailed financial projections',
    ];

    if (options.businessModel === 'saas') {
      steps.push('Set up analytics and user tracking');
      steps.push('Develop customer onboarding process');
    }

    return steps;
  }

  private getRelevantMetrics(businessModel: string): string[] {
    const metricMap: Record<string, string[]> = {
      saas: ['Monthly Recurring Revenue (MRR)', 'Customer Acquisition Cost (CAC)', 'Customer Lifetime Value (CLV)', 'Churn Rate', 'Net Promoter Score (NPS)'],
      marketplace: ['Gross Merchandise Value (GMV)', 'Take Rate', 'Active Users', 'Transaction Volume', 'Seller/Buyer Ratio'],
      'e-commerce': ['Conversion Rate', 'Average Order Value (AOV)', 'Cart Abandonment Rate', 'Customer Acquisition Cost', 'Return on Ad Spend (ROAS)'],
      default: ['Revenue Growth', 'Customer Acquisition Cost', 'Customer Lifetime Value', 'Market Share', 'Profitability'],
    };

    return metricMap[businessModel] || metricMap.default;
  }

  private async gatherMarketData(options: any): Promise<any> {
    // Simulate market data gathering
    return {
      size: this.estimateMarketSize(options.industry, options.geographicScope),
      growthRate: this.estimateGrowthRate(options.industry),
      trends: this.getIndustryTrends(options.industry),
      segments: this.identifyMarketSegments(options.targetMarket),
      competitors: options.includeCompetitors ? this.getCompetitorSummaries(options.industry) : [],
    };
  }

  private estimateMarketSize(industry: string, scope: string): string {
    const sizeMap: Record<string, Record<string, string>> = {
      technology: {
        global: '$4.8 trillion',
        national: '$480 billion',
        local: '$48 million',
      },
      'software development': {
        global: '$5.2 trillion',
        national: '$520 billion',
        local: '$52 million',
      },
      healthcare: {
        global: '$8.5 trillion',
        national: '$850 billion',
        local: '$85 million',
      },
      default: {
        global: '$1 trillion',
        national: '$100 billion',
        local: '$10 million',
      },
    };

    // Map geographic scopes to size categories
    const scopeMapping: Record<string, string> = {
      'North America': 'national',
      'United States': 'national',
      'Global': 'global',
      'International': 'global',
      'Local': 'local',
      'Regional': 'local'
    };
    
    const mappedScope = scopeMapping[scope] || 'national';
    const industryData = sizeMap[industry.toLowerCase()] || sizeMap[industry] || sizeMap.default;
    return industryData[mappedScope] || industryData.national || '$100 billion';
  }

  private estimateGrowthRate(industry: string): string {
    const growthMap: Record<string, string> = {
      technology: '8-12% annually',
      healthcare: '5-8% annually',
      finance: '6-10% annually',
      education: '4-7% annually',
      default: '5-8% annually',
    };

    return growthMap[industry] || growthMap.default;
  }

  private getIndustryTrends(industry: string): string[] {
    const trendMap: Record<string, string[]> = {
      technology: ['AI/ML adoption', 'Cloud migration', 'Remote work tools', 'Cybersecurity focus'],
      healthcare: ['Telemedicine growth', 'AI diagnostics', 'Personalized medicine', 'Digital health records'],
      finance: ['Digital banking', 'Cryptocurrency adoption', 'RegTech solutions', 'Open banking APIs'],
      default: ['Digital transformation', 'Sustainability focus', 'Customer experience improvement'],
    };

    return trendMap[industry] || trendMap.default;
  }

  private identifyMarketSegments(targetAudience: string): any[] {
    // Simple segmentation based on audience description
    return [
      {
        segment: 'Primary Target',
        description: targetAudience,
        size: 'To be determined through research',
        characteristics: ['Early adopters', 'Tech-savvy', 'Problem-aware'],
        painPoints: ['Current solutions are inadequate', 'Time-consuming processes'],
        buyingBehavior: 'Research-driven decision making',
      },
    ];
  }

  private getCompetitorSummaries(industry: string): any[] {
    // Placeholder competitor data
    return [
      {
        name: 'Market Leader',
        description: `Established player in ${industry}`,
        marketPosition: 'Leader',
      },
      {
        name: 'Emerging Competitor',
        description: `Growing startup in ${industry} space`,
        marketPosition: 'Challenger',
      },
    ];
  }

  private identifyMarketOpportunities(marketData: any, options: any): any[] {
    return [
      {
        title: 'Underserved Market Segment',
        description: 'Opportunity to serve customers not well-addressed by current solutions',
        potential: 'High',
        timeline: '6-12 months',
        requirements: ['Market research', 'Product development', 'Customer validation'],
      },
      {
        title: 'Technology Innovation',
        description: 'Leverage new technology to create competitive advantage',
        potential: 'Medium',
        timeline: '12-18 months',
        requirements: ['Technical expertise', 'R&D investment', 'IP protection'],
      },
    ];
  }

  private identifyMarketChallenges(industry: string): string[] {
    const challengeMap: Record<string, string[]> = {
      technology: ['Rapid technology changes', 'High competition', 'Talent shortage', 'Regulatory uncertainty'],
      healthcare: ['Regulatory compliance', 'Long sales cycles', 'Privacy concerns', 'Integration challenges'],
      finance: ['Heavy regulation', 'Security requirements', 'Consumer trust', 'Legacy system integration'],
      default: ['Market saturation', 'Customer acquisition costs', 'Economic uncertainty', 'Competitive pressure'],
    };

    return challengeMap[industry] || challengeMap.default;
  }

  private generateMarketRecommendations(marketData: any, opportunities: any[]): string[] {
    return [
      'Focus on primary target segment for initial market entry',
      'Develop unique value proposition based on identified gaps',
      'Build strategic partnerships to accelerate market penetration',
      'Implement customer feedback loops for continuous improvement',
      'Monitor competitive landscape and adapt strategy accordingly',
    ];
  }

  private async researchCompetitors(options: any): Promise<any[]> {
    // Simulate competitor research
    const competitors = [];
    
    if (options.competitors.length > 0) {
      // Use provided competitors
      for (const competitorName of options.competitors) {
        competitors.push({
          name: competitorName,
          description: `${competitorName} operates in the ${options.industry} space`,
          strengths: ['Established brand', 'Market presence'],
          weaknesses: ['Legacy technology', 'Limited innovation'],
          strategy: 'Market leadership through scale',
          marketShare: '15%',
          pricingModel: 'Subscription-based',
        });
      }
    } else {
      // Generate example competitors
      competitors.push(
        {
          name: 'Industry Leader Co',
          description: `Leading company in ${options.industry}`,
          strengths: ['Market dominance', 'Financial resources', 'Brand recognition'],
          weaknesses: ['Slow innovation', 'High prices', 'Poor customer service'],
          strategy: 'Maintain market position through acquisitions',
        },
        {
          name: 'Innovative Startup',
          description: `Emerging player disrupting ${options.industry}`,
          strengths: ['Innovative technology', 'Agile development', 'Customer focus'],
          weaknesses: ['Limited resources', 'Small market share', 'Unproven scalability'],
          strategy: 'Disrupt through technology innovation',
        }
      );
    }

    return competitors;
  }

  private identifyCompetitiveGaps(competitors: any[], businessIdea: string): string[] {
    return [
      'Limited mobile-first approach in current solutions',
      'Poor user experience in existing products',
      'Lack of integration capabilities',
      'High pricing barriers for small businesses',
      'Insufficient customer support and onboarding',
    ];
  }

  private identifyCompetitiveOpportunities(gaps: string[], competitors: any[]): string[] {
    return [
      'Develop superior user experience to differentiate',
      'Target underserved customer segments',
      'Offer competitive pricing with better value',
      'Build strong customer success program',
      'Focus on integration and ecosystem approach',
    ];
  }

  private generateCompetitiveRecommendations(competitors: any[], gaps: string[]): string[] {
    return [
      'Position uniquely against identified competitive gaps',
      'Monitor competitor moves and respond strategically',
      'Build sustainable competitive advantages',
      'Focus on customer experience as key differentiator',
      'Develop strategic partnerships to compete effectively',
    ];
  }

  private assessCompetitionLevel(competitors: any[]): string {
    if (competitors.length < 3) return 'Low';
    if (competitors.length < 6) return 'Moderate';
    return 'High';
  }

  private identifyCompetitiveAdvantages(businessIdea: string, competitors: any[]): string[] {
    return [
      'First-mover advantage in specific market segment',
      'Superior technology or proprietary solution',
      'Better pricing model with sustainable margins',
      'Stronger brand positioning and customer loyalty',
      'More efficient operational model',
    ];
  }
  
  private getMaturityLevel(score: number): string {
    if (score >= 80) return 'Mature';
    if (score >= 60) return 'Growing';
    if (score >= 40) return 'Developing';
    return 'Early';
  }

  private calculateProjections(options: any): any {
    const months = options.timeline;
    const projections = {
      revenue: {} as Record<string, number>,
      expenses: {} as Record<string, number>,
      netIncome: {} as Record<string, number>,
      cashFlow: {} as Record<string, number>,
    };

    // Simple projection calculation
    for (let month = 1; month <= months; month++) {
      const growthFactor = Math.pow(1.1, month - 1); // 10% monthly growth
      
      const monthlyRevenue = Object.values(options.revenue as Record<string, number>).reduce((sum: number, val: number) => sum + val, 0) * growthFactor;
      const monthlyExpenses = Object.values(options.expenses as Record<string, number>).reduce((sum: number, val: number) => sum + val, 0);
      
      projections.revenue[`Month ${month}`] = Math.round(monthlyRevenue);
      projections.expenses[`Month ${month}`] = Math.round(monthlyExpenses);
      projections.netIncome[`Month ${month}`] = Math.round(monthlyRevenue - monthlyExpenses);
      projections.cashFlow[`Month ${month}`] = month === 1 ? 
        projections.netIncome[`Month ${month}`] : 
        projections.cashFlow[`Month ${month - 1}`] + projections.netIncome[`Month ${month}`];
    }

    return projections;
  }

  private generateScenarios(projections: any): any {
    const baseRevenue = Object.values(projections.revenue as Record<string, number>).reduce((sum: number, val: number) => sum + val, 0);
    
    return {
      best: Math.round(baseRevenue * 1.5), // 50% better
      base: Math.round(baseRevenue),
      worst: Math.round(baseRevenue * 0.7), // 30% worse
    };
  }

  private calculateBreakEven(projections: any): number {
    for (const [month, income] of Object.entries(projections.netIncome)) {
      if ((income as number) > 0) {
        return parseInt(month.split(' ')[1]);
      }
    }
    return -1; // Never breaks even in timeline
  }

  private calculateROI(projections: any, timeline: number): number {
    const totalRevenue = Object.values(projections.revenue as Record<string, number>).reduce((sum: number, val: number) => sum + val, 0);
    const totalExpenses = Object.values(projections.expenses as Record<string, number>).reduce((sum: number, val: number) => sum + val, 0);
    const investment = totalExpenses; // Simplified
    
    if (investment === 0) return 0;
    return Math.round(((totalRevenue - totalExpenses) / investment) * 100);
  }

  private calculateInvestmentNeeded(projections: any): number {
    let maxNegativeCashFlow = 0;
    for (const cashFlow of Object.values(projections.cashFlow)) {
      if ((cashFlow as number) < maxNegativeCashFlow) {
        maxNegativeCashFlow = cashFlow as number;
      }
    }
    return Math.abs(maxNegativeCashFlow);
  }

  private getFinancialAssumptions(businessModel: string): string[] {
    const assumptionMap: Record<string, string[]> = {
      saas: ['10% monthly growth rate', 'Customer churn rate of 5%', 'Average customer lifetime of 24 months'],
      marketplace: ['Take rate of 3-5%', 'Transaction volume growth of 15% monthly', 'Network effects drive growth'],
      'e-commerce': ['Conversion rate of 2-3%', 'Average order value increases over time', 'Customer acquisition cost decreases with scale'],
      default: ['Linear growth in early stages', 'Operating leverage improves over time', 'Market conditions remain stable'],
    };

    return assumptionMap[businessModel] || assumptionMap.default;
  }

  private generateFinancialRecommendations(projections: any): string[] {
    return [
      'Monitor cash flow closely and maintain adequate reserves',
      'Focus on improving unit economics and customer lifetime value',
      'Diversify revenue streams to reduce dependency',
      'Optimize cost structure for better margins',
      'Plan funding needs well in advance of cash requirements',
    ];
  }

  private assessStartupCategories(options: any): any[] {
    const categories = [
      {
        name: 'Product Development',
        score: options.hasProduct ? 8 : 3,
        maxScore: 10,
        feedback: options.hasProduct ? 'Good progress on product development' : 'Need to focus on building MVP',
        recommendations: options.hasProduct ? ['Iterate based on user feedback'] : ['Define core features and build MVP'],
      },
      {
        name: 'Market Validation',
        score: options.hasCustomers ? 7 : 2,
        maxScore: 10,
        feedback: options.hasCustomers ? 'Market validation in progress' : 'Need customer validation',
        recommendations: options.hasCustomers ? ['Scale customer acquisition'] : ['Conduct customer interviews'],
      },
      {
        name: 'Revenue Generation',
        score: options.hasRevenue ? 8 : 1,
        maxScore: 10,
        feedback: options.hasRevenue ? 'Revenue generation established' : 'No revenue yet',
        recommendations: options.hasRevenue ? ['Focus on revenue growth'] : ['Develop monetization strategy'],
      },
      {
        name: 'Team Building',
        score: Math.min(options.teamSize * 2, 10),
        maxScore: 10,
        feedback: options.teamSize > 1 ? 'Team building in progress' : 'Solo founder - consider co-founders',
        recommendations: options.teamSize > 3 ? ['Optimize team structure'] : ['Recruit key team members'],
      },
      {
        name: 'Funding',
        score: options.hasFunding ? 6 : 2,
        maxScore: 10,
        feedback: options.hasFunding ? 'Funding secured' : 'No external funding yet',
        recommendations: options.hasFunding ? ['Use funding efficiently'] : ['Explore funding options'],
      },
    ];

    return categories;
  }

  private identifyStartupStrengths(categories: any[]): string[] {
    return categories
      .filter(cat => cat.score >= 7)
      .map(cat => `Strong ${cat.name.toLowerCase()}`);
  }

  private identifyStartupWeaknesses(categories: any[]): string[] {
    return categories
      .filter(cat => cat.score < 5)
      .map(cat => `Needs improvement in ${cat.name.toLowerCase()}`);
  }

  private generateStartupNextSteps(options: any, weaknesses: string[]): any[] {
    const steps = [];

    if (!options.hasProduct) {
      steps.push({
        action: 'Build minimum viable product (MVP)',
        priority: 'high' as const,
        timeline: '2-3 months',
        resources: ['Development team', 'Technical resources'],
      });
    }

    if (!options.hasCustomers) {
      steps.push({
        action: 'Validate product-market fit with target customers',
        priority: 'high' as const,
        timeline: '1-2 months',
        resources: ['Customer interviews', 'User testing'],
      });
    }

    if (!options.hasRevenue) {
      steps.push({
        action: 'Develop and test monetization strategy',
        priority: 'medium' as const,
        timeline: '1-3 months',
        resources: ['Pricing research', 'Payment systems'],
      });
    }

    return steps;
  }

  private getStageSpecificRecommendations(stage: string): string[] {
    const recommendationMap: Record<string, string[]> = {
      idea: ['Validate problem and solution fit', 'Build MVP', 'Talk to potential customers'],
      mvp: ['Achieve product-market fit', 'Gather user feedback', 'Iterate on core features'],
      early_stage: ['Scale customer acquisition', 'Optimize unit economics', 'Build repeatable processes'],
      growth: ['Expand market reach', 'Diversify revenue streams', 'Build competitive moats'],
      scale: ['International expansion', 'Strategic partnerships', 'Prepare for exit or IPO'],
    };

    return recommendationMap[stage] || recommendationMap.idea;
  }

  private generateOverallAssessment(score: number, stage: string): string {
    if (score >= 80) return `Excellent progress for ${stage} stage startup. Well positioned for growth.`;
    if (score >= 60) return `Good foundation with some areas for improvement at ${stage} stage.`;
    if (score >= 40) return `Moderate progress. Focus on key weaknesses to advance from ${stage} stage.`;
    return `Early stage with significant work needed. Focus on fundamentals for ${stage} stage.`;
  }

  private generatePitchSlides(options: any, template: any): any[] {
    const slides = [
      {
        title: 'Problem',
        content: options.problemStatement,
        order: 1,
        type: 'text' as const,
        speakerNotes: 'Clearly articulate the pain point your audience faces',
      },
      {
        title: 'Solution',
        content: options.solution,
        order: 2,
        type: 'text' as const,
        speakerNotes: 'Explain how your solution uniquely addresses the problem',
      },
      {
        title: 'Market Size',
        content: `Target Market: ${options.targetMarket}`,
        order: 3,
        type: 'chart' as const,
        speakerNotes: 'Show the size and growth potential of your market',
      },
      {
        title: 'Business Model',
        content: options.businessModel,
        order: 4,
        type: 'text' as const,
        speakerNotes: 'Explain how you will make money',
      },
      {
        title: 'Competitive Advantage',
        content: options.competitiveAdvantage,
        order: 5,
        type: 'bullets' as const,
        speakerNotes: 'Highlight what makes you different and defensible',
      },
    ];

    if (options.fundingAsk) {
      slides.push({
        title: 'Funding Ask',
        content: `Seeking: ${options.fundingAsk}`,
        order: 6,
        type: 'text' as const,
        speakerNotes: 'Clearly state funding amount and use of funds',
      });
    }

    return slides;
  }

  private formatPitchDeckMarkdown(slides: any[], options: any): string {
    let markdown = `# ${options.businessIdea} - Pitch Deck\n\n`;
    markdown += `**Generated**: ${new Date().toLocaleDateString()}\n\n`;

    slides.forEach(slide => {
      markdown += `## Slide ${slide.order}: ${slide.title}\n\n${slide.content}\n\n`;
      if (slide.speakerNotes) {
        markdown += `*Speaker Notes: ${slide.speakerNotes}*\n\n`;
      }
    });

    return markdown;
  }

  private getPresentationTips(template: string): string[] {
    return [
      'Keep slides visually simple with minimal text',
      'Tell a compelling story that flows logically',
      'Practice your delivery and timing',
      'Prepare for questions and objections',
      'Show passion and expertise for your domain',
      'Use data to support your claims',
      'End with a clear call to action',
    ];
  }

  private extractKeyMessages(options: any): string[] {
    return [
      `Solving: ${options.problemStatement.substring(0, 50)}...`,
      `Solution: ${options.solution.substring(0, 50)}...`,
      `Market: ${options.targetMarket}`,
      `Advantage: ${options.competitiveAdvantage.substring(0, 50)}...`,
    ];
  }

  private calculateMetricTrends(metrics: Record<string, number>, timeframe: string): any[] {
    // Simulate trend calculation
    return Object.keys(metrics).map(metric => ({
      metric,
      direction: Math.random() > 0.5 ? 'up' : 'down' as const,
      percentage: Math.round(Math.random() * 20),
      period: timeframe,
    }));
  }

  private getBenchmarks(metricsType: string, currentMetrics: Record<string, number>): any[] {
    // Simulate industry benchmarks
    return Object.entries(currentMetrics).map(([metric, value]) => ({
      metric,
      yourValue: value,
      industryAverage: Math.round(value * (0.8 + Math.random() * 0.4)),
      percentile: Math.round(Math.random() * 100),
    }));
  }

  private generateMetricRecommendations(options: any, trends: any[], benchmarks: any[]): string[] {
    const recommendations = [
      'Focus on improving metrics that are below industry benchmarks',
      'Investigate declining trends and implement corrective actions',
      'Set up automated tracking and alerting for key metrics',
    ];

    if (options.metricsType === 'saas') {
      recommendations.push('Optimize customer onboarding to reduce churn');
      recommendations.push('Implement customer success programs');
    }

    return recommendations;
  }

  private calculateHealthScore(current: Record<string, number>, goals: Record<string, number>, metricsType: string): number {
    const scores = Object.keys(current).map(metric => {
      const currentValue = current[metric];
      const goalValue = goals[metric];
      
      if (!goalValue) return 50; // No goal set
      
      const progress = Math.min((currentValue / goalValue) * 100, 100);
      return Math.max(progress, 0);
    });

    return Math.round(scores.reduce((sum, score) => sum + score, 0) / scores.length);
  }

  private generateMetricAlerts(current: Record<string, number>, goals: Record<string, number>, trends: any[]): any[] {
    const alerts = [];

    // Check for metrics significantly below goals
    for (const [metric, value] of Object.entries(current)) {
      const goal = goals[metric];
      if (goal && value < goal * 0.7) {
        alerts.push({
          metric,
          status: 'critical' as const,
          message: `${metric} is significantly below target`,
          recommendation: `Focus on improving ${metric} performance`,
        });
      }
    }

    // Check for declining trends
    const decliningTrends = trends.filter(trend => trend.direction === 'down' && trend.percentage > 10);
    for (const trend of decliningTrends) {
      alerts.push({
        metric: trend.metric,
        status: 'warning' as const,
        message: `${trend.metric} declining by ${trend.percentage}%`,
        recommendation: `Investigate causes of ${trend.metric} decline`,
      });
    }

    return alerts;
  }

  private findRelevantKnowledge(request: any): BusinessKnowledge[] {
    const relevant = [];
    const queryLower = request.question.toLowerCase();

    for (const knowledge of this.knowledgeBase.values()) {
      if (knowledge.topic.includes(queryLower) || 
          knowledge.content.toLowerCase().includes(queryLower) ||
          (request.stage && knowledge.stage.includes(request.stage)) ||
          (request.industry && knowledge.industry.includes(request.industry))) {
        relevant.push(knowledge);
      }
    }

    return relevant.sort((a, b) => b.confidence - a.confidence).slice(0, 5);
  }

  private generateAnswer(request: any, knowledge: BusinessKnowledge[]): string {
    if (knowledge.length === 0) {
      return `Based on general business principles, here's guidance for your question about "${request.question}": This is a common challenge in business development. Consider researching best practices, consulting with industry experts, and testing different approaches to find what works for your specific situation.`;
    }

    const primaryKnowledge = knowledge[0];
    let answer = primaryKnowledge.content;

    if (request.context) {
      answer += `\n\nGiven your context (${request.context}), this is particularly relevant because it aligns with common challenges at your stage.`;
    }

    return answer;
  }

  private generateContextualRecommendations(request: any, knowledge: BusinessKnowledge[]): string[] {
    const recommendations = [];

    if (request.stage === 'idea') {
      recommendations.push('Focus on customer discovery and problem validation');
      recommendations.push('Build a minimal viable product (MVP)');
    } else if (request.stage === 'mvp') {
      recommendations.push('Gather user feedback and iterate quickly');
      recommendations.push('Measure product-market fit indicators');
    }

    if (knowledge.length > 0) {
      const categories = [...new Set(knowledge.map(k => k.category))];
      categories.forEach(category => {
        switch (category) {
          case 'finance':
            recommendations.push('Develop detailed financial projections');
            break;
          case 'marketing':
            recommendations.push('Create a go-to-market strategy');
            break;
          case 'product':
            recommendations.push('Focus on core feature development');
            break;
        }
      });
    }

    return recommendations.slice(0, 5);
  }

  private generateActionableNextSteps(request: any, recommendations: string[]): string[] {
    return recommendations.map(rec => {
      // Convert recommendations to actionable steps
      if (rec.includes('financial projections')) {
        return 'Create 12-month financial projections this week';
      }
      if (rec.includes('customer discovery')) {
        return 'Interview 10 potential customers within 2 weeks';
      }
      if (rec.includes('MVP')) {
        return 'Define and build MVP within 6-8 weeks';
      }
      return rec;
    }).slice(0, 3);
  }

  private findRelevantResources(request: any): string[] {
    const resources = [
      'Lean Startup methodology',
      'Customer Development by Steve Blank',
      'Business Model Canvas',
      'Y Combinator Startup School',
    ];

    if (request.stage === 'idea') {
      resources.push('The Mom Test by Rob Fitzpatrick');
    } else if (request.stage === 'growth') {
      resources.push('Blitzscaling by Reid Hoffman');
    }

    return resources.slice(0, 4);
  }

  private calculateConfidence(knowledge: BusinessKnowledge[], request: any): number {
    if (knowledge.length === 0) return 0.3;
    
    const avgConfidence = knowledge.reduce((sum, k) => sum + k.confidence, 0) / knowledge.length;
    
    // Boost confidence if stage/industry matches
    let bonus = 0;
    if (request.stage && knowledge.some(k => k.stage.includes(request.stage))) bonus += 0.1;
    if (request.industry && knowledge.some(k => k.industry.includes(request.industry))) bonus += 0.1;
    
    return Math.min(avgConfidence + bonus, 1.0);
  }

  private findRelatedTopics(request: any): string[] {
    const topics = Array.from(this.knowledgeBase.keys());
    const queryWords = request.question.toLowerCase().split(/\s+/);
    
    const related = topics.filter(topic => 
      queryWords.some((word: string) => topic.includes(word)) ||
      topic.includes(request.stage || '') ||
      topic.includes(request.industry || '')
    );

    return related.slice(0, 5);
  }

  private async gatherReviewData(options: any): Promise<ReviewDataSources> {
    const productStatus = await this.gatherProductData(options.includeProductAnalysis);
    const marketPosition = await this.gatherMarketReviewData(options.includeMarketAnalysis);
    const financialHealth = await this.gatherFinancialData(options.includeFinancialAnalysis);
    const teamResources = await this.gatherTeamData(options.includeTeamAnalysis);
    const technicalStatus = await this.gatherTechnicalData(options.includeTechnicalAnalysis);
    const customerInsights = await this.gatherCustomerData(options.includeCustomerAnalysis);

    return {
      productStatus,
      marketPosition,
      financialHealth,
      teamResources,
      technicalStatus,
      customerInsights,
    };
  }

  private async gatherProductData(include: boolean): Promise<ProductReviewData> {
    if (!include) {
      return {
        developmentStage: 'unknown',
        featuresCompleted: 0,
        featuresPlanned: 0,
        qualityScore: 0,
        userSatisfaction: 0,
        technicalDebt: 'unknown',
      };
    }

    // In a real implementation, this would gather data from kanban boards, development tools, etc.
    // For now, we'll simulate some data
    return {
      developmentStage: 'MVP',
      featuresCompleted: 15,
      featuresPlanned: 25,
      qualityScore: 75,
      userSatisfaction: 80,
      technicalDebt: 'moderate',
    };
  }

  private async gatherMarketReviewData(include: boolean): Promise<MarketReviewData> {
    if (!include) {
      return {
        marketShare: 'unknown',
        competitorCount: 0,
        uniqueValueProp: 'unknown',
        marketGrowthRate: 'unknown',
        customerAcquisitionCost: 0,
        lifetimeValue: 0,
      };
    }

    return {
      marketShare: '0.5%',
      competitorCount: 12,
      uniqueValueProp: 'AI-powered automation for startups',
      marketGrowthRate: '15% annually',
      customerAcquisitionCost: 150,
      lifetimeValue: 1200,
    };
  }

  private async gatherFinancialData(include: boolean): Promise<FinancialReviewData> {
    if (!include) {
      return {
        revenue: 0,
        expenses: 0,
        runway: 'unknown',
        burnRate: 0,
        profitability: 'unknown',
        fundingStatus: 'unknown',
      };
    }

    return {
      revenue: 25000,
      expenses: 35000,
      runway: '12 months',
      burnRate: 10000,
      profitability: 'not yet',
      fundingStatus: 'bootstrapped',
    };
  }

  private async gatherTeamData(include: boolean): Promise<TeamReviewData> {
    if (!include) {
      return {
        teamSize: 0,
        keyRoles: [],
        missingRoles: [],
        teamHealth: 0,
        productivity: 0,
        culture: 'unknown',
      };
    }

    return {
      teamSize: 3,
      keyRoles: ['CEO', 'CTO', 'Developer'],
      missingRoles: ['Marketing Lead', 'Sales', 'Designer'],
      teamHealth: 85,
      productivity: 70,
      culture: 'collaborative and agile',
    };
  }

  private async gatherTechnicalData(include: boolean): Promise<TechnicalReviewData> {
    if (!include) {
      return {
        codeQuality: 0,
        testCoverage: 0,
        deploymentFrequency: 'unknown',
        systemReliability: 0,
        securityScore: 0,
        scalability: 'unknown',
      };
    }

    return {
      codeQuality: 82,
      testCoverage: 65,
      deploymentFrequency: 'weekly',
      systemReliability: 99.5,
      securityScore: 75,
      scalability: 'ready for 10x growth',
    };
  }

  private async gatherCustomerData(include: boolean): Promise<CustomerReviewData> {
    if (!include) {
      return {
        customerCount: 0,
        nps: 0,
        churnRate: 0,
        supportTickets: 0,
        featureRequests: [],
        topComplaints: [],
      };
    }

    return {
      customerCount: 50,
      nps: 45,
      churnRate: 5,
      supportTickets: 25,
      featureRequests: ['Mobile app', 'API access', 'Advanced analytics'],
      topComplaints: ['Onboarding complexity', 'Documentation'],
    };
  }

  private determineBusinessStage(data: ReviewDataSources): 'idea' | 'mvp' | 'early_stage' | 'growth' | 'scale' {
    if (data.productStatus.developmentStage === 'idea' || data.productStatus.featuresCompleted === 0) {
      return 'idea';
    }
    if (data.customerInsights.customerCount < 100 && data.productStatus.developmentStage === 'MVP') {
      return 'mvp';
    }
    if (data.customerInsights.customerCount < 1000) {
      return 'early_stage';
    }
    if (data.customerInsights.customerCount < 10000) {
      return 'growth';
    }
    return 'scale';
  }

  private analyzeStrengths(data: ReviewDataSources): ReviewStrength[] {
    const strengths: ReviewStrength[] = [];

    // Product strengths
    if (data.productStatus.qualityScore > 70) {
      strengths.push({
        area: 'Product Quality',
        description: 'High code quality and user satisfaction indicate strong product foundation',
        impact: 'high' as const,
        evidence: [
          `Quality score: ${data.productStatus.qualityScore}/100`,
          `User satisfaction: ${data.productStatus.userSatisfaction}/100`,
        ],
      });
    }

    // Market strengths
    if (data.marketPosition.lifetimeValue > data.marketPosition.customerAcquisitionCost * 3) {
      strengths.push({
        area: 'Unit Economics',
        description: 'Strong LTV:CAC ratio indicates sustainable business model',
        impact: 'high' as const,
        evidence: [
          `LTV: $${data.marketPosition.lifetimeValue}`,
          `CAC: $${data.marketPosition.customerAcquisitionCost}`,
          `Ratio: ${(data.marketPosition.lifetimeValue / data.marketPosition.customerAcquisitionCost).toFixed(1)}:1`,
        ],
      });
    }

    // Technical strengths
    if (data.technicalStatus.systemReliability > 99) {
      strengths.push({
        area: 'System Reliability',
        description: 'Excellent system uptime ensures customer trust',
        impact: 'medium' as const,
        evidence: [
          `Uptime: ${data.technicalStatus.systemReliability}%`,
          `Deployment frequency: ${data.technicalStatus.deploymentFrequency}`,
        ],
      });
    }

    // Team strengths
    if (data.teamResources.teamHealth > 80) {
      strengths.push({
        area: 'Team Culture',
        description: 'Strong team health and culture drives productivity',
        impact: 'high' as const,
        evidence: [
          `Team health: ${data.teamResources.teamHealth}/100`,
          `Culture: ${data.teamResources.culture}`,
        ],
      });
    }

    return strengths;
  }

  private identifyGaps(data: ReviewDataSources, stage: string): ReviewGap[] {
    const gaps: ReviewGap[] = [];

    // Product gaps
    if (data.productStatus.featuresCompleted < data.productStatus.featuresPlanned * 0.5) {
      gaps.push({
        area: 'Product Development',
        description: 'Significant feature backlog may delay market competitiveness',
        severity: 'major' as const,
        impact: 'Slower time to market and potential customer dissatisfaction',
        recommendedActions: [
          'Prioritize MVP features using customer feedback',
          'Consider hiring additional developers',
          'Implement agile development practices',
        ],
      });
    }

    // Market gaps
    if (data.marketPosition.competitorCount > 10 && data.marketPosition.marketShare === '0.5%') {
      gaps.push({
        area: 'Market Position',
        description: 'Low market share in competitive environment',
        severity: 'critical' as const,
        impact: 'Difficulty in customer acquisition and growth',
        recommendedActions: [
          'Develop stronger differentiation strategy',
          'Increase marketing budget and efforts',
          'Consider niche market focus',
        ],
      });
    }

    // Financial gaps
    if (data.financialHealth.revenue < data.financialHealth.expenses) {
      gaps.push({
        area: 'Financial Sustainability',
        description: 'Negative cash flow threatens business continuity',
        severity: 'critical' as const,
        impact: `Current runway: ${data.financialHealth.runway}`,
        recommendedActions: [
          'Reduce burn rate by optimizing expenses',
          'Accelerate revenue growth initiatives',
          'Consider fundraising options',
        ],
      });
    }

    // Team gaps
    if (data.teamResources.missingRoles.length > 2) {
      gaps.push({
        area: 'Team Capabilities',
        description: 'Key roles missing for sustainable growth',
        severity: 'major' as const,
        impact: 'Limited capacity for scaling operations',
        recommendedActions: [
          `Prioritize hiring: ${data.teamResources.missingRoles.slice(0, 2).join(', ')}`,
          'Consider fractional executives',
          'Develop existing team skills',
        ],
      });
    }

    // Technical gaps
    if (data.technicalStatus.testCoverage < 70) {
      gaps.push({
        area: 'Technical Quality',
        description: 'Low test coverage increases risk of bugs and regressions',
        severity: 'minor' as const,
        impact: 'Potential quality issues and slower development',
        recommendedActions: [
          'Implement TDD practices',
          'Set coverage targets for new code',
          'Add tests for critical paths',
        ],
      });
    }

    // Customer gaps
    if (data.customerInsights.nps < 50) {
      gaps.push({
        area: 'Customer Satisfaction',
        description: 'Below-average NPS indicates customer experience issues',
        severity: 'major' as const,
        impact: 'Higher churn and difficulty in organic growth',
        recommendedActions: [
          'Conduct customer interviews to understand pain points',
          'Improve onboarding process',
          'Enhance customer support',
        ],
      });
    }

    return gaps;
  }

  private calculateOverallHealthScore(
    data: ReviewDataSources, 
    strengths: ReviewStrength[], 
    gaps: ReviewGap[]
  ): number {
    let score = 50; // Base score

    // Product factors
    score += (data.productStatus.qualityScore / 100) * 10;
    score += (data.productStatus.userSatisfaction / 100) * 10;

    // Market factors
    const ltvcac = data.marketPosition.lifetimeValue / (data.marketPosition.customerAcquisitionCost || 1);
    score += Math.min(ltvcac * 2, 10);

    // Financial factors
    if (data.financialHealth.revenue > data.financialHealth.expenses) {
      score += 10;
    }

    // Team factors
    score += (data.teamResources.teamHealth / 100) * 5;

    // Technical factors
    score += (data.technicalStatus.codeQuality / 100) * 5;
    score += (data.technicalStatus.testCoverage / 100) * 5;

    // Customer factors
    score += (data.customerInsights.nps / 100) * 5;

    // Adjust for gaps
    const criticalGaps = gaps.filter(g => g.severity === 'critical').length;
    const majorGaps = gaps.filter(g => g.severity === 'major').length;
    score -= criticalGaps * 10;
    score -= majorGaps * 5;

    return Math.max(0, Math.min(100, Math.round(score)));
  }

  private generateStrategicPaths(
    data: ReviewDataSources, 
    gaps: ReviewGap[], 
    stage: string
  ): StrategicPath[] {
    const paths: StrategicPath[] = [];

    // Conservative Path
    paths.push({
      name: 'Conservative Growth',
      focus: 'Profitability and sustainability',
      description: 'Focus on achieving profitability through careful expense management and organic growth',
      timeline: '12-18 months',
      riskLevel: 'low' as const,
      expectedOutcome: 'Sustainable 20-30% annual growth with positive cash flow',
      investmentRequired: 'Minimal external funding needed',
      successMetrics: [
        'Achieve positive cash flow within 6 months',
        'Maintain 90%+ customer retention',
        'Grow revenue by 25% annually',
      ],
      keyActions: this.generateConservativeActions(data, gaps),
    });

    // Aggressive Path
    paths.push({
      name: 'Aggressive Scaling',
      focus: 'Market capture and rapid growth',
      description: 'Pursue aggressive growth through significant investment in sales, marketing, and product development',
      timeline: '6-12 months',
      riskLevel: 'high' as const,
      expectedOutcome: '10x growth potential with market leadership position',
      investmentRequired: '$2-5M Series A funding',
      successMetrics: [
        'Achieve 10x customer growth',
        'Capture 10%+ market share',
        'Build team to 50+ employees',
      ],
      keyActions: this.generateAggressiveActions(data, gaps),
    });

    // Balanced Path
    paths.push({
      name: 'Balanced Innovation',
      focus: 'Product excellence with sustainable growth',
      description: 'Balance product innovation with measured growth, focusing on customer success and quality',
      timeline: '9-15 months',
      riskLevel: 'medium' as const,
      expectedOutcome: '3-5x growth with strong product-market fit',
      investmentRequired: '$500K-1M seed extension',
      successMetrics: [
        'Achieve product-market fit with NPS > 70',
        'Triple revenue while maintaining quality',
        'Build sustainable competitive advantages',
      ],
      keyActions: this.generateBalancedActions(data, gaps),
    });

    return paths;
  }

  private generateConservativeActions(data: ReviewDataSources, gaps: ReviewGap[]): PathAction[] {
    const actions: PathAction[] = [];
    const today = new Date();

    actions.push({
      action: 'Optimize burn rate to extend runway',
      priority: 'immediate' as const,
      owner: 'CEO/CFO',
      resources: ['Financial analysis', 'Expense audit'],
      deadline: new Date(today.getTime() + 30 * 24 * 60 * 60 * 1000).toISOString(), // 30 days
    });

    actions.push({
      action: 'Focus on highest-value customer segments',
      priority: 'immediate' as const,
      owner: 'Head of Sales',
      resources: ['Customer data analysis', 'Sales team'],
      deadline: new Date(today.getTime() + 45 * 24 * 60 * 60 * 1000).toISOString(), // 45 days
    });

    actions.push({
      action: 'Implement customer success program',
      priority: 'short-term' as const,
      owner: 'Customer Success Manager',
      resources: ['CS tools', 'Training budget'],
      deadline: new Date(today.getTime() + 60 * 24 * 60 * 60 * 1000).toISOString(), // 60 days
    });

    actions.push({
      action: 'Automate repetitive processes',
      priority: 'short-term' as const,
      owner: 'CTO',
      resources: ['Development team', 'Automation tools'],
      deadline: new Date(today.getTime() + 90 * 24 * 60 * 60 * 1000).toISOString(), // 90 days
    });

    return actions;
  }

  private generateAggressiveActions(data: ReviewDataSources, gaps: ReviewGap[]): PathAction[] {
    const actions: PathAction[] = [];
    const today = new Date();

    actions.push({
      action: 'Raise Series A funding',
      priority: 'immediate' as const,
      owner: 'CEO',
      resources: ['Pitch deck', 'Financial projections', 'Legal counsel'],
      deadline: new Date(today.getTime() + 90 * 24 * 60 * 60 * 1000).toISOString(), // 90 days
    });

    actions.push({
      action: 'Triple sales and marketing team',
      priority: 'immediate' as const,
      owner: 'VP Sales/Marketing',
      resources: ['Recruiting budget', 'Hiring plan'],
      deadline: new Date(today.getTime() + 60 * 24 * 60 * 60 * 1000).toISOString(), // 60 days
    });

    actions.push({
      action: 'Launch major product features',
      priority: 'short-term' as const,
      owner: 'VP Product',
      resources: ['Expanded dev team', 'Product roadmap'],
      deadline: new Date(today.getTime() + 120 * 24 * 60 * 60 * 1000).toISOString(), // 120 days
    });

    actions.push({
      action: 'Expand to new markets/segments',
      priority: 'short-term' as const,
      owner: 'Head of Growth',
      resources: ['Market research', 'Localization budget'],
      deadline: new Date(today.getTime() + 150 * 24 * 60 * 60 * 1000).toISOString(), // 150 days
    });

    return actions;
  }

  private generateBalancedActions(data: ReviewDataSources, gaps: ReviewGap[]): PathAction[] {
    const actions: PathAction[] = [];
    const today = new Date();

    actions.push({
      action: 'Achieve product-market fit validation',
      priority: 'immediate' as const,
      owner: 'Product Manager',
      resources: ['User research', 'Analytics tools'],
      deadline: new Date(today.getTime() + 45 * 24 * 60 * 60 * 1000).toISOString(), // 45 days
    });

    actions.push({
      action: 'Build world-class customer experience',
      priority: 'immediate' as const,
      owner: 'Head of Customer Success',
      resources: ['UX team', 'Support tools'],
      deadline: new Date(today.getTime() + 60 * 24 * 60 * 60 * 1000).toISOString(), // 60 days
    });

    actions.push({
      action: 'Develop unique competitive advantages',
      priority: 'short-term' as const,
      owner: 'CTO/CPO',
      resources: ['R&D budget', 'Innovation team'],
      deadline: new Date(today.getTime() + 90 * 24 * 60 * 60 * 1000).toISOString(), // 90 days
    });

    actions.push({
      action: 'Build strategic partnerships',
      priority: 'short-term' as const,
      owner: 'Head of Partnerships',
      resources: ['BD team', 'Partnership budget'],
      deadline: new Date(today.getTime() + 120 * 24 * 60 * 60 * 1000).toISOString(), // 120 days
    });

    return actions;
  }

  private determineImmediateActions(gaps: ReviewGap[], paths: StrategicPath[]): ImmediateAction[] {
    const actions: ImmediateAction[] = [];

    // Address critical gaps first
    const criticalGaps = gaps.filter(g => g.severity === 'critical');
    
    if (criticalGaps.length > 0) {
      criticalGaps.forEach(gap => {
        actions.push({
          action: gap.recommendedActions[0] || `Address ${gap.area} immediately`,
          rationale: `Critical gap: ${gap.description}`,
          expectedImpact: 'Prevent business failure or major setback',
          timeframe: '0-30 days',
          dependencies: [],
        });
      });
    }

    // Add path-specific immediate actions
    if (paths.length > 0) {
      const immediatePathActions = paths[0].keyActions.filter(a => a.priority === 'immediate');
      if (immediatePathActions.length > 0) {
        actions.push({
          action: immediatePathActions[0].action,
          rationale: `First step in ${paths[0].name} strategy`,
          expectedImpact: 'Set foundation for chosen growth path',
          timeframe: '0-45 days',
          dependencies: immediatePathActions[0].resources,
        });
      }
    }

    // Ensure we have at least 3 immediate actions
    while (actions.length < 3 && gaps.length > actions.length) {
      const gap = gaps[actions.length];
      actions.push({
        action: gap.recommendedActions[0] || `Improve ${gap.area}`,
        rationale: gap.description,
        expectedImpact: `Reduce ${gap.severity} gap in ${gap.area}`,
        timeframe: '30-60 days',
        dependencies: [],
      });
    }

    return actions.slice(0, 5); // Return top 5 immediate actions
  }

  private async getProjectName(): Promise<string> {
    try {
      const packageJsonPath = path.join(process.cwd(), 'package.json');
      const packageJson = await fs.readFile(packageJsonPath, 'utf-8');
      const parsed = JSON.parse(packageJson);
      return parsed.name || 'Unnamed Project';
    } catch {
      return path.basename(process.cwd());
    }
  }
}