const axios = require('axios');
const MockTechStackAnalyzer = require('./mock_tech_stack_analyzer');

/**
 * Intelligent Tech Stack Analyzer
 * Uses AI to analyze features and generate comprehensive tech stack recommendations
 */
class IntelligentTechStackAnalyzer {
  constructor() {
    this.claudeApiKey = process.env.CLAUDE_API_KEY;
    this.mockAnalyzer = new MockTechStackAnalyzer();
    this.analysisCache = new Map();
    this.maxCacheSize = 1000;
  }

  /**
   * Analyze template data and generate tech stack recommendations
   * This method is called by auto_tech_stack_analyzer.js
   */
  async analyzeTemplate(templateData) {
    try {
      console.log(`🤖 [IntelligentAnalyzer] Analyzing template: ${templateData.title}`);
      
      // If no Claude API key, use mock analyzer
      if (!this.claudeApiKey) {
        console.log('⚠️ [IntelligentAnalyzer] No Claude API key, using mock analyzer');
        return await this.mockAnalyzer.analyzeTemplate(templateData);
      }
      
      // Extract features for analysis
      const features = templateData.features || [];
      const templateContext = {
        type: templateData.type || 'web application',
        category: templateData.category || 'general',
        complexity: templateData.complexity || 'medium'
      };
      
      // Use existing analyzeFeaturesForTechStack method
      const analysis = await this.analyzeFeaturesForTechStack(features, templateContext);
      
      return {
        ...analysis,
        analysis_context: {
          template_title: templateData.title,
          template_category: templateData.category,
          features_count: features.length,
          business_rules_count: Object.keys(templateData.business_rules || {}).length
        },
        processing_time_ms: 0, // Will be set by caller
        ai_model: 'claude-3-5-sonnet',
        analysis_version: '1.0',
        status: 'completed'
      };
      
    } catch (error) {
      console.error(`❌ [IntelligentAnalyzer] Analysis failed, using mock analyzer:`, error.message);
      return await this.mockAnalyzer.analyzeTemplate(templateData);
    }
  }

  /**
   * Analyze features and generate intelligent tech stack recommendations
   */
  async analyzeFeaturesForTechStack(features, templateContext = {}) {
    try {
      const cacheKey = this.generateCacheKey(features, templateContext);
      if (this.analysisCache.has(cacheKey)) {
        console.log('📋 Using cached analysis for features');
        return this.analysisCache.get(cacheKey);
      }

      console.log(`🤖 Analyzing ${features.length} features for tech stack recommendations`);
      
      const analysis = await this.performClaudeAnalysis(features, templateContext);
      
      // Cache the result
      this.cacheResult(cacheKey, analysis);
      
      return analysis;
    } catch (error) {
      console.error('❌ Failed to analyze features for tech stack:', error.message);
      return this.getFallbackTechStack(features, templateContext);
    }
  }

