const express = require('express');
const router = express.Router();
const EnhancedCKGService = require('../services/enhanced-ckg-service');
const IntelligentTechStackAnalyzer = require('../services/intelligent-tech-stack-analyzer');
const Template = require('../models/template');
const CustomTemplate = require('../models/custom_template');
const Feature = require('../models/feature');
const CustomFeature = require('../models/custom_feature');

// Initialize enhanced services
const ckgService = new EnhancedCKGService();
const techStackAnalyzer = new IntelligentTechStackAnalyzer();

/**
 * GET /api/enhanced-ckg-tech-stack/template/:templateId
 * Get intelligent tech stack recommendations based on template
 */
router.get('/template/:templateId', async (req, res) => {
  try {
    const { templateId } = req.params;
    const includeFeatures = req.query.include_features === 'true';
    const limit = parseInt(req.query.limit) || 10;
    const minConfidence = parseFloat(req.query.min_confidence) || 0.7;
    
    console.log(`🔍 [Enhanced CKG] Fetching intelligent template-based recommendations for: ${templateId}`);
    
    // Get template details
    const template = await Template.getByIdWithFeatures(templateId) || await CustomTemplate.getByIdWithFeatures(templateId);
    if (!template) {
      return res.status(404).json({
        success: false,
        error: 'Template not found',
        message: `Template with ID ${templateId} does not exist`
      });
    }
    
    // Get template features if requested
    let features = [];
    if (includeFeatures) {
      features = await Feature.getByTemplateId(templateId) || await CustomFeature.getByTemplateId(templateId);
    }
    
    // Use intelligent analyzer to get tech stack recommendations
    const templateContext = {
      type: template.type,
      category: template.category,
      complexity: template.complexity
    };
    
    const analysis = await techStackAnalyzer.analyzeFeaturesForTechStack(template.features || [], templateContext);
    
    res.json({
      success: true,
      data: {
        template: {
          id: template.id,
          title: template.title,
          description: template.description,
          category: template.category,
          type: template.type || 'default',
          complexity: template.complexity
        },
        features: includeFeatures ? features : undefined,
        tech_stack_analysis: analysis,
        recommendation_type: 'intelligent-template-based',
        total_recommendations: Object.keys(analysis).length
      },
      message: `Found intelligent tech stack analysis for ${template.title}`
    });
    
  } catch (error) {
    console.error('❌ Error fetching intelligent template-based tech stack:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to fetch intelligent template-based recommendations',
      message: error.message
    });
  }
});

/**
 * GET /api/enhanced-ckg-tech-stack/permutations/:templateId
 * Get intelligent tech stack recommendations based on feature permutations
 */
router.get('/permutations/:templateId', async (req, res) => {
  try {
    const { templateId } = req.params;
    const includeFeatures = req.query.include_features === 'true';
    const limit = parseInt(req.query.limit) || 10;
    const minSequenceLength = parseInt(req.query.min_sequence) || 1;
    const maxSequenceLength = parseInt(req.query.max_sequence) || 10;
    const minConfidence = parseFloat(req.query.min_confidence) || 0.7;
    
    console.log(`🔍 [Enhanced CKG] Fetching intelligent permutation-based recommendations for: ${templateId}`);
    
    // Get template details
    const template = await Template.getByIdWithFeatures(templateId) || await CustomTemplate.getByIdWithFeatures(templateId);
    if (!template) {
      return res.status(404).json({
        success: false,
        error: 'Template not found',
        message: `Template with ID ${templateId} does not exist`
      });
    }
    
    // Get template features if requested
    let features = [];
    if (includeFeatures) {
      features = await Feature.getByTemplateId(templateId) || await CustomFeature.getByTemplateId(templateId);
    }
    
    // Get intelligent permutation recommendations from Neo4j
    const permutationRecommendations = await ckgService.getIntelligentPermutationRecommendations(templateId, {
      limit,
      minConfidence
    });
    
    // Filter by sequence length
    const filteredRecommendations = permutationRecommendations.filter(rec => 
      rec.permutation.sequence_length >= minSequenceLength && 
      rec.permutation.sequence_length <= maxSequenceLength
    ).slice(0, limit);
    
    res.json({
      success: true,
      data: {
        template: {
          id: template.id,
          title: template.title,
          description: template.description,
          category: template.category,
          type: template.type || 'default',
          complexity: template.complexity
        },
        features: includeFeatures ? features : undefined,
        permutation_recommendations: filteredRecommendations,
        recommendation_type: 'intelligent-permutation-based',
        total_permutations: filteredRecommendations.length,
        filters: {
          min_sequence_length: minSequenceLength,
          max_sequence_length: maxSequenceLength,
          min_confidence: minConfidence
        }
      },
      message: `Found ${filteredRecommendations.length} intelligent permutation-based tech stack recommendations for ${template.title}`
    });
    
  } catch (error) {
    console.error('❌ Error fetching intelligent permutation-based tech stack:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to fetch intelligent permutation-based recommendations',
      message: error.message
    });
  }
});

