const database = require('../config/database');
const EnhancedCKGService = require('./enhanced-ckg-service');
const IntelligentTechStackAnalyzer = require('./intelligent-tech-stack-analyzer');
const Neo4jNamespaceService = require('./neo4j-namespace-service');
const { v4: uuidv4 } = require('uuid');

/**
 * Enhanced CKG Migration Service
 * Handles migration from PostgreSQL to Neo4j with intelligent tech stack analysis
 */
class EnhancedCKGMigrationService {
  constructor() {
    this.ckgService = new EnhancedCKGService();
    this.techStackAnalyzer = new IntelligentTechStackAnalyzer();
    this.neo4jService = new Neo4jNamespaceService('TM');
    this.migrationStats = {
      templates: 0,
      features: 0,
      permutations: 0,
      combinations: 0,
      techStacks: 0,
      technologies: 0,
      relationships: 0,
      errors: 0
    };
  }

  /**
   * Migrate all templates to enhanced CKG (sequential processing)
   */
  async migrateAllTemplates() {
    console.log('🚀 Starting Enhanced CKG migration for all templates...');
    
    try {
      // Get all active templates with their features
      const templates = await this.getAllTemplatesWithFeatures();
      console.log(`📊 Found ${templates.length} templates to migrate`);
      
      // Process templates one by one sequentially
      for (let i = 0; i < templates.length; i++) {
        const template = templates[i];
        console.log(`\n🔄 Processing template ${i + 1}/${templates.length}: ${template.title} (${template.id})`);
        
        // Check if template already has CKG data to prevent duplicates
        const hasExistingCKG = await this.checkTemplateHasCKGData(template.id);
        if (hasExistingCKG) {
          console.log(`⏭️ Template ${template.id} already has CKG data, skipping...`);
          continue;
        }
        
        // Process this template completely before moving to next
        await this.migrateTemplateToEnhancedCKG(template);
        console.log(`✅ Template ${template.id} completed (${i + 1}/${templates.length})`);
        
        // Small delay between templates to prevent overwhelming the system
        await new Promise(resolve => setTimeout(resolve, 1000));
      }
      
      // Create technology relationships only once at the end
      console.log('\n🔗 Creating technology relationships...');
      await this.createTechnologyRelationships();
      
      console.log('✅ Enhanced CKG migration completed successfully');
      return this.migrationStats;
    } catch (error) {
      console.error('❌ Enhanced CKG migration failed:', error.message);
      throw error;
    }
  }

  /**
   * Migrate specific template to enhanced CKG
   */
  async migrateTemplateToEnhancedCKG(template) {
    console.log(`🔄 Migrating template ${template.id} to Enhanced CKG...`);
    
    try {
      if (!template) {
        throw new Error(`Template not found`);
      }
      
      // Check if template already has CKG data to prevent duplicates
      const hasExistingCKG = await this.checkTemplateHasCKGData(template.id);
      if (hasExistingCKG) {
        console.log(`⏭️ Template ${template.id} already has CKG data, skipping migration...`);
        return;
      }
      
      // Create template node
      await this.ckgService.createTemplateNode(template);
      this.migrationStats.templates++;
      
      // Create feature nodes and relationships
      for (const feature of template.features) {
        await this.ckgService.createFeatureNode(feature);
        await this.ckgService.createTemplateFeatureRelationship(template.id, feature.id);
        this.migrationStats.features++;
        
        // Create feature dependency relationships if they exist
        if (feature.dependencies && feature.dependencies.length > 0) {
          await this.ckgService.createFeatureDependencyRelationships(feature.id, feature.dependencies);
          this.migrationStats.relationships += feature.dependencies.length;
        }
        
        // Create feature conflict relationships if they exist
        if (feature.conflicts && feature.conflicts.length > 0) {
          await this.ckgService.createFeatureConflictRelationships(feature.id, feature.conflicts);
          this.migrationStats.relationships += feature.conflicts.length;
        }
      }
      
      // Generate enhanced permutations and combinations
      await this.generateEnhancedPermutationsAndCombinations(template);
      
      console.log(`✅ Template ${template.id} migrated to Enhanced CKG successfully`);
    } catch (error) {
      console.error(`❌ Failed to migrate template ${template.id}:`, error.message);
      this.migrationStats.errors++;
      throw error;
    }
  }

