/**
 * Tech Stack Mapper Service
 * Maps feature combinations and permutations to technology recommendations
 * Provides intelligent tech stack suggestions based on feature analysis
 */
class TechStackMapper {
  constructor() {
    this.technologyDatabase = this.initializeTechnologyDatabase();
    this.featureTechMappings = this.initializeFeatureTechMappings();
    this.compatibilityMatrix = this.initializeCompatibilityMatrix();
  }

  /**
   * Initialize technology database with categories and properties
   */
  initializeTechnologyDatabase() {
    return {
      frontend: {
        'React': { 
          category: 'framework', 
          complexity: 'medium', 
          popularity: 0.9, 
          version: '18.x',
          description: 'A JavaScript library for building user interfaces',
          website: 'https://reactjs.org',
          documentation: 'https://reactjs.org/docs'
        },
        'Next.js': { 
          category: 'framework', 
          complexity: 'medium', 
          popularity: 0.8, 
          version: '13.x',
          description: 'The React Framework for Production',
          website: 'https://nextjs.org',
          documentation: 'https://nextjs.org/docs'
        },
        'Vue.js': { 
          category: 'framework', 
          complexity: 'low', 
          popularity: 0.7, 
          version: '3.x',
          description: 'The Progressive JavaScript Framework',
          website: 'https://vuejs.org',
          documentation: 'https://vuejs.org/guide'
        },
        'Angular': { 
          category: 'framework', 
          complexity: 'high', 
          popularity: 0.6, 
          version: '15.x',
          description: 'A platform for building mobile and desktop web applications',
          website: 'https://angular.io',
          documentation: 'https://angular.io/docs'
        },
        'Tailwind CSS': { 
          category: 'styling', 
          complexity: 'low', 
          popularity: 0.8, 
          version: '3.x',
          description: 'A utility-first CSS framework',
          website: 'https://tailwindcss.com',
          documentation: 'https://tailwindcss.com/docs'
        }
      },
      backend: {
        'Node.js': { 
          category: 'runtime', 
          complexity: 'medium', 
          popularity: 0.9, 
          version: '18.x',
          description: 'JavaScript runtime built on Chrome V8 engine',
          website: 'https://nodejs.org',
          documentation: 'https://nodejs.org/docs'
        },
        'Express': { 
          category: 'framework', 
          complexity: 'low', 
          popularity: 0.9, 
          version: '4.x',
          description: 'Fast, unopinionated, minimalist web framework for Node.js',
          website: 'https://expressjs.com',
          documentation: 'https://expressjs.com/en/guide'
        },
        'Python': { 
          category: 'language', 
          complexity: 'low', 
          popularity: 0.8, 
          version: '3.11',
          description: 'A high-level programming language',
          website: 'https://python.org',
          documentation: 'https://docs.python.org'
        },
        'Django': { 
          category: 'framework', 
          complexity: 'medium', 
          popularity: 0.7, 
          version: '4.x',
          description: 'A high-level Python web framework',
          website: 'https://djangoproject.com',
          documentation: 'https://docs.djangoproject.com'
        },
        'FastAPI': { 
          category: 'framework', 
          complexity: 'medium', 
          popularity: 0.8, 
          version: '0.95.x',
          description: 'Modern, fast web framework for building APIs with Python',
          website: 'https://fastapi.tiangolo.com',
          documentation: 'https://fastapi.tiangolo.com/docs'
        }
      },
      database: {
        'PostgreSQL': { 
          category: 'relational', 
          complexity: 'medium', 
          popularity: 0.8, 
          version: '15.x',
          description: 'A powerful, open source object-relational database system',
          website: 'https://postgresql.org',
          documentation: 'https://postgresql.org/docs'
        },
        'MongoDB': { 
          category: 'document', 
          complexity: 'low', 
          popularity: 0.7, 
          version: '6.x',
          description: 'A document-oriented NoSQL database',
          website: 'https://mongodb.com',
          documentation: 'https://docs.mongodb.com'
        },
        'Redis': { 
          category: 'cache', 
          complexity: 'low', 
          popularity: 0.8, 
          version: '7.x',
          description: 'An in-memory data structure store',
          website: 'https://redis.io',
          documentation: 'https://redis.io/docs'
        },
        'MySQL': { 
          category: 'relational', 
          complexity: 'low', 
          popularity: 0.9, 
          version: '8.x',
          description: 'The world\'s most popular open source database',
          website: 'https://mysql.com',
          documentation: 'https://dev.mysql.com/doc'
        }
      },
      devops: {
        'Docker': { 
          category: 'containerization', 
          complexity: 'medium', 
          popularity: 0.9, 
          version: '20.x',
          description: 'A platform for developing, shipping, and running applications',
          website: 'https://docker.com',
          documentation: 'https://docs.docker.com'
        },
        'Kubernetes': { 
          category: 'orchestration', 
          complexity: 'high', 
          popularity: 0.8, 
          version: '1.27',
          description: 'An open-source container orchestration system',
          website: 'https://kubernetes.io',
          documentation: 'https://kubernetes.io/docs'
        },
        'AWS': { 
          category: 'cloud', 
          complexity: 'high', 
          popularity: 0.9, 
          version: 'latest',
          description: 'Amazon Web Services cloud platform',
          website: 'https://aws.amazon.com',
          documentation: 'https://docs.aws.amazon.com'
        },
        'GitHub Actions': { 
          category: 'ci_cd', 
          complexity: 'medium', 
          popularity: 0.8, 
          version: 'latest',
          description: 'Automate, customize, and execute your software development workflows',
          website: 'https://github.com/features/actions',
          documentation: 'https://docs.github.com/actions'
        }
      }
    };
  }