  /**
   * Perform Claude AI analysis
   */
  async performClaudeAnalysis(features, templateContext) {
    const featuresText = features.map(f => 
      `- ${f.name}: ${f.description} (${f.complexity} complexity, ${f.feature_type} type)`
    ).join('\n');

    const prompt = `Analyze these application features and provide comprehensive tech stack recommendations:

Template Context:
- Type: ${templateContext.type || 'web application'}
- Category: ${templateContext.category || 'general'}
- Complexity: ${templateContext.complexity || 'medium'}

Features to Analyze:
${featuresText}

Provide a detailed tech stack analysis in JSON format:
{
  "frontend_tech": [
    {
      "name": "Technology Name",
      "category": "framework|library|tool",
      "confidence": 0.9,
      "reasoning": "Why this technology is recommended",
      "alternatives": ["Alternative 1", "Alternative 2"],
      "learning_curve": "easy|medium|hard",
      "performance_score": 8.5,
      "community_support": "high|medium|low",
      "cost": "free|freemium|paid",
      "scalability": "low|medium|high",
      "security_score": 8.0
    }
  ],
  "backend_tech": [...],
  "database_tech": [...],
  "devops_tech": [...],
  "mobile_tech": [...],
  "cloud_tech": [...],
  "testing_tech": [...],
  "ai_ml_tech": [...],
  "tools_tech": [...],
  "overall_confidence": 0.85,
  "complexity_assessment": "low|medium|high",
  "estimated_development_time": "2-4 weeks",
  "key_considerations": [
    "Important consideration 1",
    "Important consideration 2"
  ],
  "technology_synergies": [
    {
      "tech1": "React",
      "tech2": "Node.js",
      "synergy_score": 0.9,
      "reasoning": "Both are JavaScript-based, enabling full-stack development"
    }
  ],
  "potential_conflicts": [
    {
      "tech1": "Vue.js",
      "tech2": "Angular",
      "conflict_severity": "high",
      "reasoning": "Both are frontend frameworks, choose one"
    }
  ],
  "scalability_recommendations": [
    "Recommendation for scaling the application"
  ],
  "security_recommendations": [
    "Security best practices for this tech stack"
  ]
}

Guidelines:
1. Consider the template type and category
2. Analyze feature complexity and interactions
3. Recommend technologies that work well together
4. Include confidence scores for each recommendation
5. Identify potential synergies and conflicts
6. Consider scalability, security, and performance
7. Provide reasoning for each recommendation
8. Include alternatives for flexibility

Return ONLY the JSON object, no other text.`;

    try {
      console.log('🔍 Making Claude API request for tech stack analysis...');
      
      const response = await axios.post('https://api.anthropic.com/v1/messages', {
        model: 'claude-3-5-sonnet-20241022',
        max_tokens: 4000,
        temperature: 0.1,
        messages: [
          {
            role: 'user',
            content: prompt
          }
        ]
      }, {
        headers: {
          'x-api-key': this.claudeApiKey,
          'Content-Type': 'application/json',
          'anthropic-version': '2023-06-01'
        },
        timeout: 30000
      });

      console.log('✅ Claude API response received');
      
      const responseText = (response?.data?.content?.[0]?.text || '').trim();
      
      // Extract JSON from response
      const jsonMatch = responseText.match(/\{[\s\S]*\}/);
      if (jsonMatch) {
        const analysis = JSON.parse(jsonMatch[0]);
        console.log('✅ Claude analysis successful');
        return analysis;
      } else {
        console.error('❌ No valid JSON found in Claude response');
        throw new Error('No valid JSON found in Claude response');
      }
    } catch (error) {
      console.error('❌ Claude API error:', error.message);
      // If API fails, use mock analyzer
      console.log('⚠️ [IntelligentAnalyzer] Claude API failed, using mock analyzer');
      return await this.mockAnalyzer.analyzeTemplate({
        title: 'Fallback Analysis',
        category: templateContext.category || 'general',
        features: features,
        business_rules: {}
      });
    }
  }

  /**
   * Generate fallback tech stack when AI analysis fails
   */
  getFallbackTechStack(features, templateContext) {
    console.log('⚠️ Using fallback tech stack analysis');
    
    const frontendTech = this.getFrontendTech(features, templateContext);
    const backendTech = this.getBackendTech(features, templateContext);
    const databaseTech = this.getDatabaseTech(features, templateContext);
    const devopsTech = this.getDevopsTech(features, templateContext);
    
    return {
      frontend_tech: frontendTech,
      backend_tech: backendTech,
      database_tech: databaseTech,
      devops_tech: devopsTech,
      mobile_tech: this.getMobileTech(features, templateContext),
      cloud_tech: this.getCloudTech(features, templateContext),
      testing_tech: this.getTestingTech(features, templateContext),
      ai_ml_tech: this.getAiMlTech(features, templateContext),
      tools_tech: this.getToolsTech(features, templateContext),
      overall_confidence: 0.7,
      complexity_assessment: this.getComplexityAssessment(features),
      estimated_development_time: this.getEstimatedTime(features),
      key_considerations: this.getKeyConsiderations(features),
      technology_synergies: [],
      potential_conflicts: [],
      scalability_recommendations: [],
      security_recommendations: []
    };
  }