  /**
   * Check if template already has CKG data to prevent duplicates
   */
  async checkTemplateHasCKGData(templateId) {
    try {
      const session = this.ckgService.driver.session();
      const result = await session.run(`
        MATCH (t:Template {id: $templateId})
        OPTIONAL MATCH (t)<-[:template_id]-(c:Combination)
        OPTIONAL MATCH (t)<-[:template_id]-(p:Permutation)
        OPTIONAL MATCH (t)-[:HAS_FEATURE]->(f:Feature)
        RETURN count(c) as combination_count, count(p) as permutation_count, count(f) as feature_count
      `, { templateId });
      
      await session.close();
      
      const record = result.records[0];
      const combinationCount = record.get('combination_count').toNumber();
      const permutationCount = record.get('permutation_count').toNumber();
      const featureCount = record.get('feature_count').toNumber();
      
      // Template has CKG data if it has features AND (combinations OR permutations)
      const hasCKGData = featureCount > 0 && (combinationCount > 0 || permutationCount > 0);
      console.log(`🔍 Template ${templateId} CKG check: ${featureCount} features, ${combinationCount} combinations, ${permutationCount} permutations, hasCKG: ${hasCKGData}`);
      return hasCKGData;
    } catch (error) {
      console.error(`❌ Failed to check CKG data for template ${templateId}:`, error.message);
      return false; // If check fails, assume no data and proceed
    }
  }

  /**
   * Get all templates with their features
   */
  async getAllTemplatesWithFeatures() {
    const query = `
      SELECT 
        t.id, t.type, t.title, t.description, t.category, t.is_active,
        tf.id as feature_id, tf.name, tf.description as feature_description,
        tf.feature_type, tf.complexity, tf.display_order, tf.usage_count,
        tf.user_rating, tf.is_default, tf.created_by_user
      FROM templates t
      LEFT JOIN template_features tf ON t.id = tf.template_id
      WHERE t.is_active = true AND t.type != '_migration_test'
      ORDER BY t.id, tf.display_order, tf.name
    `;
    
    const result = await database.query(query);
    
    // Group by template
    const templatesMap = new Map();
    
    for (const row of result.rows) {
      const templateId = row.id;
      
      if (!templatesMap.has(templateId)) {
        templatesMap.set(templateId, {
          id: row.id,
          type: row.type,
          title: row.title,
          description: row.description,
          category: row.category,
          is_active: row.is_active,
          features: []
        });
      }
      
      if (row.feature_id) {
        templatesMap.get(templateId).features.push({
          id: row.feature_id,
          name: row.name,
          description: row.feature_description,
          feature_type: row.feature_type,
          complexity: row.complexity,
          display_order: row.display_order,
          usage_count: row.usage_count,
          user_rating: row.user_rating,
          is_default: row.is_default,
          created_by_user: row.created_by_user,
          template_id: row.id,
          dependencies: [],
          conflicts: []
        });
      }
    }
    
    return Array.from(templatesMap.values());
  }

  /**
   * Generate enhanced permutations and combinations with intelligent analysis
   */
  async generateEnhancedPermutationsAndCombinations(template) {
    const features = template.features || [];
    if (features.length === 0) {
      console.log(`⚠️ No features found for template ${template.id}`);
      return;
    }
    
    console.log(`🧮 Generating enhanced permutations and combinations for template ${template.id} with ${features.length} features`);
    
    // Generate all permutations (ordered sequences)
    const permutations = this.generatePermutations(features);
    console.log(`📊 Generated ${permutations.length} permutations`);
    
    // Generate all combinations (unordered sets)
    const combinations = this.generateCombinations(features);
    console.log(`📊 Generated ${combinations.length} combinations`);
    
    // Create permutation nodes and relationships with intelligent analysis
    for (const permutation of permutations) {
      await this.createEnhancedPermutationNode(template.id, permutation);
    }
    
    // Create combination nodes and relationships with intelligent analysis
    for (const combination of combinations) {
      await this.createEnhancedCombinationNode(template.id, combination);
    }
    
    console.log(`✅ Enhanced permutations and combinations generated for template ${template.id}`);
  }

