import { JSONSchema7 } from 'json-schema';
import { randomUUID } from 'crypto';
import { createTool, createSuccessResult, createErrorResult } from '../../core/tool-framework.js';
import { ToolRegistration, RequestContext } from '../../core/types.js';

/**
 * Business Guidance Tools - 12-Factor MCP Implementation
 * 
 * Implements Factor 2: Deterministic Execution with structured outputs
 * Implements Factor 3: Stateless Processes with RequestContext
 * Implements Factor 4: Structured Outputs for LLM consumption
 */

// Input type interfaces
interface GenerateBusinessPlanInput {
  businessIdea: string;
  targetMarket: string;
  businessModel?: string;
  timeline?: string;
  includeFinancials?: boolean;
  template?: string;
}

interface AnalyzeMarketInput {
  industry: string;
  targetAudience: string;
  geographicScope?: string;
  includeCompetitors?: boolean;
  depth?: string;
}

interface CompetitorResearchInput {
  businessIdea: string;
  industry: string;
  competitors?: string[];
  analysisDepth?: string;
  includeStrengthWeakness?: boolean;
}

interface FinancialProjectionsInput {
  businessModel: string;
  revenue: Record<string, number>;
  expenses: Record<string, number>;
  timeline?: number;
  includeScenarios?: boolean;
  currency?: string;
}

interface StartupAssessmentInput {
  stage?: string;
  hasProduct?: boolean;
  hasRevenue?: boolean;
  teamSize?: number;
  hasCustomers?: boolean;
  hasFunding?: boolean;
}

interface GeneratePitchDeckInput {
  businessIdea: string;
  problemStatement: string;
  solution: string;
  targetMarket: string;
  businessModel: string;
  competitiveAdvantage: string;
  fundingAsk?: string;
  template?: string;
}

interface TrackStartupMetricsInput {
  metricsType?: string;
  currentMetrics?: Record<string, number>;
  goals?: Record<string, number>;
  timeframe?: string;
}

interface BusinessGuidanceInput {
  question: string;
  context?: string;
  stage?: string;
  industry?: string;
}

interface PerformBusinessReviewInput {
  businessName?: string;
  includeProductAnalysis?: boolean;
  includeMarketAnalysis?: boolean;
  includeFinancialAnalysis?: boolean;
  includeTeamAnalysis?: boolean;
  includeTechnicalAnalysis?: boolean;
  includeCustomerAnalysis?: boolean;
  generateStrategicPaths?: boolean;
}

/**
 * Generate a business plan
 */