  /**
   * Initialize feature-to-technology mappings
   */
  initializeFeatureTechMappings() {
    return {
      'auth': {
        frontend: ['React', 'Next.js'],
        backend: ['Node.js', 'Express', 'Passport.js'],
        database: ['PostgreSQL', 'Redis'],
        devops: ['Docker', 'AWS']
      },
      'payment': {
        frontend: ['React', 'Stripe.js'],
        backend: ['Node.js', 'Express', 'Stripe API'],
        database: ['PostgreSQL', 'Redis'],
        devops: ['Docker', 'AWS']
      },
      'dashboard': {
        frontend: ['React', 'Chart.js', 'D3.js'],
        backend: ['Node.js', 'Express'],
        database: ['PostgreSQL', 'Redis'],
        devops: ['Docker', 'AWS']
      },
      'api': {
        frontend: ['React', 'Axios'],
        backend: ['Node.js', 'Express', 'Swagger'],
        database: ['PostgreSQL'],
        devops: ['Docker', 'AWS']
      },
      'notification': {
        frontend: ['React', 'Socket.io'],
        backend: ['Node.js', 'Express', 'Socket.io'],
        database: ['PostgreSQL', 'Redis'],
        devops: ['Docker', 'AWS']
      },
      'file_upload': {
        frontend: ['React', 'Dropzone'],
        backend: ['Node.js', 'Express', 'Multer'],
        database: ['PostgreSQL'],
        devops: ['Docker', 'AWS S3']
      },
      'search': {
        frontend: ['React', 'Algolia'],
        backend: ['Node.js', 'Express', 'Elasticsearch'],
        database: ['PostgreSQL', 'Elasticsearch'],
        devops: ['Docker', 'AWS']
      },
      'analytics': {
        frontend: ['React', 'Chart.js', 'D3.js'],
        backend: ['Node.js', 'Express', 'Python'],
        database: ['PostgreSQL', 'MongoDB'],
        devops: ['Docker', 'AWS']
      }
    };
  }

  /**
   * Initialize technology compatibility matrix
   */
  initializeCompatibilityMatrix() {
    return {
      'React': ['Next.js', 'Tailwind CSS', 'Axios', 'Socket.io'],
      'Next.js': ['React', 'Tailwind CSS', 'Axios'],
      'Node.js': ['Express', 'MongoDB', 'PostgreSQL', 'Redis'],
      'Express': ['Node.js', 'MongoDB', 'PostgreSQL', 'Redis'],
      'PostgreSQL': ['Node.js', 'Express', 'Python', 'Django'],
      'MongoDB': ['Node.js', 'Express', 'Python', 'Django'],
      'Docker': ['Kubernetes', 'AWS', 'GitHub Actions'],
      'AWS': ['Docker', 'Kubernetes', 'GitHub Actions']
    };
  }

  /**
   * Map features to tech stack recommendations
   */
  mapFeaturesToTechStack(features, combinationType = 'combination') {
    if (!features || features.length === 0) {
      return this.getDefaultTechStack();
    }

    const techStack = {
      frontend: [],
      backend: [],
      database: [],
      devops: [],
      confidence_score: 0,
      complexity_level: 'low',
      estimated_effort: '1-2 weeks',
      reasoning: []
    };

    // Analyze each feature and map to technologies
    for (const feature of features) {
      const featureTech = this.getFeatureTechnologies(feature);
      this.mergeTechnologies(techStack, featureTech);
    }

    // Apply combination-specific logic
    if (combinationType === 'permutation') {
      this.applyPermutationLogic(techStack, features);
    } else {
      this.applyCombinationLogic(techStack, features);
    }

    // Calculate confidence and complexity
    techStack.confidence_score = this.calculateConfidenceScore(techStack, features);
    techStack.complexity_level = this.calculateComplexityLevel(techStack, features);
    techStack.estimated_effort = this.calculateEstimatedEffort(techStack, features);

    // Remove duplicates and sort by popularity
    techStack.frontend = this.deduplicateAndSort(techStack.frontend, 'frontend');
    techStack.backend = this.deduplicateAndSort(techStack.backend, 'backend');
    techStack.database = this.deduplicateAndSort(techStack.database, 'database');
    techStack.devops = this.deduplicateAndSort(techStack.devops, 'devops');

    return techStack;
  }