  /**
   * Generate all permutations of features
   */
  generatePermutations(features) {
    if (!features || features.length === 0) {
      return [];
    }
    
    const permutations = [];
    
    // Generate permutations of all lengths (1 to n)
    for (let length = 1; length <= features.length; length++) {
      const perms = this.getPermutationsOfLength(features, length);
      permutations.push(...perms);
    }
    
    return permutations;
  }

  /**
   * Generate permutations of specific length
   */
  getPermutationsOfLength(features, length) {
    if (length === 0) return [[]];
    if (length === 1) return features.map(f => [f]);
    
    const permutations = [];
    
    for (let i = 0; i < features.length; i++) {
      const current = features[i];
      const remaining = features.filter((_, index) => index !== i);
      const subPermutations = this.getPermutationsOfLength(remaining, length - 1);
      
      for (const subPerm of subPermutations) {
        permutations.push([current, ...subPerm]);
      }
    }
    
    return permutations;
  }

  /**
   * Generate all combinations of features
   */
  generateCombinations(features) {
    if (!features || features.length === 0) {
      return [];
    }
    
    const combinations = [];
    
    // Generate combinations of all sizes (1 to n)
    for (let size = 1; size <= features.length; size++) {
      const combs = this.getCombinationsOfSize(features, size);
      combinations.push(...combs);
    }
    
    return combinations;
  }

  /**
   * Generate combinations of specific size
   */
  getCombinationsOfSize(features, size) {
    if (size === 0) return [[]];
    if (size === 1) return features.map(f => [f]);
    if (size === features.length) return [features];
    
    const combinations = [];
    
    for (let i = 0; i <= features.length - size; i++) {
      const current = features[i];
      const remaining = features.slice(i + 1);
      const subCombinations = this.getCombinationsOfSize(remaining, size - 1);
      
      for (const subComb of subCombinations) {
        combinations.push([current, ...subComb]);
      }
    }
    
    return combinations;
  }

  /**
   * Create enhanced permutation node with intelligent analysis
   */
  async createEnhancedPermutationNode(templateId, features) {
    try {
      const permutationId = uuidv4();
      const featureIds = features.map(f => f.id || f.feature_id);
      const complexityScore = this.calculateComplexityScore(features);
      const performanceScore = this.calculatePerformanceScore(features);
      const compatibilityScore = this.calculateCompatibilityScore(features);
      
      const permutationData = {
        id: permutationId,
        template_id: templateId,
        feature_sequence: featureIds,
        sequence_length: features.length,
        complexity_score: complexityScore,
        usage_frequency: 0,
        performance_score: performanceScore,
        compatibility_score: compatibilityScore,
        created_at: new Date()
      };
      
      await this.ckgService.createPermutationNode(permutationData);
      await this.ckgService.createPermutationFeatureRelationships(permutationId, features);
      
      // Generate intelligent tech stack for this permutation
      await this.generateIntelligentTechStackForPermutation(permutationId, features, templateId);
      
      this.migrationStats.permutations++;
    } catch (error) {
      console.error('❌ Failed to create enhanced permutation node:', error.message);
      this.migrationStats.errors++;
    }
  }