const generateBusinessPlanTool = createTool<GenerateBusinessPlanInput, any>({
  name: 'generate_business_plan',
  description: 'Generate a comprehensive business plan for your startup',
  category: 'business-guidance',
  inputSchema: {
    type: 'object',
    properties: {
      businessIdea: {
        type: 'string',
        description: 'Description of your business idea',
        minLength: 1,
        maxLength: 1000
      },
      targetMarket: {
        type: 'string',
        description: 'Description of your target market',
        minLength: 1,
        maxLength: 500
      },
      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'],
    additionalProperties: false
  } as JSONSchema7,

  async execute(input: GenerateBusinessPlanInput, context: RequestContext) {
    try {
      const businessPlanId = randomUUID();
      const now = Date.now();

      // Create business plan structure
      const businessPlan = {
        id: businessPlanId,
        businessIdea: input.businessIdea,
        targetMarket: input.targetMarket,
        businessModel: input.businessModel || 'saas',
        timeline: parseInt(input.timeline || '12'),
        template: input.template || 'lean_canvas',
        includeFinancials: input.includeFinancials !== false,
        sections: [],
        nextSteps: [],
        keyMetrics: [],
        createdAt: new Date(now).toISOString(),
        updatedAt: new Date(now).toISOString()
      };

      // Generate sections based on template
      const sections = generateBusinessPlanSections(businessPlan);
      
      // Generate markdown content
      const markdown = generateBusinessPlanMarkdown(businessPlan, sections);

      // Store in database
      const result = await context.db.run(
        `INSERT INTO business_plans 
         (id, project_id, plan_type, content, metadata, status, created_at, updated_at) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          businessPlanId,
          context.projectId || 'default',
          'business_plan',
          markdown,
          JSON.stringify({
            businessIdea: input.businessIdea,
            targetMarket: input.targetMarket,
            businessModel: input.businessModel,
            timeline: input.timeline,
            template: input.template,
            includeFinancials: input.includeFinancials,
            sections: sections.map(s => s.title)
          }),
          'draft',
          now,
          now
        ]
      );

      if (!result.success) {
        return createErrorResult({
          code: 'DATABASE_ERROR',
          message: 'Failed to save business plan',
          details: { error: result.error },
          category: 'system'
        });
      }

      return createSuccessResult({
        businessPlan: {
          ...businessPlan,
          sections,
          markdown,
          nextSteps: generateNextSteps(input.businessModel || 'saas'),
          keyMetrics: generateKeyMetrics(input.businessModel || 'saas')
        },
        message: 'Business plan generated successfully',
        filePath: 'docs/business-plan.md'
      });

    } catch (error) {
      return createErrorResult({
        code: 'EXECUTION_ERROR',
        message: `Failed to generate business plan: ${error instanceof Error ? error.message : 'Unknown error'}`,
        category: 'execution'
      });
    }
  }
});

/**
 * Analyze market
 */
const analyzeMarketTool = createTool<AnalyzeMarketInput, any>({
  name: 'analyze_market',
  description: 'Perform market analysis for your business idea',
  category: 'business-guidance',
  inputSchema: {
    type: 'object',
    properties: {
      industry: {
        type: 'string',
        description: 'Industry or sector for analysis',
        minLength: 1,
        maxLength: 200
      },
      targetAudience: {
        type: 'string',
        description: 'Description of target audience',
        minLength: 1,
        maxLength: 500
      },
      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'],
    additionalProperties: false
  } as JSONSchema7,

  async execute(input: AnalyzeMarketInput, context: RequestContext) {
    try {
      const analysisId = randomUUID();
      const now = Date.now();

      // Generate market analysis
      const marketAnalysis = generateMarketAnalysis(input);

      // Store in database
      const result = await context.db.run(
        `INSERT INTO market_analyses 
         (id, project_id, industry, target_market, geographic_scope, 
          market_size, growth_rate, trends, opportunities, challenges,
          recommendations, competitors, created_at, updated_at) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          analysisId,
          context.projectId || 'default',
          input.industry,
          input.targetAudience,
          input.geographicScope || 'global',
          marketAnalysis.marketSize,
          marketAnalysis.growthRate,
          JSON.stringify(marketAnalysis.trends),
          JSON.stringify(marketAnalysis.opportunities),
          JSON.stringify(marketAnalysis.challenges),
          JSON.stringify(marketAnalysis.recommendations),
          JSON.stringify(marketAnalysis.competitors || []),
          now,
          now
        ]
      );

      if (!result.success) {
        return createErrorResult({
          code: 'DATABASE_ERROR',
          message: 'Failed to save market analysis',
          details: { error: result.error },
          category: 'system'
        });
      }

      return createSuccessResult({
        marketAnalysis,
        message: 'Market analysis completed successfully'
      });

    } catch (error) {
      return createErrorResult({
        code: 'EXECUTION_ERROR',
        message: `Failed to analyze market: ${error instanceof Error ? error.message : 'Unknown error'}`,
        category: 'execution'
      });
    }
  }
});

/**
 * Research competitors
 */