/**
 * GET /api/enhanced-ckg-tech-stack/combinations/:templateId
 * Get intelligent tech stack recommendations based on feature combinations
 */
router.get('/combinations/:templateId', async (req, res) => {
  try {
    const { templateId } = req.params;
    const includeFeatures = req.query.include_features === 'true';
    const limit = parseInt(req.query.limit) || 10;
    const minSetSize = parseInt(req.query.min_set_size) || 2;
    const maxSetSize = parseInt(req.query.max_set_size) || 5;
    const minConfidence = parseFloat(req.query.min_confidence) || 0.7;
    
    console.log(`🔍 [Enhanced CKG] Fetching intelligent combination-based recommendations for: ${templateId}`);
    
    // Get template details
    const template = await Template.getByIdWithFeatures(templateId) || await CustomTemplate.getByIdWithFeatures(templateId);
    if (!template) {
      return res.status(404).json({
        success: false,
        error: 'Template not found',
        message: `Template with ID ${templateId} does not exist`
      });
    }
    
    // Get template features if requested
    let features = [];
    if (includeFeatures) {
      features = await Feature.getByTemplateId(templateId) || await CustomFeature.getByTemplateId(templateId);
    }
    
    // Get intelligent combination recommendations from Neo4j
    const combinationRecommendations = await ckgService.getIntelligentCombinationRecommendations(templateId, {
      limit,
      minConfidence
    });
    
    // Filter by set size
    const filteredRecommendations = combinationRecommendations.filter(rec => 
      rec.combination.set_size >= minSetSize && 
      rec.combination.set_size <= maxSetSize
    ).slice(0, limit);
    
    res.json({
      success: true,
      data: {
        template: {
          id: template.id,
          title: template.title,
          description: template.description,
          category: template.category,
          type: template.type || 'default',
          complexity: template.complexity
        },
        features: includeFeatures ? features : undefined,
        combination_recommendations: filteredRecommendations,
        recommendation_type: 'intelligent-combination-based',
        total_combinations: filteredRecommendations.length,
        filters: {
          min_set_size: minSetSize,
          max_set_size: maxSetSize,
          min_confidence: minConfidence
        }
      },
      message: `Found ${filteredRecommendations.length} intelligent combination-based tech stack recommendations for ${template.title}`
    });
    
  } catch (error) {
    console.error('❌ Error fetching intelligent combination-based tech stack:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to fetch intelligent combination-based recommendations',
      message: error.message
    });
  }
});

/**
 * POST /api/enhanced-ckg-tech-stack/analyze-compatibility
 * Analyze feature compatibility and generate recommendations
 */