  /**
   * Create enhanced combination node with intelligent analysis
   */
  async createEnhancedCombinationNode(templateId, features) {
    try {
      const combinationId = uuidv4();
      const featureIds = features.map(f => f.id || f.feature_id);
      const complexityScore = this.calculateComplexityScore(features);
      const synergyScore = this.calculateSynergyScore(features);
      const compatibilityScore = this.calculateCompatibilityScore(features);
      
      const combinationData = {
        id: combinationId,
        template_id: templateId,
        feature_set: featureIds,
        set_size: features.length,
        complexity_score: complexityScore,
        usage_frequency: 0,
        synergy_score: synergyScore,
        compatibility_score: compatibilityScore,
        created_at: new Date()
      };
      
      await this.ckgService.createCombinationNode(combinationData);
      await this.ckgService.createCombinationFeatureRelationships(combinationId, features);
      
      // Generate intelligent tech stack for this combination
      await this.generateIntelligentTechStackForCombination(combinationId, features, templateId);
      
      this.migrationStats.combinations++;
    } catch (error) {
      console.error('❌ Failed to create enhanced combination node:', error.message);
      this.migrationStats.errors++;
    }
  }

  /**
   * Generate intelligent tech stack for permutation
   */
  async generateIntelligentTechStackForPermutation(permutationId, features, templateId) {
    try {
      const templateContext = {
        type: 'web application',
        category: 'general',
        complexity: 'medium'
      };
      
      // Use intelligent analyzer to get tech stack recommendations
      const analysis = await this.techStackAnalyzer.analyzeFeaturesForTechStack(features, templateContext);
      
      const techStackId = uuidv4();
      const techStackData = {
        id: techStackId,
        permutation_id: permutationId,
        frontend_tech: analysis.frontend_tech || [],
        backend_tech: analysis.backend_tech || [],
        database_tech: analysis.database_tech || [],
        devops_tech: analysis.devops_tech || [],
        mobile_tech: analysis.mobile_tech || [],
        cloud_tech: analysis.cloud_tech || [],
        testing_tech: analysis.testing_tech || [],
        ai_ml_tech: analysis.ai_ml_tech || [],
        tools_tech: analysis.tools_tech || [],
        confidence_score: analysis.overall_confidence || 0.8,
        complexity_level: analysis.complexity_assessment || 'medium',
        estimated_effort: analysis.estimated_development_time || '2-4 weeks',
        ai_model: 'claude-3-5-sonnet',
        analysis_version: '1.0',
        created_at: new Date()
      };
      
      await this.ckgService.createTechStackNode(techStackData);
      await this.ckgService.createTechStackRelationships(permutationId, 'Permutation', techStackId);
      
      // Create technology nodes and relationships
      await this.createTechnologyNodesAndRelationships(techStackId, analysis);
      
      this.migrationStats.techStacks++;
    } catch (error) {
      console.error('❌ Failed to generate intelligent tech stack for permutation:', error.message);
      this.migrationStats.errors++;
    }
  }

  /**
   * Generate intelligent tech stack for combination
   */
  async generateIntelligentTechStackForCombination(combinationId, features, templateId) {
    try {
      const templateContext = {
        type: 'web application',
        category: 'general',
        complexity: 'medium'
      };
      
      // Use intelligent analyzer to get tech stack recommendations
      const analysis = await this.techStackAnalyzer.analyzeFeaturesForTechStack(features, templateContext);
      
      const techStackId = uuidv4();
      const techStackData = {
        id: techStackId,
        combination_id: combinationId,
        frontend_tech: analysis.frontend_tech || [],
        backend_tech: analysis.backend_tech || [],
        database_tech: analysis.database_tech || [],
        devops_tech: analysis.devops_tech || [],
        mobile_tech: analysis.mobile_tech || [],
        cloud_tech: analysis.cloud_tech || [],
        testing_tech: analysis.testing_tech || [],
        ai_ml_tech: analysis.ai_ml_tech || [],
        tools_tech: analysis.tools_tech || [],
        confidence_score: analysis.overall_confidence || 0.8,
        complexity_level: analysis.complexity_assessment || 'medium',
        estimated_effort: analysis.estimated_development_time || '2-4 weeks',
        ai_model: 'claude-3-5-sonnet',
        analysis_version: '1.0',
        created_at: new Date()
      };
      
      await this.ckgService.createTechStackNode(techStackData);
      await this.ckgService.createTechStackRelationships(combinationId, 'Combination', techStackId);
      
      // Create technology nodes and relationships
      await this.createTechnologyNodesAndRelationships(techStackId, analysis);
      
      this.migrationStats.techStacks++;
    } catch (error) {
      console.error('❌ Failed to generate intelligent tech stack for combination:', error.message);
      this.migrationStats.errors++;
    }
  }

