import { BusinessTemplate, BusinessPlanSection, PitchSlide } from './types.js';

export class StartupTemplates {
  static readonly LEAN_CANVAS_TEMPLATE: BusinessTemplate = {
    name: 'Lean Canvas Business Plan',
    type: 'business_plan',
    description: 'One-page business plan focusing on key assumptions and rapid iteration',
    sections: [
      {
        title: 'Problem',
        description: 'Top 3 problems you are solving',
        required: true,
        order: 1,
        template: 'List the most important problems your target customers face. Be specific and focus on pain points that customers are willing to pay to solve.',
      },
      {
        title: 'Customer Segments',
        description: 'Target customer groups',
        required: true,
        order: 2,
        template: 'Define your early adopters and target customer segments. Be as specific as possible about demographics, behaviors, and characteristics.',
      },
      {
        title: 'Unique Value Proposition',
        description: 'Single, clear compelling message',
        required: true,
        order: 3,
        template: 'Explain why you are different and worth buying. Focus on the benefit that makes you different from competitors.',
      },
      {
        title: 'Solution',
        description: 'Top 3 features solving the problems',
        required: true,
        order: 4,
        template: 'Outline the key features of your solution that directly address the problems identified.',
      },
      {
        title: 'Channels',
        description: 'Path to customers',
        required: true,
        order: 5,
        template: 'How will you reach your customers? Include both customer acquisition and distribution channels.',
      },
      {
        title: 'Revenue Streams',
        description: 'How you make money',
        required: true,
        order: 6,
        template: 'Describe your revenue model, pricing strategy, and how customers will pay.',
      },
      {
        title: 'Key Metrics',
        description: 'Key numbers that tell you how your business is doing',
        required: true,
        order: 7,
        template: 'Define the metrics that matter most for measuring progress and success.',
      },
      {
        title: 'Unfair Advantage',
        description: 'Something that cannot be easily copied',
        required: false,
        order: 8,
        template: 'What makes your solution defensible? Network effects, proprietary technology, brand, etc.',
      },
      {
        title: 'Cost Structure',
        description: 'Customer acquisition costs, distribution costs, hosting, people, etc.',
        required: true,
        order: 9,
        template: 'List your main cost drivers and how they scale with your business.',
      },
    ],
    variables: [
      {
        name: 'businessIdea',
        type: 'string',
        description: 'Core business idea or concept',
        required: true,
      },
      {
        name: 'targetMarket',
        type: 'string',
        description: 'Primary target market',
        required: true,
      },
      {
        name: 'businessModel',
        type: 'string',
        description: 'Revenue generation model',
        required: true,
      },
    ],
    examples: [
      'Airbnb Lean Canvas',
      'Uber Lean Canvas',
      'Slack Lean Canvas',
    ],
  };