  /**
   * Get frontend technologies based on features
   */
  getFrontendTech(features, templateContext) {
    const frontendTech = [];
    
    // Base frontend stack
    frontendTech.push({
      name: 'React',
      category: 'framework',
      confidence: 0.9,
      reasoning: 'Popular, flexible frontend framework',
      alternatives: ['Vue.js', 'Angular'],
      learning_curve: 'medium',
      performance_score: 8.5,
      community_support: 'high',
      cost: 'free',
      scalability: 'high',
      security_score: 8.0
    });

    // Add specific technologies based on features
    for (const feature of features) {
      const featureName = feature.name.toLowerCase();
      
      if (featureName.includes('dashboard') || featureName.includes('analytics')) {
        frontendTech.push({
          name: 'Chart.js',
          category: 'library',
          confidence: 0.8,
          reasoning: 'Excellent for data visualization',
          alternatives: ['D3.js', 'Recharts'],
          learning_curve: 'easy',
          performance_score: 8.0,
          community_support: 'high',
          cost: 'free',
          scalability: 'medium',
          security_score: 8.5
        });
      }
      
      if (featureName.includes('auth') || featureName.includes('login')) {
        frontendTech.push({
          name: 'React Router',
          category: 'library',
          confidence: 0.9,
          reasoning: 'Essential for authentication routing',
          alternatives: ['Next.js Router'],
          learning_curve: 'easy',
          performance_score: 8.5,
          community_support: 'high',
          cost: 'free',
          scalability: 'high',
          security_score: 8.0
        });
      }
    }
    
    return frontendTech;
  }

  /**
   * Get backend technologies based on features
   */
  getBackendTech(features, templateContext) {
    const backendTech = [];
    
    // Base backend stack
    backendTech.push({
      name: 'Node.js',
      category: 'runtime',
      confidence: 0.9,
      reasoning: 'JavaScript runtime for full-stack development',
      alternatives: ['Python', 'Java'],
      learning_curve: 'medium',
      performance_score: 8.0,
      community_support: 'high',
      cost: 'free',
      scalability: 'high',
      security_score: 7.5
    });

    backendTech.push({
      name: 'Express.js',
      category: 'framework',
      confidence: 0.9,
      reasoning: 'Lightweight Node.js web framework',
      alternatives: ['Fastify', 'Koa.js'],
      learning_curve: 'easy',
      performance_score: 8.5,
      community_support: 'high',
      cost: 'free',
      scalability: 'high',
      security_score: 8.0
    });

    // Add specific technologies based on features
    for (const feature of features) {
      const featureName = feature.name.toLowerCase();
      
      if (featureName.includes('api') || featureName.includes('integration')) {
        backendTech.push({
          name: 'Swagger/OpenAPI',
          category: 'tool',
          confidence: 0.8,
          reasoning: 'API documentation and testing',
          alternatives: ['GraphQL'],
          learning_curve: 'medium',
          performance_score: 8.0,
          community_support: 'high',
          cost: 'free',
          scalability: 'high',
          security_score: 8.5
        });
      }
      
      if (featureName.includes('payment') || featureName.includes('billing')) {
        backendTech.push({
          name: 'Stripe API',
          category: 'service',
          confidence: 0.9,
          reasoning: 'Comprehensive payment processing',
          alternatives: ['PayPal API', 'Square API'],
          learning_curve: 'medium',
          performance_score: 9.0,
          community_support: 'high',
          cost: 'paid',
          scalability: 'high',
          security_score: 9.5
        });
      }
    }
    
    return backendTech;
  }