  /**
   * Create technology nodes and relationships
   */
  async createTechnologyNodesAndRelationships(techStackId, analysis) {
    try {
      const allTechnologies = [
        ...(analysis.frontend_tech || []),
        ...(analysis.backend_tech || []),
        ...(analysis.database_tech || []),
        ...(analysis.devops_tech || []),
        ...(analysis.mobile_tech || []),
        ...(analysis.cloud_tech || []),
        ...(analysis.testing_tech || []),
        ...(analysis.ai_ml_tech || []),
        ...(analysis.tools_tech || [])
      ];
      
      for (const tech of allTechnologies) {
        // Create technology node
        await this.ckgService.createTechnologyNode(tech);
        this.migrationStats.technologies++;
        
        // Create tech stack-technology relationship
        await this.ckgService.createTechStackTechnologyRelationship(
          techStackId,
          tech.name,
          tech.category,
          {
            confidence: tech.confidence || 0.8,
            reasoning: tech.reasoning || '',
            alternatives: tech.alternatives || []
          }
        );
        this.migrationStats.relationships++;
      }
    } catch (error) {
      console.error('❌ Failed to create technology nodes and relationships:', error.message);
      this.migrationStats.errors++;
    }
  }

  /**
   * Create technology relationships (synergies and conflicts)
   */
  async createTechnologyRelationships() {
    console.log('🔗 Creating technology relationships...');
    
    try {
      // Create some common technology synergies
      const synergies = [
        { tech1: 'React', tech2: 'Node.js', score: 0.9 },
        { tech1: 'React', tech2: 'Express.js', score: 0.8 },
        { tech1: 'Node.js', tech2: 'PostgreSQL', score: 0.9 },
        { tech1: 'Docker', tech2: 'Kubernetes', score: 0.9 },
        { tech1: 'AWS', tech2: 'Docker', score: 0.8 }
      ];
      
      for (const synergy of synergies) {
        await this.ckgService.createTechnologySynergyRelationships(
          synergy.tech1,
          synergy.tech2,
          synergy.score
        );
        this.migrationStats.relationships++;
      }
      
      // Create some common technology conflicts
      const conflicts = [
        { tech1: 'Vue.js', tech2: 'Angular', severity: 'high' },
        { tech1: 'React', tech2: 'Angular', severity: 'medium' },
        { tech1: 'MySQL', tech2: 'PostgreSQL', severity: 'low' }
      ];
      
      for (const conflict of conflicts) {
        await this.ckgService.createTechnologyConflictRelationships(
          conflict.tech1,
          conflict.tech2,
          conflict.severity
        );
        this.migrationStats.relationships++;
      }
      
      console.log('✅ Technology relationships created');
    } catch (error) {
      console.error('❌ Failed to create technology relationships:', error.message);
      this.migrationStats.errors++;
    }
  }

  /**
   * Calculate complexity score for feature set
   */
  calculateComplexityScore(features) {
    if (!features || features.length === 0) {
      return 0;
    }
    
    const complexityMap = { low: 1, medium: 2, high: 3 };
    const totalScore = features.reduce((sum, feature) => {
      return sum + (complexityMap[feature.complexity] || 2);
    }, 0);
    
    return totalScore / features.length;
  }

  /**
   * Calculate performance score for feature set
   */
  calculatePerformanceScore(features) {
    if (!features || features.length === 0) {
      return 0;
    }
    
    // Simple performance scoring based on feature types
    let performanceScore = 0.8; // Base score
    
    for (const feature of features) {
      const featureName = feature.name.toLowerCase();
      
      if (featureName.includes('cache') || featureName.includes('optimization')) {
        performanceScore += 0.1;
      } else if (featureName.includes('analytics') || featureName.includes('reporting')) {
        performanceScore -= 0.05;
      }
    }
    
    return Math.min(1.0, Math.max(0.0, performanceScore));
  }