  /**
   * Get technologies for a specific feature
   */
  getFeatureTechnologies(feature) {
    const featureName = feature.name.toLowerCase();
    const featureType = feature.feature_type;
    const complexity = feature.complexity;

    // Direct mapping based on feature name
    for (const [pattern, techs] of Object.entries(this.featureTechMappings)) {
      if (featureName.includes(pattern)) {
        return techs;
      }
    }

    // Fallback based on feature type and complexity
    return this.getFallbackTechnologies(featureType, complexity);
  }

  /**
   * Get fallback technologies based on feature type and complexity
   */
  getFallbackTechnologies(featureType, complexity) {
    const baseTechs = {
      frontend: ['React', 'Tailwind CSS'],
      backend: ['Node.js', 'Express'],
      database: ['PostgreSQL'],
      devops: ['Docker']
    };

    if (complexity === 'high') {
      baseTechs.frontend.push('Next.js', 'Chart.js');
      baseTechs.backend.push('Python', 'FastAPI');
      baseTechs.database.push('Redis', 'MongoDB');
      baseTechs.devops.push('Kubernetes', 'AWS');
    } else if (complexity === 'medium') {
      baseTechs.frontend.push('Next.js');
      baseTechs.backend.push('Python');
      baseTechs.database.push('Redis');
      baseTechs.devops.push('AWS');
    }

    return baseTechs;
  }

  /**
   * Merge technologies from different features
   */
  mergeTechnologies(techStack, featureTech) {
    for (const [category, technologies] of Object.entries(featureTech)) {
      if (!techStack[category]) {
        techStack[category] = [];
      }
      techStack[category].push(...technologies);
    }
  }

  /**
   * Apply permutation-specific logic
   */
  applyPermutationLogic(techStack, features) {
    // For permutations, order matters - earlier features may influence later ones
    const firstFeature = features[0];
    const lastFeature = features[features.length - 1];

    // If first feature is auth, ensure security technologies
    if (firstFeature.name.toLowerCase().includes('auth')) {
      techStack.backend.push('Passport.js', 'JWT');
      techStack.database.push('Redis');
    }

    // If last feature is analytics, ensure data processing technologies
    if (lastFeature.name.toLowerCase().includes('analytics')) {
      techStack.backend.push('Python', 'Pandas');
      techStack.database.push('MongoDB');
    }
  }

  /**
   * Apply combination-specific logic
   */
  applyCombinationLogic(techStack, features) {
    // For combinations, focus on compatibility and synergy
    const hasAuth = features.some(f => f.name.toLowerCase().includes('auth'));
    const hasPayment = features.some(f => f.name.toLowerCase().includes('payment'));
    const hasDashboard = features.some(f => f.name.toLowerCase().includes('dashboard'));

    // If both auth and payment, ensure secure payment processing
    if (hasAuth && hasPayment) {
      techStack.backend.push('Stripe API', 'JWT');
      techStack.database.push('Redis');
    }

    // If dashboard and analytics, ensure data visualization
    if (hasDashboard && features.some(f => f.name.toLowerCase().includes('analytics'))) {
      techStack.frontend.push('Chart.js', 'D3.js');
      techStack.backend.push('Python', 'Pandas');
    }
  }

  /**
   * Calculate confidence score for tech stack
   */
  calculateConfidenceScore(techStack, features) {
    let confidence = 0.5; // Base confidence

    // Increase confidence based on feature coverage
    const totalCategories = 4; // frontend, backend, database, devops
    const coveredCategories = Object.values(techStack).filter(category => 
      Array.isArray(category) && category.length > 0
    ).length;
    
    confidence += (coveredCategories / totalCategories) * 0.3;

    // Increase confidence based on technology popularity
    const allTechs = [
      ...techStack.frontend,
      ...techStack.backend,
      ...techStack.database,
      ...techStack.devops
    ];

    const avgPopularity = allTechs.reduce((sum, tech) => {
      const techData = this.getTechnologyData(tech);
      return sum + (techData?.popularity || 0.5);
    }, 0) / allTechs.length;

    confidence += avgPopularity * 0.2;

    return Math.min(confidence, 1.0);
  }