  static readonly TRADITIONAL_BUSINESS_PLAN: BusinessTemplate = {
    name: 'Traditional Business Plan',
    type: 'business_plan',
    description: 'Comprehensive business plan for formal presentations and funding',
    sections: [
      {
        title: 'Executive Summary',
        description: 'Overview of the entire business plan',
        required: true,
        order: 1,
        template: 'Provide a compelling overview of your business, including mission, vision, key success factors, and financial summary.',
      },
      {
        title: 'Company Description',
        description: 'Detailed company overview',
        required: true,
        order: 2,
        template: 'Describe your company history, ownership, legal structure, location, and facilities.',
      },
      {
        title: 'Market Analysis',
        description: 'Industry and market research',
        required: true,
        order: 3,
        template: 'Analyze industry trends, market size, growth projections, and target market characteristics.',
      },
      {
        title: 'Organization & Management',
        description: 'Organizational structure and management team',
        required: true,
        order: 4,
        template: 'Detail your organizational structure, management team, board of directors, and personnel plan.',
      },
      {
        title: 'Service or Product Line',
        description: 'Products or services offered',
        required: true,
        order: 5,
        template: 'Describe your products or services, including lifecycle, intellectual property, and R&D activities.',
      },
      {
        title: 'Marketing & Sales',
        description: 'Marketing and sales strategy',
        required: true,
        order: 6,
        template: 'Outline your marketing strategy, sales strategy, pricing, and promotional plans.',
      },
      {
        title: 'Funding Request',
        description: 'Funding requirements and usage',
        required: false,
        order: 7,
        template: 'Specify funding requirements, future funding requirements, how funds will be used, and strategic financial plans.',
      },
      {
        title: 'Financial Projections',
        description: 'Financial forecasts and analysis',
        required: true,
        order: 8,
        template: 'Provide historical financial data, prospective financial data, and break-even analysis.',
      },
      {
        title: 'Appendix',
        description: 'Supporting documents',
        required: false,
        order: 9,
        template: 'Include resumes, permits, lease agreements, legal documents, and other relevant paperwork.',
      },
    ],
    variables: [
      {
        name: 'companyName',
        type: 'string',
        description: 'Legal company name',
        required: true,
      },
      {
        name: 'founders',
        type: 'array',
        description: 'Founding team members',
        required: true,
      },
      {
        name: 'fundingAmount',
        type: 'number',
        description: 'Amount of funding requested',
        required: false,
      },
    ],
    examples: [
      'Restaurant Business Plan',
      'Tech Startup Business Plan',
      'Manufacturing Business Plan',
    ],
  };

  static readonly INVESTOR_PITCH_DECK: BusinessTemplate = {
    name: 'Investor Pitch Deck',
    type: 'pitch_deck',
    description: 'Standard investor presentation format',
    sections: [
      {
        title: 'Problem',
        description: 'The pain point you are solving',
        required: true,
        order: 1,
        template: 'Clearly articulate the problem that your target customers face. Make it relatable and urgent.',
      },
      {
        title: 'Solution',
        description: 'Your solution to the problem',
        required: true,
        order: 2,
        template: 'Present your solution and how it uniquely addresses the problem. Include product demo if possible.',
      },
      {
        title: 'Market Size',
        description: 'Total Addressable Market (TAM)',
        required: true,
        order: 3,
        template: 'Show the size of the market opportunity using TAM, SAM, and SOM framework.',
      },
      {
        title: 'Product',
        description: 'Product demonstration',
        required: true,
        order: 4,
        template: 'Demonstrate your product in action. Show key features and user experience.',
      },
      {
        title: 'Traction',
        description: 'Proof of market validation',
        required: true,
        order: 5,
        template: 'Show evidence of traction: users, revenue, partnerships, team growth, etc.',
      },
      {
        title: 'Business Model',
        description: 'How you make money',
        required: true,
        order: 6,
        template: 'Explain your revenue model, pricing strategy, and unit economics.',
      },
      {
        title: 'Competition',
        description: 'Competitive landscape',
        required: true,
        order: 7,
        template: 'Acknowledge competition and show your competitive advantages.',
      },
      {
        title: 'Team',
        description: 'The people behind the company',
        required: true,
        order: 8,
        template: 'Highlight relevant experience and expertise of key team members.',
      },
      {
        title: 'Financial Projections',
        description: 'Revenue and growth projections',
        required: true,
        order: 9,
        template: 'Show 3-5 year financial projections with key assumptions.',
      },
      {
        title: 'Funding Ask',
        description: 'Investment request and use of funds',
        required: true,
        order: 10,
        template: 'Clearly state how much you are raising and how funds will be used.',
      },
    ],
    variables: [
      {
        name: 'companyName',
        type: 'string',
        description: 'Company name',
        required: true,
      },
      {
        name: 'fundingAsk',
        type: 'string',
        description: 'Amount of funding requested',
        required: true,
      },
      {
        name: 'useOfFunds',
        type: 'array',
        description: 'How funds will be used',
        required: true,
      },
    ],
    examples: [
      'Airbnb Series A Pitch',
      'Buffer Seed Pitch',
      'Mixpanel Series A Pitch',
    ],
  };