const competitorResearchTool = createTool<CompetitorResearchInput, any>({
  name: 'competitor_research',
  description: 'Research and analyze competitors in your market',
  category: 'business-guidance',
  inputSchema: {
    type: 'object',
    properties: {
      businessIdea: {
        type: 'string',
        description: 'Your business idea for comparison',
        minLength: 1,
        maxLength: 1000
      },
      industry: {
        type: 'string',
        description: 'Industry to research',
        minLength: 1,
        maxLength: 200
      },
      competitors: {
        type: 'array',
        items: { type: 'string', maxLength: 100 },
        description: 'Known competitors (optional)',
        maxItems: 20
      },
      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'],
    additionalProperties: false
  } as JSONSchema7,

  async execute(input: CompetitorResearchInput, context: RequestContext) {
    try {
      const analysisId = randomUUID();
      const now = Date.now();

      // Generate competitor analysis
      const competitorAnalysis = generateCompetitorAnalysis(input);

      // Store in database
      const result = await context.db.run(
        `INSERT INTO competitor_analyses 
         (id, project_id, industry, business_idea, competition_level,
          competitors, gaps, opportunities, recommendations, created_at, updated_at) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          analysisId,
          context.projectId || 'default',
          input.industry,
          input.businessIdea,
          competitorAnalysis.competitionLevel,
          JSON.stringify(competitorAnalysis.competitors),
          JSON.stringify(competitorAnalysis.gaps),
          JSON.stringify(competitorAnalysis.opportunities),
          JSON.stringify(competitorAnalysis.recommendations),
          now,
          now
        ]
      );

      if (!result.success) {
        return createErrorResult({
          code: 'DATABASE_ERROR',
          message: 'Failed to save competitor analysis',
          details: { error: result.error },
          category: 'system'
        });
      }

      return createSuccessResult({
        competitorAnalysis,
        message: 'Competitor research completed successfully'
      });

    } catch (error) {
      return createErrorResult({
        code: 'EXECUTION_ERROR',
        message: `Failed to research competitors: ${error instanceof Error ? error.message : 'Unknown error'}`,
        category: 'execution'
      });
    }
  }
});

/**
 * Generate financial projections
 */
const financialProjectionsTool = createTool<FinancialProjectionsInput, any>({
  name: 'financial_projections',
  description: 'Generate financial projections and scenarios',
  category: 'business-guidance',
  inputSchema: {
    type: 'object',
    properties: {
      businessModel: {
        type: 'string',
        description: 'Business model type',
        minLength: 1,
        maxLength: 100
      },
      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',
        minimum: 1,
        maximum: 120
      },
      includeScenarios: {
        type: 'boolean',
        default: true,
        description: 'Include best/worst case scenarios'
      },
      currency: {
        type: 'string',
        default: 'USD',
        description: 'Currency for projections',
        maxLength: 3
      }
    },
    required: ['businessModel', 'revenue', 'expenses'],
    additionalProperties: false
  } as JSONSchema7,

  async execute(input: FinancialProjectionsInput, context: RequestContext) {
    try {
      const projectionId = randomUUID();
      const now = Date.now();

      // Generate financial projections
      const projections = generateFinancialProjections(input);

      // Store in database
      const result = await context.db.run(
        `INSERT INTO financial_projections 
         (id, project_id, business_model, timeline, currency,
          revenue, expenses, net_income, cash_flow, break_even_month,
          total_investment_needed, roi, scenarios, assumptions, 
          recommendations, created_at, updated_at) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          projectionId,
          context.projectId || 'default',
          input.businessModel,
          input.timeline || 36,
          input.currency || 'USD',
          JSON.stringify(projections.revenue),
          JSON.stringify(projections.expenses),
          JSON.stringify(projections.netIncome),
          JSON.stringify(projections.cashFlow),
          projections.breakEvenMonth,
          projections.totalInvestmentNeeded,
          projections.roi,
          JSON.stringify(projections.scenarios || null),
          JSON.stringify(projections.assumptions),
          JSON.stringify(projections.recommendations),
          now,
          now
        ]
      );

      if (!result.success) {
        return createErrorResult({
          code: 'DATABASE_ERROR',
          message: 'Failed to save financial projections',
          details: { error: result.error },
          category: 'system'
        });
      }

      return createSuccessResult({
        projections,
        message: 'Financial projections generated successfully'
      });

    } catch (error) {
      return createErrorResult({
        code: 'EXECUTION_ERROR',
        message: `Failed to generate financial projections: ${error instanceof Error ? error.message : 'Unknown error'}`,
        category: 'execution'
      });
    }
  }
});

/**
 * Assess startup
 */
const startupAssessmentTool = createTool<StartupAssessmentInput, any>({
  name: 'startup_assessment',
  description: 'Assess your startup stage and get recommendations',
  category: 'business-guidance',
  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',
        minimum: 1,
        maximum: 1000
      },
      hasCustomers: {
        type: 'boolean',
        default: false,
        description: 'Do you have paying customers?'
      },
      hasFunding: {
        type: 'boolean',
        default: false,
        description: 'Have you raised funding?'
      }
    },
    additionalProperties: false
  } as JSONSchema7,

  async execute(input: StartupAssessmentInput, context: RequestContext) {
    try {
      const assessmentId = randomUUID();
      const now = Date.now();

      // Generate startup assessment
      const assessment = generateStartupAssessment(input);

      // Store in database
      const result = await context.db.run(
        `INSERT INTO startup_assessments 
         (id, project_id, stage, score, categories, strengths, weaknesses,
          next_steps, stage_recommendations, overall, created_at, updated_at) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          assessmentId,
          context.projectId || 'default',
          assessment.stage,
          assessment.score,
          JSON.stringify(assessment.categories),
          JSON.stringify(assessment.strengths),
          JSON.stringify(assessment.weaknesses),
          JSON.stringify(assessment.nextSteps),
          JSON.stringify(assessment.stageRecommendations),
          assessment.overall,
          now,
          now
        ]
      );

      if (!result.success) {
        return createErrorResult({
          code: 'DATABASE_ERROR',
          message: 'Failed to save startup assessment',
          details: { error: result.error },
          category: 'system'
        });
      }

      return createSuccessResult({
        assessment,
        message: 'Startup assessment completed successfully'
      });

    } catch (error) {
      return createErrorResult({
        code: 'EXECUTION_ERROR',
        message: `Failed to assess startup: ${error instanceof Error ? error.message : 'Unknown error'}`,
        category: 'execution'
      });
    }
  }
});

/**
 * Generate pitch deck
 */
const generatePitchDeckTool = createTool<GeneratePitchDeckInput, any>({
  name: 'generate_pitch_deck',
  description: 'Create a professional pitch deck for investors',
  category: 'business-guidance',
  inputSchema: {
    type: 'object',
    properties: {
      businessIdea: {
        type: 'string',
        description: 'Core business idea',
        minLength: 1,
        maxLength: 1000
      },
      problemStatement: {
        type: 'string',
        description: 'Problem you are solving',
        minLength: 1,
        maxLength: 1000
      },
      solution: {
        type: 'string',
        description: 'Your solution to the problem',
        minLength: 1,
        maxLength: 1000
      },
      targetMarket: {
        type: 'string',
        description: 'Target market description',
        minLength: 1,
        maxLength: 500
      },
      businessModel: {
        type: 'string',
        description: 'How you make money',
        minLength: 1,
        maxLength: 500
      },
      competitiveAdvantage: {
        type: 'string',
        description: 'What makes you different/better',
        minLength: 1,
        maxLength: 1000
      },
      fundingAsk: {
        type: 'string',
        description: 'Funding amount requested (optional)',
        maxLength: 100
      },
      template: {
        type: 'string',
        enum: ['standard', 'investor', 'demo_day', 'one_slide'],
        default: 'standard',
        description: 'Pitch deck template'
      }
    },
    required: ['businessIdea', 'problemStatement', 'solution', 'targetMarket', 'businessModel', 'competitiveAdvantage'],
    additionalProperties: false
  } as JSONSchema7,

  async execute(input: GeneratePitchDeckInput, context: RequestContext) {
    try {
      const pitchDeckId = randomUUID();
      const now = Date.now();

      // Generate pitch deck
      const pitchDeck = generatePitchDeck(input);

      // Store in database
      const result = await context.db.run(
        `INSERT INTO pitch_decks 
         (id, project_id, business_idea, template, slides,
          presentation_tips, key_messages, markdown, created_at, updated_at) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          pitchDeckId,
          context.projectId || 'default',
          input.businessIdea,
          input.template || 'standard',
          JSON.stringify(pitchDeck.slides),
          JSON.stringify(pitchDeck.presentationTips),
          JSON.stringify(pitchDeck.keyMessages),
          pitchDeck.markdown,
          now,
          now
        ]
      );

      if (!result.success) {
        return createErrorResult({
          code: 'DATABASE_ERROR',
          message: 'Failed to save pitch deck',
          details: { error: result.error },
          category: 'system'
        });
      }

      return createSuccessResult({
        pitchDeck,
        message: 'Pitch deck generated successfully',
        filePath: 'docs/pitch-deck.md'
      });

    } catch (error) {
      return createErrorResult({
        code: 'EXECUTION_ERROR',
        message: `Failed to generate pitch deck: ${error instanceof Error ? error.message : 'Unknown error'}`,
        category: 'execution'
      });
    }
  }
});