  /**
   * Calculate compatibility score for feature set
   */
  calculateCompatibilityScore(features) {
    if (!features || features.length === 0) {
      return 0;
    }
    
    // Simple compatibility scoring
    let compatibilityScore = 0.9; // Base score
    
    // Check for potential conflicts
    const featureNames = features.map(f => f.name.toLowerCase());
    
    // Example conflict detection
    if (featureNames.includes('mobile') && featureNames.includes('desktop')) {
      compatibilityScore -= 0.2;
    }
    
    return Math.min(1.0, Math.max(0.0, compatibilityScore));
  }

  /**
   * Calculate synergy score for feature set
   */
  calculateSynergyScore(features) {
    if (!features || features.length === 0) {
      return 0;
    }
    
    // Simple synergy scoring based on feature interactions
    let synergyScore = 0.7; // Base score
    
    const featureNames = features.map(f => f.name.toLowerCase());
    
    // Check for synergistic features
    if (featureNames.includes('auth') && featureNames.includes('user')) {
      synergyScore += 0.1;
    }
    
    if (featureNames.includes('payment') && featureNames.includes('order')) {
      synergyScore += 0.1;
    }
    
    if (featureNames.includes('dashboard') && featureNames.includes('analytics')) {
      synergyScore += 0.1;
    }
    
    return Math.min(1.0, Math.max(0.0, synergyScore));
  }

  /**
   * Get migration statistics
   */
  async getMigrationStats() {
    try {
      const ckgStats = await this.ckgService.getCKGStats();
      return {
        ...this.migrationStats,
        ckg_stats: ckgStats
      };
    } catch (error) {
      console.error('❌ Failed to get migration stats:', error.message);
      return this.migrationStats;
    }
  }

  /**
   * Comprehensive fix for all templates - ensures all have proper combinations and tech stacks
   */
  async fixAllTemplatesComprehensive() {
    console.log('🔧 Starting comprehensive template fix...');
    
    try {
      // Step 1: Fix confidence scores for all tech stacks
      await this.fixConfidenceScores();
      
      // Step 2: Create missing combinations for all templates
      await this.createMissingCombinationsForAllTemplates();
      
      // Step 3: Link all combinations to tech stacks
      await this.linkAllCombinationsToTechStacks();
      
      // Step 4: Link all tech stacks to technologies
      await this.linkAllTechStacksToTechnologies();
      
      console.log('✅ Comprehensive template fix completed');
      return { success: true, message: 'All templates fixed successfully' };
    } catch (error) {
      console.error('❌ Comprehensive template fix failed:', error.message);
      return { success: false, error: error.message };
    }
  }

  /**
   * Fix confidence scores for all tech stacks
   */
  async fixConfidenceScores() {
    const session = this.ckgService.driver.session();
    try {
      console.log('🔧 Fixing confidence scores...');
      
      const result = await session.run(`
        MATCH (ts:TechStack)
        WHERE ts.confidence_score IS NULL
        SET ts.confidence_score = 0.8
        RETURN count(ts) as updated_count
      `);
      
      console.log(`✅ Updated ${result.records[0].get('updated_count')} tech stack confidence scores`);
    } finally {
      await session.close();
    }
  }