  static readonly DEMO_DAY_PITCH: BusinessTemplate = {
    name: 'Demo Day Pitch',
    type: 'pitch_deck',
    description: 'Short format pitch for demo days and competitions',
    sections: [
      {
        title: 'Hook',
        description: 'Attention-grabbing opening',
        required: true,
        order: 1,
        template: 'Start with a compelling hook - surprising statistic, bold statement, or relatable story.',
      },
      {
        title: 'Problem',
        description: 'The problem you solve',
        required: true,
        order: 2,
        template: 'Quickly establish the problem and why it matters.',
      },
      {
        title: 'Solution',
        description: 'Your solution',
        required: true,
        order: 3,
        template: 'Present your solution concisely with a brief demo.',
      },
      {
        title: 'Market',
        description: 'Market opportunity',
        required: true,
        order: 4,
        template: 'Show the market size and opportunity in one compelling slide.',
      },
      {
        title: 'Traction',
        description: 'Proof points',
        required: true,
        order: 5,
        template: 'Highlight your best traction metrics and achievements.',
      },
      {
        title: 'Ask',
        description: 'What you need',
        required: true,
        order: 6,
        template: 'Clear call to action - funding, partnerships, customers, etc.',
      },
    ],
    variables: [
      {
        name: 'hookStatement',
        type: 'string',
        description: 'Opening hook statement',
        required: true,
      },
      {
        name: 'demoTime',
        type: 'number',
        description: 'Demo duration in seconds',
        required: true,
        defaultValue: 30,
      },
    ],
    examples: [
      'Y Combinator Demo Day Pitch',
      'TechCrunch Disrupt Pitch',
      'Startup Weekend Pitch',
    ],
  };

  static readonly FINANCIAL_MODEL_TEMPLATE: BusinessTemplate = {
    name: 'SaaS Financial Model',
    type: 'financial_model',
    description: 'Financial model template for SaaS businesses',
    sections: [
      {
        title: 'Revenue Model',
        description: 'Subscription and revenue assumptions',
        required: true,
        order: 1,
        template: 'Define subscription tiers, pricing, and revenue recognition.',
      },
      {
        title: 'Customer Acquisition',
        description: 'CAC and growth assumptions',
        required: true,
        order: 2,
        template: 'Model customer acquisition costs and growth rates.',
      },
      {
        title: 'Unit Economics',
        description: 'LTV, CAC, and payback period',
        required: true,
        order: 3,
        template: 'Calculate customer lifetime value and acquisition payback.',
      },
      {
        title: 'Operating Expenses',
        description: 'Operational cost structure',
        required: true,
        order: 4,
        template: 'Model personnel, infrastructure, and operational costs.',
      },
      {
        title: 'Cash Flow',
        description: 'Cash flow projections',
        required: true,
        order: 5,
        template: 'Project monthly cash flow and funding requirements.',
      },
    ],
    variables: [
      {
        name: 'pricingTiers',
        type: 'array',
        description: 'Subscription pricing tiers',
        required: true,
      },
      {
        name: 'churnRate',
        type: 'number',
        description: 'Monthly churn rate percentage',
        required: true,
        defaultValue: 5,
      },
    ],
    examples: [
      'Slack Financial Model',
      'Zoom Financial Model',
      'Dropbox Financial Model',
    ],
  };

  static getBusinessPlanTemplate(templateType: string): BusinessTemplate {
    switch (templateType) {
      case 'lean_canvas':
        return this.LEAN_CANVAS_TEMPLATE;
      case 'traditional':
        return this.TRADITIONAL_BUSINESS_PLAN;
      case 'one_page':
        return this.LEAN_CANVAS_TEMPLATE; // Use lean canvas for one-page
      case 'investor':
        return this.TRADITIONAL_BUSINESS_PLAN;
      default:
        return this.LEAN_CANVAS_TEMPLATE;
    }
  }

  static getPitchDeckTemplate(templateType: string): BusinessTemplate {
    switch (templateType) {
      case 'investor':
        return this.INVESTOR_PITCH_DECK;
      case 'demo_day':
        return this.DEMO_DAY_PITCH;
      case 'standard':
        return this.INVESTOR_PITCH_DECK;
      case 'one_slide':
        return this.DEMO_DAY_PITCH;
      default:
        return this.INVESTOR_PITCH_DECK;
    }
  }