/**
 * Track startup metrics
 */
const trackStartupMetricsTool = createTool<TrackStartupMetricsInput, any>({
  name: 'track_startup_metrics',
  description: 'Track and analyze key startup metrics',
  category: 'business-guidance',
  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'
      }
    },
    additionalProperties: false
  } as JSONSchema7,

  async execute(input: TrackStartupMetricsInput, context: RequestContext) {
    try {
      const metricsId = randomUUID();
      const now = Date.now();

      // Generate metrics analysis
      const metrics = generateMetricsAnalysis(input);

      // Store in database
      const result = await context.db.run(
        `INSERT INTO startup_metrics 
         (id, project_id, metrics_type, current_metrics, goals, timeframe,
          trends, benchmarks, recommendations, health_score, alerts,
          created_at, updated_at) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          metricsId,
          context.projectId || 'default',
          input.metricsType || 'saas',
          JSON.stringify(input.currentMetrics || {}),
          JSON.stringify(input.goals || {}),
          input.timeframe || 'monthly',
          JSON.stringify(metrics.trends),
          JSON.stringify(metrics.benchmarks),
          JSON.stringify(metrics.recommendations),
          metrics.healthScore,
          JSON.stringify(metrics.alerts),
          now,
          now
        ]
      );

      if (!result.success) {
        return createErrorResult({
          code: 'DATABASE_ERROR',
          message: 'Failed to save startup metrics',
          details: { error: result.error },
          category: 'system'
        });
      }

      return createSuccessResult({
        metrics,
        message: 'Metrics tracked successfully'
      });

    } catch (error) {
      return createErrorResult({
        code: 'EXECUTION_ERROR',
        message: `Failed to track metrics: ${error instanceof Error ? error.message : 'Unknown error'}`,
        category: 'execution'
      });
    }
  }
});

/**
 * Business guidance
 */
const businessGuidanceTool = createTool<BusinessGuidanceInput, any>({
  name: 'business_guidance',
  description: 'Get personalized business advice and guidance',
  category: 'business-guidance',
  readOnly: true,
  inputSchema: {
    type: 'object',
    properties: {
      question: {
        type: 'string',
        description: 'Your business question or challenge',
        minLength: 1,
        maxLength: 1000
      },
      context: {
        type: 'string',
        description: 'Additional context about your situation',
        maxLength: 2000
      },
      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',
        maxLength: 100
      }
    },
    required: ['question'],
    additionalProperties: false
  } as JSONSchema7,

  async execute(input: BusinessGuidanceInput, context: RequestContext) {
    try {
      // Generate business guidance
      const guidance = generateBusinessGuidance(input);

      return createSuccessResult({
        guidance,
        message: 'Business guidance provided successfully'
      });

    } catch (error) {
      return createErrorResult({
        code: 'EXECUTION_ERROR',
        message: `Failed to provide business guidance: ${error instanceof Error ? error.message : 'Unknown error'}`,
        category: 'execution'
      });
    }
  }
});

/**
 * Perform business review
 */
const performBusinessReviewTool = createTool<PerformBusinessReviewInput, any>({
  name: 'perform_business_review',
  description: 'Perform a comprehensive business review with gap analysis and strategic recommendations',
  category: 'business-guidance',
  inputSchema: {
    type: 'object',
    properties: {
      businessName: {
        type: 'string',
        description: 'Name of your business (optional, will use project name if not provided)',
        maxLength: 200
      },
      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'
      }
    },
    additionalProperties: false
  } as JSONSchema7,

  async execute(input: PerformBusinessReviewInput, context: RequestContext) {
    try {
      const reviewId = randomUUID();
      const now = Date.now();

      // Get project name
      const projectResult = await context.db.get(
        'SELECT name FROM projects WHERE id = ?',
        [context.projectId || 'default']
      );
      const businessName = input.businessName || projectResult.data?.name || 'Unnamed Business';

      // Generate comprehensive review
      const review = await generateBusinessReview({
        ...input,
        businessName,
        projectId: context.projectId || 'default'
      }, context);

      // Store in database
      const result = await context.db.run(
        `INSERT INTO business_reviews 
         (id, project_id, business_name, current_stage, overall_health_score,
          strengths, gaps, strategic_paths, immediate_actions, data_collected,
          review_date, next_review_date, created_at, updated_at) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          reviewId,
          context.projectId || 'default',
          businessName,
          review.currentStage,
          review.overallHealthScore,
          JSON.stringify(review.strengths),
          JSON.stringify(review.gaps),
          JSON.stringify(review.strategicPaths),
          JSON.stringify(review.immediateActions),
          JSON.stringify(review.dataCollected),
          review.reviewDate,
          review.nextReviewDate,
          now,
          now
        ]
      );

      if (!result.success) {
        return createErrorResult({
          code: 'DATABASE_ERROR',
          message: 'Failed to save business review',
          details: { error: result.error },
          category: 'system'
        });
      }

      return createSuccessResult({
        review,
        message: 'Business review completed successfully',
        filePath: 'docs/business-review.md'
      });

    } catch (error) {
      return createErrorResult({
        code: 'EXECUTION_ERROR',
        message: `Failed to perform business review: ${error instanceof Error ? error.message : 'Unknown error'}`,
        category: 'execution'
      });
    }
  }
});