  /**
   * Calculate complexity level
   */
  calculateComplexityLevel(techStack, features) {
    const featureComplexity = features.reduce((sum, feature) => {
      const complexityMap = { low: 1, medium: 2, high: 3 };
      return sum + (complexityMap[feature.complexity] || 2);
    }, 0) / features.length;

    const techComplexity = this.calculateTechComplexity(techStack);
    
    const totalComplexity = (featureComplexity + techComplexity) / 2;

    if (totalComplexity <= 1.5) return 'low';
    if (totalComplexity <= 2.5) return 'medium';
    return 'high';
  }

  /**
   * Calculate technology complexity
   */
  calculateTechComplexity(techStack) {
    const allTechs = [
      ...techStack.frontend,
      ...techStack.backend,
      ...techStack.database,
      ...techStack.devops
    ];

    const avgComplexity = allTechs.reduce((sum, tech) => {
      const techData = this.getTechnologyData(tech);
      const complexityMap = { low: 1, medium: 2, high: 3 };
      return sum + (complexityMap[techData?.complexity] || 2);
    }, 0) / allTechs.length;

    return avgComplexity;
  }

  /**
   * Calculate estimated effort
   */
  calculateEstimatedEffort(techStack, features) {
    const featureEffort = features.reduce((sum, feature) => {
      const complexityMap = { low: 1, medium: 2, high: 3 };
      return sum + (complexityMap[feature.complexity] || 2);
    }, 0);

    const techEffort = this.calculateTechComplexity(techStack);
    const totalEffort = featureEffort + techEffort;

    if (totalEffort <= 3) return '1-2 weeks';
    if (totalEffort <= 6) return '2-4 weeks';
    if (totalEffort <= 9) return '1-2 months';
    return '2+ months';
  }

  /**
   * Get technology data
   */
  getTechnologyData(techName) {
    for (const [category, techs] of Object.entries(this.technologyDatabase)) {
      if (techs[techName]) {
        return techs[techName];
      }
    }
    return null;
  }

  /**
   * Remove duplicates and sort by popularity
   */
  deduplicateAndSort(technologies, category) {
    const unique = [...new Set(technologies)];
    return unique.sort((a, b) => {
      const aData = this.getTechnologyData(a);
      const bData = this.getTechnologyData(b);
      return (bData?.popularity || 0) - (aData?.popularity || 0);
    });
  }

  /**
   * Get default tech stack
   */
  getDefaultTechStack() {
    return {
      frontend: ['React', 'Tailwind CSS'],
      backend: ['Node.js', 'Express'],
      database: ['PostgreSQL'],
      devops: ['Docker'],
      confidence_score: 0.7,
      complexity_level: 'low',
      estimated_effort: '1-2 weeks',
      reasoning: ['Default minimal tech stack']
    };
  }

  /**
   * Get technology recommendations based on existing stack
   */
  getTechnologyRecommendations(existingTechStack, features) {
    const recommendations = [];

    for (const [category, existingTechs] of Object.entries(existingTechStack)) {
      if (!Array.isArray(existingTechs)) continue;

      for (const existingTech of existingTechs) {
        const compatibleTechs = this.compatibilityMatrix[existingTech] || [];
        
        for (const compatibleTech of compatibleTechs) {
          if (!existingTechs.includes(compatibleTech)) {
            recommendations.push({
              technology: compatibleTech,
              category: category,
              reason: `Compatible with ${existingTech}`,
              compatibility_score: 0.8
            });
          }
        }
      }
    }

    return recommendations.sort((a, b) => b.compatibility_score - a.compatibility_score);
  }

  /**
   * Validate tech stack compatibility
   */
  validateTechStackCompatibility(techStack) {
    const issues = [];

    // Check frontend-backend compatibility
    if (techStack.frontend.includes('React') && techStack.backend.includes('Django')) {
      issues.push('React and Django may have integration challenges');
    }

    // Check database compatibility
    if (techStack.database.includes('MongoDB') && techStack.database.includes('PostgreSQL')) {
      issues.push('Using both MongoDB and PostgreSQL may add complexity');
    }

    // Check devops compatibility
    if (techStack.devops.includes('Kubernetes') && !techStack.devops.includes('Docker')) {
      issues.push('Kubernetes typically requires Docker');
    }

    return {
      isCompatible: issues.length === 0,
      issues: issues
    };
  }
}

module.exports = TechStackMapper;