  /**
   * Create missing combinations for all templates
   */
  async createMissingCombinationsForAllTemplates() {
    const session = this.ckgService.driver.session();
    try {
      console.log('🔧 Creating missing combinations...');
      
      // Get all templates without combinations
      const templatesWithoutCombinations = await session.run(`
        MATCH (t:Template)
        WHERE NOT EXISTS((t)<-[:template_id]-(:Combination))
        RETURN t.id as template_id, t.title as title
      `);
      
      console.log(`Found ${templatesWithoutCombinations.records.length} templates without combinations`);
      
      for (const record of templatesWithoutCombinations.records) {
        const templateId = record.get('template_id');
        const title = record.get('title');
        
        try {
          // Get template features
          const featuresResult = await session.run(`
            MATCH (t:Template {id: $templateId})-[:HAS_FEATURE]->(f:Feature)
            RETURN f.id as feature_id, f.name as name
            ORDER BY f.name
            LIMIT 5
          `, { templateId });
          
          const features = featuresResult.records.map(r => ({
            id: r.get('feature_id'),
            name: r.get('name')
          }));
          
          if (features.length === 0) {
            console.log(`⚠️ No features found for template: ${title}`);
            continue;
          }
          
          // Create combinations
          const combinations = this.generateKeyCombinations(features);
          
          for (const combination of combinations) {
            const combinationId = uuidv4();
            await session.run(`
              CREATE (c:Combination {
                id: $combinationId,
                template_id: $templateId,
                feature_set: $featureSet,
                set_size: $setSize,
                complexity_score: $complexityScore,
                synergy_score: $synergyScore,
                compatibility_score: $compatibilityScore,
                usage_frequency: 0,
                created_at: datetime()
              })
            `, {
              combinationId,
              templateId,
              featureSet: JSON.stringify(combination.map(f => f.id)),
              setSize: combination.length,
              complexityScore: combination.length * 0.5,
              synergyScore: 0.7,
              compatibilityScore: 0.8
            });
          }
          
          console.log(`✅ Created ${combinations.length} combinations for: ${title}`);
          
        } catch (error) {
          console.error(`❌ Failed to create combinations for ${title}:`, error.message);
        }
      }
      
    } finally {
      await session.close();
    }
  }

  /**
   * Generate key combinations for features
   */
  generateKeyCombinations(features) {
    const combinations = [];
    
    // Single features
    for (const feature of features) {
      combinations.push([feature]);
    }
    
    // Pairs
    if (features.length >= 2) {
      for (let i = 0; i < Math.min(3, features.length - 1); i++) {
        for (let j = i + 1; j < Math.min(5, features.length); j++) {
          combinations.push([features[i], features[j]]);
        }
      }
    }
    
    // Triples
    if (features.length >= 3) {
      for (let i = 0; i < Math.min(2, features.length - 2); i++) {
        for (let j = i + 1; j < Math.min(3, features.length - 1); j++) {
          for (let k = j + 1; k < Math.min(4, features.length); k++) {
            combinations.push([features[i], features[j], features[k]]);
          }
        }
      }
    }
    
    return combinations;
  }

  /**
   * Link all combinations to tech stacks
   */
  async linkAllCombinationsToTechStacks() {
    const session = this.ckgService.driver.session();
    try {
      console.log('🔧 Linking all combinations to tech stacks...');
      
      const result = await session.run(`
        MATCH (c:Combination)
        MATCH (ts:TechStack {template_id: c.template_id})
        WHERE NOT (c)-[:RECOMMENDS_TECH_STACK]->(ts)
        CREATE (c)-[:RECOMMENDS_TECH_STACK]->(ts)
        RETURN count(*) as linked_count
      `);
      
      console.log(`✅ Linked ${result.records[0].get('linked_count')} combination-tech stack relationships`);
    } finally {
      await session.close();
    }
  }

  /**
   * Link all tech stacks to technologies
   */
  async linkAllTechStacksToTechnologies() {
    const session = this.ckgService.driver.session();
    try {
      console.log('🔧 Linking all tech stacks to technologies...');
      
      // Link each tech stack to technologies
      const result = await session.run(`
        MATCH (ts:TechStack)
        MATCH (tech:Technology)
        WHERE NOT (ts)-[:INCLUDES_TECHNOLOGY]->(tech)
        WITH ts, tech
        LIMIT 2000
        CREATE (ts)-[:INCLUDES_TECHNOLOGY {category: 'general', confidence: 0.8}]->(tech)
        RETURN count(*) as linked_count
      `);
      
      console.log(`✅ Linked ${result.records[0].get('linked_count')} tech stack-technology relationships`);
    } finally {
      await session.close();
    }
  }

  /**
   * Close connections
   */
  async close() {
    await this.ckgService.close();
  }
}

module.exports = EnhancedCKGMigrationService;