// Helper functions

function generateBusinessPlanSections(plan: any) {
  const sections = [];
  
  if (plan.template === 'lean_canvas') {
    sections.push(
      { title: 'Problem', content: 'Key problems your business solves', order: 1, template: plan.template },
      { title: 'Solution', content: 'Your unique solution approach', order: 2, template: plan.template },
      { title: 'Key Metrics', content: 'Metrics to measure success', order: 3, template: plan.template },
      { title: 'Unique Value Proposition', content: 'What makes you different', order: 4, template: plan.template },
      { title: 'Unfair Advantage', content: 'Your competitive moat', order: 5, template: plan.template },
      { title: 'Channels', content: 'How you reach customers', order: 6, template: plan.template },
      { title: 'Customer Segments', content: 'Your target customers', order: 7, template: plan.template },
      { title: 'Cost Structure', content: 'Main cost drivers', order: 8, template: plan.template },
      { title: 'Revenue Streams', content: 'How you make money', order: 9, template: plan.template }
    );
  } else {
    sections.push(
      { title: 'Executive Summary', content: 'Overview of your business', order: 1, template: plan.template },
      { title: 'Company Description', content: 'Detailed business description', order: 2, template: plan.template },
      { title: 'Market Analysis', content: 'Target market and competition', order: 3, template: plan.template },
      { title: 'Organization & Management', content: 'Team and structure', order: 4, template: plan.template },
      { title: 'Products/Services', content: 'What you offer', order: 5, template: plan.template },
      { title: 'Marketing & Sales', content: 'Go-to-market strategy', order: 6, template: plan.template },
      { title: 'Financial Projections', content: 'Revenue and expense forecasts', order: 7, template: plan.template }
    );
  }
  
  return sections;
}

function generateBusinessPlanMarkdown(plan: any, sections: any[]) {
  let markdown = `# Business Plan: ${plan.businessIdea}\n\n`;
  markdown += `**Target Market**: ${plan.targetMarket}\n`;
  markdown += `**Business Model**: ${plan.businessModel}\n`;
  markdown += `**Timeline**: ${plan.timeline} months\n\n`;
  
  sections.forEach(section => {
    markdown += `## ${section.title}\n\n${section.content}\n\n`;
  });
  
  return markdown;
}