router.post('/analyze-compatibility', async (req, res) => {
  try {
    const { featureIds, templateId } = req.body;
    
    if (!featureIds || !Array.isArray(featureIds) || featureIds.length === 0) {
      return res.status(400).json({
        success: false,
        error: 'Invalid feature IDs',
        message: 'Feature IDs array is required and must not be empty'
      });
    }
    
    console.log(`🔍 [Enhanced CKG] Analyzing compatibility for ${featureIds.length} features`);
    
    // Analyze feature compatibility
    const compatibility = await ckgService.analyzeFeatureCompatibility(featureIds);
    
    res.json({
      success: true,
      data: {
        feature_ids: featureIds,
        compatibility_analysis: compatibility,
        total_features: featureIds.length,
        compatible_features: compatibility.compatible.length,
        dependencies: compatibility.dependencies.length,
        conflicts: compatibility.conflicts.length,
        neutral: compatibility.neutral.length
      },
      message: `Compatibility analysis completed for ${featureIds.length} features`
    });
    
  } catch (error) {
    console.error('❌ Error analyzing feature compatibility:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to analyze feature compatibility',
      message: error.message
    });
  }
});

/**
 * GET /api/enhanced-ckg-tech-stack/synergies
 * Get technology synergies
 */
router.get('/synergies', async (req, res) => {
  try {
    const techNames = req.query.technologies ? req.query.technologies.split(',') : [];
    const limit = parseInt(req.query.limit) || 20;
    
    console.log(`🔍 [Enhanced CKG] Fetching technology synergies`);
    
    if (techNames.length === 0) {
      return res.status(400).json({
        success: false,
        error: 'No technologies specified',
        message: 'Please provide technologies as a comma-separated list'
      });
    }
    
    // Get technology relationships
    const relationships = await ckgService.getTechnologyRelationships(techNames);
    
    res.json({
      success: true,
      data: {
        technologies: techNames,
        synergies: relationships.synergies.slice(0, limit),
        conflicts: relationships.conflicts.slice(0, limit),
        neutral: relationships.neutral.slice(0, limit),
        total_synergies: relationships.synergies.length,
        total_conflicts: relationships.conflicts.length,
        total_neutral: relationships.neutral.length
      },
      message: `Found ${relationships.synergies.length} synergies and ${relationships.conflicts.length} conflicts`
    });
    
  } catch (error) {
    console.error('❌ Error fetching technology synergies:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to fetch technology synergies',
      message: error.message
    });
  }
});

/**
 * GET /api/enhanced-ckg-tech-stack/conflicts
 * Get technology conflicts
 */
router.get('/conflicts', async (req, res) => {
  try {
    const techNames = req.query.technologies ? req.query.technologies.split(',') : [];
    const limit = parseInt(req.query.limit) || 20;
    
    console.log(`🔍 [Enhanced CKG] Fetching technology conflicts`);
    
    if (techNames.length === 0) {
      return res.status(400).json({
        success: false,
        error: 'No technologies specified',
        message: 'Please provide technologies as a comma-separated list'
      });
    }
    
    // Get technology relationships
    const relationships = await ckgService.getTechnologyRelationships(techNames);
    
    res.json({
      success: true,
      data: {
        technologies: techNames,
        conflicts: relationships.conflicts.slice(0, limit),
        synergies: relationships.synergies.slice(0, limit),
        neutral: relationships.neutral.slice(0, limit),
        total_conflicts: relationships.conflicts.length,
        total_synergies: relationships.synergies.length,
        total_neutral: relationships.neutral.length
      },
      message: `Found ${relationships.conflicts.length} conflicts and ${relationships.synergies.length} synergies`
    });
    
  } catch (error) {
    console.error('❌ Error fetching technology conflicts:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to fetch technology conflicts',
      message: error.message
    });
  }
});

/**
 * GET /api/enhanced-ckg-tech-stack/recommendations/:templateId
 * Get comprehensive recommendations for a template
 */