  static getFinancialModelTemplate(businessModel: string): BusinessTemplate {
    // For now, return SaaS model for all types
    // Could expand to include e-commerce, marketplace, etc.
    return this.FINANCIAL_MODEL_TEMPLATE;
  }

  static getAllTemplates(): BusinessTemplate[] {
    return [
      this.LEAN_CANVAS_TEMPLATE,
      this.TRADITIONAL_BUSINESS_PLAN,
      this.INVESTOR_PITCH_DECK,
      this.DEMO_DAY_PITCH,
      this.FINANCIAL_MODEL_TEMPLATE,
    ];
  }

  static generateBusinessPlanContent(template: BusinessTemplate, variables: Record<string, any>): string {
    let content = `# ${variables.businessIdea || 'Business Plan'}\n\n`;
    content += `**Template**: ${template.name}\n`;
    content += `**Generated**: ${new Date().toLocaleDateString()}\n\n`;

    template.sections.forEach(section => {
      content += `## ${section.title}\n\n`;
      content += `${section.template}\n\n`;
      
      // Add variable substitution if relevant
      if (section.title === 'Problem' && variables.problemStatement) {
        content += `**Current Problem**: ${variables.problemStatement}\n\n`;
      } else if (section.title === 'Solution' && variables.solution) {
        content += `**Proposed Solution**: ${variables.solution}\n\n`;
      } else if (section.title === 'Customer Segments' && variables.targetMarket) {
        content += `**Target Market**: ${variables.targetMarket}\n\n`;
      }

      content += '---\n\n';
    });

    return content;
  }

  static generatePitchDeckContent(template: BusinessTemplate, variables: Record<string, any>): string {
    let content = `# ${variables.businessIdea || 'Pitch Deck'}\n\n`;
    content += `**Template**: ${template.name}\n`;
    content += `**Presentation Date**: ${new Date().toLocaleDateString()}\n\n`;

    template.sections.forEach((section, index) => {
      content += `## Slide ${index + 1}: ${section.title}\n\n`;
      content += `${section.template}\n\n`;
      
      // Add specific content based on section
      switch (section.title) {
        case 'Problem':
          if (variables.problemStatement) {
            content += `**The Problem**: ${variables.problemStatement}\n\n`;
          }
          break;
        case 'Solution':
          if (variables.solution) {
            content += `**Our Solution**: ${variables.solution}\n\n`;
          }
          break;
        case 'Funding Ask':
          if (variables.fundingAsk) {
            content += `**Seeking**: ${variables.fundingAsk}\n\n`;
          }
          break;
      }

      content += '---\n\n';
    });

    // Add presentation notes
    content += '## Presentation Notes\n\n';
    content += '- Keep each slide to 2-3 minutes\n';
    content += '- Practice transitions between slides\n';
    content += '- Prepare for Q&A after presentation\n';
    content += '- Have backup slides ready\n\n';

    return content;
  }

  static getTemplateByName(name: string): BusinessTemplate | undefined {
    return this.getAllTemplates().find(template => 
      template.name.toLowerCase().includes(name.toLowerCase())
    );
  }

  static getTemplatesByType(type: string): BusinessTemplate[] {
    return this.getAllTemplates().filter(template => template.type === type);
  }

  static validateTemplateVariables(template: BusinessTemplate, variables: Record<string, any>): {
    isValid: boolean;
    missingRequired: string[];
    warnings: string[];
  } {
    const missingRequired: string[] = [];
    const warnings: string[] = [];

    template.variables.forEach(variable => {
      if (variable.required && !variables[variable.name]) {
        missingRequired.push(variable.name);
      }
      
      if (variables[variable.name] && variable.type === 'number' && isNaN(Number(variables[variable.name]))) {
        warnings.push(`${variable.name} should be a number`);
      }
    });

    return {
      isValid: missingRequired.length === 0,
      missingRequired,
      warnings,
    };
  }
}