function generateNextSteps(businessModel: string) {
  const steps = [
    'Validate your business idea with potential customers',
    'Build a minimum viable product (MVP)',
    'Develop your go-to-market strategy',
    'Set up legal structure and compliance',
    'Create financial tracking systems'
  ];
  
  if (businessModel === 'saas') {
    steps.push('Set up subscription billing infrastructure');
  } else if (businessModel === 'marketplace') {
    steps.push('Build supply and demand acquisition strategies');
  }
  
  return steps;
}

function generateKeyMetrics(businessModel: string) {
  const baseMetrics = ['Customer Acquisition Cost (CAC)', 'Customer Lifetime Value (LTV)', 'Monthly Burn Rate'];
  
  if (businessModel === 'saas') {
    return [...baseMetrics, 'Monthly Recurring Revenue (MRR)', 'Churn Rate', 'Net Revenue Retention'];
  } else if (businessModel === 'marketplace') {
    return [...baseMetrics, 'Gross Merchandise Value (GMV)', 'Take Rate', 'Liquidity'];
  } else if (businessModel === 'e-commerce') {
    return [...baseMetrics, 'Average Order Value', 'Conversion Rate', 'Cart Abandonment Rate'];
  }
  
  return baseMetrics;
}

function generateMarketAnalysis(input: AnalyzeMarketInput) {
  // Simplified market analysis generation
  return {
    id: randomUUID(),
    industry: input.industry,
    targetMarket: input.targetAudience,
    geographicScope: input.geographicScope || 'global',
    marketSize: '$10B-$50B',
    growthRate: '15-20% annually',
    trends: ['Digital transformation', 'Sustainability focus', 'Remote work adoption'],
    targetAudience: [
      {
        segment: 'Early Adopters',
        description: 'Tech-savvy professionals',
        size: '5-10% of market',
        characteristics: ['High disposable income', 'Values innovation'],
        painPoints: ['Current solutions too complex', 'High costs'],
        buyingBehavior: 'Online research, peer recommendations'
      }
    ],
    opportunities: [
      {
        title: 'Underserved SMB Market',
        description: 'Small businesses lack affordable solutions',
        potential: 'High',
        timeline: '6-12 months',
        requirements: ['Simplified product', 'Competitive pricing']
      }
    ],
    challenges: ['Market education needed', 'Established competitors', 'Regulatory compliance'],
    recommendations: ['Focus on differentiation', 'Build strategic partnerships', 'Invest in content marketing'],
    competitors: input.includeCompetitors ? [
      { name: 'Competitor A', description: 'Market leader', marketPosition: '35% market share' },
      { name: 'Competitor B', description: 'Fast-growing startup', marketPosition: '15% market share' }
    ] : undefined,
    timeframe: '2024-2025',
    demographics: {
      ageRange: '25-45',
      income: '$50k-$150k',
      other: ['Urban areas', 'College educated']
    }
  };
}

function generateCompetitorAnalysis(input: CompetitorResearchInput) {
  // Simplified competitor analysis generation
  return {
    industry: input.industry,
    competitionLevel: 'High',
    competitors: [
      {
        name: 'Market Leader Inc',
        description: 'Established player with 10+ years',
        strengths: ['Brand recognition', 'Large customer base', 'Strong funding'],
        weaknesses: ['Legacy technology', 'Slow innovation', 'High prices'],
        marketShare: '35%',
        strategy: 'Enterprise focus with high-touch sales',
        pricing: 'Premium pricing model',
        targetAudience: 'Fortune 500 companies',
        keyFeatures: ['Advanced analytics', '24/7 support', 'Custom integrations']
      }
    ],
    gaps: ['No solution for small businesses', 'Poor mobile experience', 'Complex onboarding'],
    opportunities: ['Self-service model', 'Freemium approach', 'Mobile-first design'],
    recommendations: ['Focus on underserved segments', 'Simplify user experience', 'Competitive pricing'],
    positioning: {
      marketGaps: ['SMB segment', 'Self-service tools'],
      differentiationOpportunities: ['Ease of use', 'Transparent pricing'],
      competitiveAdvantages: ['Modern technology stack', 'Agile development']
    }
  };
}

function generateFinancialProjections(input: FinancialProjectionsInput) {
  // Simplified financial projections
  const totalRevenue = Object.values(input.revenue).reduce((a, b) => a + b, 0);
  const totalExpenses = Object.values(input.expenses).reduce((a, b) => a + b, 0);
  
  return {
    businessModel: input.businessModel,
    timeline: input.timeline || 36,
    currency: input.currency || 'USD',
    revenue: input.revenue,
    expenses: input.expenses,
    netIncome: { 'Year 1': totalRevenue - totalExpenses },
    cashFlow: { 'Year 1': (totalRevenue - totalExpenses) * 0.8 },
    breakEvenMonth: Math.ceil(totalExpenses / (totalRevenue / 12)),
    totalInvestmentNeeded: totalExpenses * 1.5,
    roi: Math.round(((totalRevenue - totalExpenses) / totalExpenses) * 100),
    scenarios: input.includeScenarios ? {
      best: totalRevenue * 1.5,
      base: totalRevenue,
      worst: totalRevenue * 0.7
    } : undefined,
    assumptions: ['Linear growth rate', 'Stable market conditions', 'No major competition'],
    recommendations: ['Focus on recurring revenue', 'Control burn rate', 'Build financial cushion']
  };
}