  /**
   * Get database technologies based on features
   */
  getDatabaseTech(features, templateContext) {
    const databaseTech = [];
    
    // Base database stack
    databaseTech.push({
      name: 'PostgreSQL',
      category: 'database',
      confidence: 0.9,
      reasoning: 'Robust relational database',
      alternatives: ['MySQL', 'SQLite'],
      learning_curve: 'medium',
      performance_score: 8.5,
      community_support: 'high',
      cost: 'free',
      scalability: 'high',
      security_score: 9.0
    });

    // Add specific technologies based on features
    for (const feature of features) {
      const featureName = feature.name.toLowerCase();
      
      if (featureName.includes('cache') || featureName.includes('session')) {
        databaseTech.push({
          name: 'Redis',
          category: 'cache',
          confidence: 0.9,
          reasoning: 'High-performance in-memory cache',
          alternatives: ['Memcached'],
          learning_curve: 'easy',
          performance_score: 9.5,
          community_support: 'high',
          cost: 'free',
          scalability: 'high',
          security_score: 8.0
        });
      }
      
      if (featureName.includes('analytics') || featureName.includes('big data')) {
        databaseTech.push({
          name: 'MongoDB',
          category: 'database',
          confidence: 0.8,
          reasoning: 'Document database for flexible data',
          alternatives: ['CouchDB'],
          learning_curve: 'medium',
          performance_score: 8.0,
          community_support: 'high',
          cost: 'freemium',
          scalability: 'high',
          security_score: 7.5
        });
      }
    }
    
    return databaseTech;
  }

  /**
   * Get DevOps technologies based on features
   */
  getDevopsTech(features, templateContext) {
    const devopsTech = [];
    
    // Base DevOps stack
    devopsTech.push({
      name: 'Docker',
      category: 'containerization',
      confidence: 0.9,
      reasoning: 'Containerization for consistent deployments',
      alternatives: ['Podman'],
      learning_curve: 'medium',
      performance_score: 8.5,
      community_support: 'high',
      cost: 'free',
      scalability: 'high',
      security_score: 8.0
    });

    // Add specific technologies based on features
    for (const feature of features) {
      const featureName = feature.name.toLowerCase();
      
      if (featureName.includes('scaling') || featureName.includes('load')) {
        devopsTech.push({
          name: 'Kubernetes',
          category: 'orchestration',
          confidence: 0.8,
          reasoning: 'Container orchestration for scaling',
          alternatives: ['Docker Swarm'],
          learning_curve: 'hard',
          performance_score: 9.0,
          community_support: 'high',
          cost: 'free',
          scalability: 'high',
          security_score: 8.5
        });
      }
    }
    
    return devopsTech;
  }

  /**
   * Get mobile technologies based on features
   */
  getMobileTech(features, templateContext) {
    const mobileTech = [];
    
    // Check if mobile features are present
    const hasMobileFeatures = features.some(f => 
      f.name.toLowerCase().includes('mobile') || 
      f.name.toLowerCase().includes('app')
    );
    
    if (hasMobileFeatures) {
      mobileTech.push({
        name: 'React Native',
        category: 'framework',
        confidence: 0.9,
        reasoning: 'Cross-platform mobile development',
        alternatives: ['Flutter', 'Ionic'],
        learning_curve: 'medium',
        performance_score: 8.0,
        community_support: 'high',
        cost: 'free',
        scalability: 'high',
        security_score: 8.0
      });
    }
    
    return mobileTech;
  }

  /**
   * Get cloud technologies based on features
   */
  getCloudTech(features, templateContext) {
    const cloudTech = [];
    
    // Base cloud stack
    cloudTech.push({
      name: 'AWS',
      category: 'cloud',
      confidence: 0.9,
      reasoning: 'Comprehensive cloud platform',
      alternatives: ['Google Cloud', 'Azure'],
      learning_curve: 'hard',
      performance_score: 9.0,
      community_support: 'high',
      cost: 'paid',
      scalability: 'high',
      security_score: 9.0
    });
    
    return cloudTech;
  }

  /**
   * Get testing technologies based on features
   */
  getTestingTech(features, templateContext) {
    const testingTech = [];
    
    // Base testing stack
    testingTech.push({
      name: 'Jest',
      category: 'framework',
      confidence: 0.9,
      reasoning: 'JavaScript testing framework',
      alternatives: ['Mocha', 'Jasmine'],
      learning_curve: 'easy',
      performance_score: 8.5,
      community_support: 'high',
      cost: 'free',
      scalability: 'high',
      security_score: 8.0
    });
    
    return testingTech;
  }