router.get('/recommendations/:templateId', async (req, res) => {
  try {
    const { templateId } = req.params;
    const limit = parseInt(req.query.limit) || 5;
    const minConfidence = parseFloat(req.query.min_confidence) || 0.7;
    
    console.log(`🔍 [Enhanced CKG] Fetching comprehensive recommendations for: ${templateId}`);
    
    // Get template details
    const template = await Template.getByIdWithFeatures(templateId) || await CustomTemplate.getByIdWithFeatures(templateId);
    if (!template) {
      return res.status(404).json({
        success: false,
        error: 'Template not found',
        message: `Template with ID ${templateId} does not exist`
      });
    }
    
    // Get all types of recommendations
    const [permutationRecs, combinationRecs] = await Promise.all([
      ckgService.getIntelligentPermutationRecommendations(templateId, { limit, minConfidence }),
      ckgService.getIntelligentCombinationRecommendations(templateId, { limit, minConfidence })
    ]);
    
    // Use intelligent analyzer for template-based analysis
    const templateContext = {
      type: template.type,
      category: template.category,
      complexity: template.complexity
    };
    
    const templateAnalysis = await techStackAnalyzer.analyzeFeaturesForTechStack(template.features || [], templateContext);
    
    res.json({
      success: true,
      data: {
        template: {
          id: template.id,
          title: template.title,
          description: template.description,
          category: template.category,
          type: template.type || 'default',
          complexity: template.complexity
        },
        recommendations: {
          template_based: templateAnalysis,
          permutation_based: permutationRecs,
          combination_based: combinationRecs
        },
        summary: {
          total_permutations: permutationRecs.length,
          total_combinations: combinationRecs.length,
          template_confidence: templateAnalysis.overall_confidence || 0.8,
          best_approach: getBestApproach(templateAnalysis, permutationRecs, combinationRecs)
        }
      },
      message: `Comprehensive recommendations generated for ${template.title}`
    });
    
  } catch (error) {
    console.error('❌ Error fetching comprehensive recommendations:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to fetch comprehensive recommendations',
      message: error.message
    });
  }
});

/**
 * GET /api/enhanced-ckg-tech-stack/stats
 * Get enhanced CKG statistics
 */
router.get('/stats', async (req, res) => {
  try {
    console.log('📊 [Enhanced CKG] Fetching enhanced CKG statistics');
    
    const stats = await ckgService.getCKGStats();
    
    res.json({
      success: true,
      data: {
        features: stats.get('features'),
        permutations: stats.get('permutations'),
        combinations: stats.get('combinations'),
        tech_stacks: stats.get('tech_stacks'),
        technologies: stats.get('technologies'),
        avg_performance_score: stats.get('avg_performance_score'),
        avg_synergy_score: stats.get('avg_synergy_score'),
        avg_confidence_score: stats.get('avg_confidence_score')
      },
      message: 'Enhanced CKG statistics retrieved successfully'
    });
    
  } catch (error) {
    console.error('❌ Error fetching enhanced CKG stats:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to fetch enhanced CKG statistics',
      message: error.message
    });
  }
});

/**
 * GET /api/enhanced-ckg-tech-stack/health
 * Health check for enhanced CKG service
 */
router.get('/health', async (req, res) => {
  try {
    const isConnected = await ckgService.testConnection();
    
    res.json({
      success: isConnected,
      data: {
        connected: isConnected,
        service: 'Enhanced CKG Neo4j Service',
        timestamp: new Date().toISOString(),
        cache_stats: techStackAnalyzer.getCacheStats()
      },
      message: isConnected ? 'Enhanced CKG service is healthy' : 'Enhanced CKG service is not responding'
    });
    
  } catch (error) {
    console.error('❌ Enhanced CKG health check failed:', error.message);
    res.status(500).json({
      success: false,
      error: 'Enhanced CKG health check failed',
      message: error.message
    });
  }
});

/**
 * Helper function to determine the best approach based on recommendations
 */
function getBestApproach(templateAnalysis, permutations, combinations) {
  const scores = {
    template: (templateAnalysis.overall_confidence || 0.8) * 0.4,
    permutation: permutations.length * 0.3,
    combination: combinations.length * 0.3
  };
  
  return Object.keys(scores).reduce((a, b) => scores[a] > scores[b] ? a : b);
}

module.exports = router;