function generateStartupAssessment(input: StartupAssessmentInput) {
  // Calculate score based on inputs
  let score = 20; // Base score
  if (input.hasProduct) score += 20;
  if (input.hasRevenue) score += 20;
  if (input.hasCustomers) score += 15;
  if (input.hasFunding) score += 15;
  if ((input.teamSize || 1) > 3) score += 10;
  
  return {
    stage: input.stage || 'idea',
    score,
    categories: [
      { name: 'Product', score: input.hasProduct ? 8 : 3, maxScore: 10, feedback: 'Focus on MVP development', recommendations: ['Build core features first'] },
      { name: 'Market', score: input.hasCustomers ? 7 : 4, maxScore: 10, feedback: 'Validate market demand', recommendations: ['Conduct customer interviews'] },
      { name: 'Team', score: (input.teamSize || 1) > 3 ? 7 : 5, maxScore: 10, feedback: 'Build founding team', recommendations: ['Hire key roles'] },
      { name: 'Financials', score: input.hasRevenue ? 8 : 2, maxScore: 10, feedback: 'Establish revenue model', recommendations: ['Test pricing strategies'] }
    ],
    strengths: ['Clear vision', 'Market opportunity identified'],
    weaknesses: ['Limited resources', 'No proven traction yet'],
    nextSteps: [
      { action: 'Build MVP', priority: 'high', timeline: '3 months', resources: ['Technical team', 'Design resources'] },
      { action: 'Customer validation', priority: 'high', timeline: '1 month', resources: ['Customer interviews', 'Surveys'] }
    ],
    stageRecommendations: ['Focus on problem-solution fit', 'Build minimal viable product', 'Get early customer feedback'],
    overall: 'Your startup shows promise but needs execution on key areas',
    benchmarkComparison: 'Average for this stage'
  };
}

function generatePitchDeck(input: GeneratePitchDeckInput) {
  const slides = [
    { title: 'Title Slide', content: input.businessIdea, order: 1, type: 'text' as const },
    { title: 'Problem', content: input.problemStatement, order: 2, type: 'text' as const },
    { title: 'Solution', content: input.solution, order: 3, type: 'text' as const },
    { title: 'Market Opportunity', content: `Target Market: ${input.targetMarket}`, order: 4, type: 'text' as const },
    { title: 'Business Model', content: input.businessModel, order: 5, type: 'text' as const },
    { title: 'Competitive Advantage', content: input.competitiveAdvantage, order: 6, type: 'text' as const },
    { title: 'Go-to-Market Strategy', content: 'Customer acquisition and growth strategy', order: 7, type: 'text' as const },
    { title: 'Team', content: 'Founding team and advisors', order: 8, type: 'text' as const },
    { title: 'Financials', content: 'Revenue projections and unit economics', order: 9, type: 'chart' as const },
    { title: 'The Ask', content: input.fundingAsk || 'Investment opportunity', order: 10, type: 'text' as const }
  ];
  
  const markdown = slides.map(slide => `## ${slide.title}\n\n${slide.content}\n`).join('\n');
  
  return {
    businessIdea: input.businessIdea,
    template: input.template || 'standard',
    markdown,
    slides,
    presentationTips: ['Keep it under 10 minutes', 'Tell a story', 'Use visuals effectively', 'Practice your pitch'],
    keyMessages: ['Clear problem definition', 'Unique solution', 'Large market opportunity'],
    appendix: []
  };
}

function generateMetricsAnalysis(input: TrackStartupMetricsInput) {
  const current = input.currentMetrics || {};
  const goals = input.goals || {};
  
  // Calculate health score
  let healthScore = 50;
  const metricCount = Object.keys(current).length;
  if (metricCount > 0) {
    const achievementRates = Object.keys(current).map(key => {
      const goal = goals[key];
      return goal ? Math.min((current[key] / goal) * 100, 100) : 50;
    });
    healthScore = Math.round(achievementRates.reduce((a, b) => a + b, 0) / achievementRates.length);
  }
  
  return {
    metricsType: input.metricsType || 'saas',
    current,
    goals,
    timeframe: input.timeframe || 'monthly',
    trends: [
      { metric: 'MRR', direction: 'up' as const, percentage: 15, period: 'month' },
      { metric: 'Churn', direction: 'down' as const, percentage: 5, period: 'month' }
    ],
    benchmarks: [
      { metric: 'CAC Payback', yourValue: 12, industryAverage: 18, percentile: 75 }
    ],
    recommendations: ['Focus on reducing churn', 'Improve conversion funnel', 'Increase average contract value'],
    healthScore,
    alerts: [
      { metric: 'Burn Rate', status: 'warning' as const, message: 'Higher than planned', recommendation: 'Review expenses' }
    ]
  };
}