  /**
   * Get AI/ML technologies based on features
   */
  getAiMlTech(features, templateContext) {
    const aiMlTech = [];
    
    // Check if AI/ML features are present
    const hasAiFeatures = features.some(f => 
      f.name.toLowerCase().includes('ai') || 
      f.name.toLowerCase().includes('ml') ||
      f.name.toLowerCase().includes('machine learning')
    );
    
    if (hasAiFeatures) {
      aiMlTech.push({
        name: 'OpenAI API',
        category: 'service',
        confidence: 0.9,
        reasoning: 'Advanced AI capabilities',
        alternatives: ['Anthropic Claude', 'Google AI'],
        learning_curve: 'medium',
        performance_score: 9.5,
        community_support: 'high',
        cost: 'paid',
        scalability: 'high',
        security_score: 8.5
      });
    }
    
    return aiMlTech;
  }

  /**
   * Get tools technologies based on features
   */
  getToolsTech(features, templateContext) {
    const toolsTech = [];
    
    // Base tools stack
    toolsTech.push({
      name: 'Git',
      category: 'tool',
      confidence: 0.9,
      reasoning: 'Version control system',
      alternatives: ['Mercurial'],
      learning_curve: 'medium',
      performance_score: 9.0,
      community_support: 'high',
      cost: 'free',
      scalability: 'high',
      security_score: 8.5
    });
    
    return toolsTech;
  }

  /**
   * Get complexity assessment based on features
   */
  getComplexityAssessment(features) {
    if (!features || features.length === 0) return 'low';
    
    const complexityScores = features.map(f => {
      const complexityMap = { low: 1, medium: 2, high: 3 };
      return complexityMap[f.complexity] || 2;
    });
    
    const avgComplexity = complexityScores.reduce((sum, score) => sum + score, 0) / complexityScores.length;
    
    if (avgComplexity <= 1.5) return 'low';
    if (avgComplexity <= 2.5) return 'medium';
    return 'high';
  }

  /**
   * Get estimated development time based on features
   */
  getEstimatedTime(features) {
    if (!features || features.length === 0) return '1-2 weeks';
    
    const totalComplexity = features.reduce((sum, feature) => {
      const complexityMap = { low: 1, medium: 2, high: 3 };
      return sum + (complexityMap[feature.complexity] || 2);
    }, 0);
    
    if (totalComplexity <= 3) return '1-2 weeks';
    if (totalComplexity <= 6) return '2-4 weeks';
    if (totalComplexity <= 9) return '1-2 months';
    return '2+ months';
  }

  /**
   * Get key considerations based on features
   */
  getKeyConsiderations(features) {
    const considerations = [];
    
    const hasAuth = features.some(f => f.name.toLowerCase().includes('auth'));
    const hasPayment = features.some(f => f.name.toLowerCase().includes('payment'));
    const hasApi = features.some(f => f.name.toLowerCase().includes('api'));
    
    if (hasAuth) {
      considerations.push('Implement secure authentication and authorization');
    }
    
    if (hasPayment) {
      considerations.push('Ensure PCI compliance for payment processing');
    }
    
    if (hasApi) {
      considerations.push('Design RESTful API with proper documentation');
    }
    
    return considerations;
  }

  /**
   * Generate cache key for features and context
   */
  generateCacheKey(features, templateContext) {
    const featureIds = features.map(f => f.id).sort().join('_');
    const contextKey = `${templateContext.type || 'default'}_${templateContext.category || 'general'}`;
    return `analysis_${featureIds}_${contextKey}`;
  }

  /**
   * Cache analysis result
   */
  cacheResult(key, result) {
    if (this.analysisCache.size >= this.maxCacheSize) {
      // Remove oldest entry
      const firstKey = this.analysisCache.keys().next().value;
      this.analysisCache.delete(firstKey);
    }
    
    this.analysisCache.set(key, result);
  }

  /**
   * Clear analysis cache
   */
  clearCache() {
    this.analysisCache.clear();
  }

  /**
   * Get cache statistics
   */
  getCacheStats() {
    return {
      size: this.analysisCache.size,
      maxSize: this.maxCacheSize,
      keys: Array.from(this.analysisCache.keys())
    };
  }
}

module.exports = IntelligentTechStackAnalyzer;