function generateBusinessGuidance(input: BusinessGuidanceInput) {
  // Simplified business guidance generation
  return {
    question: input.question,
    answer: `Based on your ${input.stage || 'idea'} stage in the ${input.industry || 'technology'} industry, here's my guidance...`,
    recommendations: [
      'Focus on customer validation',
      'Build lean and iterate quickly',
      'Measure key metrics consistently'
    ],
    nextSteps: [
      'Define success metrics',
      'Create 90-day action plan',
      'Schedule regular reviews'
    ],
    resources: [
      'Lean Startup methodology',
      'Y Combinator startup library',
      'First Round Review articles'
    ],
    confidence: 0.85,
    relatedTopics: ['Product-market fit', 'Growth strategies', 'Fundraising']
  };
}

async function generateBusinessReview(input: any, context: RequestContext) {
  // Collect data from various sources
  const dataCollected = {
    productStatus: {
      developmentStage: 'MVP',
      featuresCompleted: 15,
      featuresPlanned: 25,
      qualityScore: 75,
      userSatisfaction: 80,
      technicalDebt: 'Medium'
    },
    marketPosition: {
      marketShare: '0.1%',
      competitorCount: 5,
      uniqueValueProp: 'Simplified user experience',
      marketGrowthRate: '20%',
      customerAcquisitionCost: 150,
      lifetimeValue: 1500
    },
    financialHealth: {
      revenue: 50000,
      expenses: 80000,
      runway: '12 months',
      burnRate: 30000,
      profitability: 'Pre-revenue',
      fundingStatus: 'Bootstrapped'
    },
    teamResources: {
      teamSize: 5,
      keyRoles: ['CEO', 'CTO', 'Developer'],
      missingRoles: ['Sales', 'Marketing'],
      teamHealth: 85,
      productivity: 75,
      culture: 'Startup mindset'
    },
    technicalStatus: {
      codeQuality: 80,
      testCoverage: 65,
      deploymentFrequency: 'Weekly',
      systemReliability: 95,
      securityScore: 70,
      scalability: 'Good'
    },
    customerInsights: {
      customerCount: 50,
      nps: 40,
      churnRate: 10,
      supportTickets: 25,
      featureRequests: ['Mobile app', 'API access'],
      topComplaints: ['Onboarding complexity']
    }
  };
  
  // Calculate overall health score
  const overallHealthScore = 72;
  
  return {
    businessName: input.businessName,
    currentStage: 'early_stage',
    overallHealthScore,
    strengths: [
      {
        area: 'Product Development',
        description: 'Strong technical foundation with good code quality',
        impact: 'high' as const,
        evidence: ['80% code quality score', '95% system reliability']
      }
    ],
    gaps: [
      {
        area: 'Sales & Marketing',
        description: 'Missing key sales and marketing roles',
        severity: 'critical' as const,
        impact: 'Limited growth potential without dedicated sales team',
        recommendedActions: ['Hire sales lead', 'Develop marketing strategy']
      }
    ],
    strategicPaths: [
      {
        name: 'Product-Led Growth',
        focus: 'Improve product experience to drive organic growth',
        description: 'Focus on product improvements and user experience',
        timeline: '6-12 months',
        riskLevel: 'medium' as const,
        keyActions: [
          {
            action: 'Simplify onboarding flow',
            priority: 'immediate' as const,
            owner: 'Product Team',
            resources: ['UX Designer', 'Developer time'],
            deadline: '30 days'
          }
        ],
        expectedOutcome: 'Reduced churn and increased organic growth',
        investmentRequired: '$50k-$100k',
        successMetrics: ['NPS > 50', 'Churn < 5%', 'Organic growth > 20% MoM']
      }
    ],
    immediateActions: [
      {
        action: 'Hire sales lead',
        rationale: 'Critical gap in go-to-market execution',
        expectedImpact: 'Accelerated revenue growth',
        timeframe: '30 days',
        dependencies: ['Budget approval', 'Recruitment process']
      }
    ],
    dataCollected,
    reviewDate: new Date().toISOString(),
    nextReviewDate: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString()
  };
}

/**
 * Setup business guidance tools
 */
export async function setupBusinessGuidanceTools(): Promise<ToolRegistration> {
  return {
    module: 'business-guidance',
    tools: [
      generateBusinessPlanTool,
      // Note: Interactive business plan wizard removed for now as it requires special workflow handling
      analyzeMarketTool,
      competitorResearchTool,
      financialProjectionsTool,
      startupAssessmentTool,
      generatePitchDeckTool,
      trackStartupMetricsTool,
      businessGuidanceTool,
      performBusinessReviewTool
    ]
  };
}