const express = require('express');
const router = express.Router();
const EnhancedCKGMigrationService = require('../services/enhanced-ckg-migration-service');

/**
 * CKG Migration Routes
 * Handles migration from PostgreSQL to Neo4j CKG
 * Manages permutations, combinations, and tech stack mappings
 */

// POST /api/ckg-migration/migrate - Migrate all templates to CKG
router.post('/migrate', async (req, res) => {
  try {
    console.log('🚀 Starting CKG migration...');
    
    const migrationService = new EnhancedCKGMigrationService();
    const stats = await migrationService.migrateAllTemplates();
    await migrationService.close();
    
    res.json({
      success: true,
      data: stats,
      message: 'CKG migration completed successfully'
    });
  } catch (error) {
    console.error('❌ CKG migration failed:', error.message);
    res.status(500).json({
      success: false,
      error: 'Migration failed',
      message: error.message
    });
  }
});

// POST /api/ckg-migration/fix-all - Automated comprehensive fix for all templates
router.post('/fix-all', async (req, res) => {
  try {
    console.log('🔧 Starting automated comprehensive template fix...');
    
    const migrationService = new EnhancedCKGMigrationService();
    
    // Step 1: Get all templates and check their status
    const templates = await migrationService.getAllTemplatesWithFeatures();
    console.log(`📊 Found ${templates.length} templates to check`);
    
    let processedCount = 0;
    let skippedCount = 0;
    
    // Step 2: Process templates one by one
    for (let i = 0; i < templates.length; i++) {
      const template = templates[i];
      console.log(`\n🔄 Processing template ${i + 1}/${templates.length}: ${template.title}`);
      
      const hasExistingCKG = await migrationService.checkTemplateHasCKGData(template.id);
      if (hasExistingCKG) {
        console.log(`⏭️ Template ${template.id} already has CKG data, skipping...`);
        skippedCount++;
      } else {
        console.log(`🔄 Template ${template.id} needs CKG migration...`);
        await migrationService.migrateTemplateToEnhancedCKG(template);
        processedCount++;
      }
    }
    
    // Step 3: Run comprehensive fix only if needed
    let fixResult = { success: true, message: 'No new templates to fix' };
    if (processedCount > 0) {
      console.log('🔧 Running comprehensive template fix...');
      fixResult = await migrationService.fixAllTemplatesComprehensive();
    }
    
    await migrationService.close();
    
    res.json({
      success: true,
      message: `Automated fix completed: ${processedCount} processed, ${skippedCount} skipped`,
      data: { 
        processed: processedCount,
        skipped: skippedCount,
        total: templates.length,
        fixResult: fixResult
      }
    });
  } catch (error) {
    console.error('❌ Automated comprehensive fix failed:', error.message);
    res.status(500).json({
      success: false,
      error: 'Automated fix failed',
      message: error.message
    });
  }
});

// POST /api/ckg-migration/cleanup-duplicates - Clean up duplicate templates
router.post('/cleanup-duplicates', async (req, res) => {
  try {
    console.log('🧹 Starting duplicate cleanup...');
    
    const migrationService = new EnhancedCKGMigrationService();
    const result = await migrationService.ckgService.cleanupDuplicates();
    await migrationService.close();
    
    if (result.success) {
      res.json({
        success: true,
        message: 'Duplicate cleanup completed successfully',
        data: {
          removedCount: result.removedCount,
          duplicateCount: result.duplicateCount,
          totalTemplates: result.totalTemplates
        }
      });
    } else {
      res.status(500).json({
        success: false,
        error: 'Cleanup failed',
        message: result.error
      });
    }
  } catch (error) {
    console.error('❌ Duplicate cleanup failed:', error.message);
    res.status(500).json({
      success: false,
      error: 'Cleanup failed',
      message: error.message
    });
  }
});

// GET /api/ckg-migration/stats - Get migration statistics
router.get('/stats', async (req, res) => {
  try {
    const migrationService = new EnhancedCKGMigrationService();
    const stats = await migrationService.getMigrationStats();
    await migrationService.close();
    
    res.json({
      success: true,
      data: stats,
      message: 'CKG migration statistics'
    });
  } catch (error) {
    console.error('❌ Failed to get migration stats:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to get stats',
      message: error.message
    });
  }
});

// POST /api/ckg-migration/clear - Clear CKG data
router.post('/clear', async (req, res) => {
  try {
    console.log('🧹 Clearing CKG data...');
    
    const migrationService = new EnhancedCKGMigrationService();
    await migrationService.neo4j.clearCKG();
    await migrationService.close();
    
    res.json({
      success: true,
      message: 'CKG data cleared successfully'
    });
  } catch (error) {
    console.error('❌ Failed to clear CKG:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to clear CKG',
      message: error.message
    });
  }
});

// POST /api/ckg-migration/template/:id - Migrate single template
router.post('/template/:id', async (req, res) => {
  try {
    const { id } = req.params;
    console.log(`🔄 Migrating template ${id} to CKG...`);
    
    const migrationService = new EnhancedCKGMigrationService();
    await migrationService.migrateTemplateToCKG(id);
    await migrationService.close();
    
    res.json({
      success: true,
      message: `Template ${id} migrated to CKG successfully`
    });
  } catch (error) {
    console.error(`❌ Failed to migrate template ${req.params.id}:`, error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to migrate template',
      message: error.message
    });
  }
});

// GET /api/ckg-migration/template/:id/permutations - Get template permutations
router.get('/template/:id/permutations', async (req, res) => {
  try {
    const { id } = req.params;
    
    const migrationService = new EnhancedCKGMigrationService();
    const permutations = await migrationService.neo4j.getTemplatePermutations(id);
    await migrationService.close();
    
    res.json({
      success: true,
      data: permutations,
      message: `Permutations for template ${id}`
    });
  } catch (error) {
    console.error(`❌ Failed to get permutations for template ${req.params.id}:`, error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to get permutations',
      message: error.message
    });
  }
});

// GET /api/ckg-migration/template/:id/combinations - Get template combinations
router.get('/template/:id/combinations', async (req, res) => {
  try {
    const { id } = req.params;
    
    const migrationService = new EnhancedCKGMigrationService();
    const combinations = await migrationService.neo4j.getTemplateCombinations(id);
    await migrationService.close();
    
    res.json({
      success: true,
      data: combinations,
      message: `Combinations for template ${id}`
    });
  } catch (error) {
    console.error(`❌ Failed to get combinations for template ${req.params.id}:`, error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to get combinations',
      message: error.message
    });
  }
});

// GET /api/ckg-migration/combination/:id/tech-stack - Get tech stack for combination
router.get('/combination/:id/tech-stack', async (req, res) => {
  try {
    const { id } = req.params;
    
    const migrationService = new EnhancedCKGMigrationService();
    const techStack = await migrationService.neo4j.getCombinationTechStack(id);
    await migrationService.close();
    
    res.json({
      success: true,
      data: techStack,
      message: `Tech stack for combination ${id}`
    });
  } catch (error) {
    console.error(`❌ Failed to get tech stack for combination ${req.params.id}:`, error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to get tech stack',
      message: error.message
    });
  }
});

// GET /api/ckg-migration/permutation/:id/tech-stack - Get tech stack for permutation
router.get('/permutation/:id/tech-stack', async (req, res) => {
  try {
    const { id } = req.params;
    
    const migrationService = new EnhancedCKGMigrationService();
    const techStack = await migrationService.neo4j.getPermutationTechStack(id);
    await migrationService.close();
    
    res.json({
      success: true,
      data: techStack,
      message: `Tech stack for permutation ${id}`
    });
  } catch (error) {
    console.error(`❌ Failed to get tech stack for permutation ${req.params.id}:`, error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to get tech stack',
      message: error.message
    });
  }
});

// GET /api/ckg-migration/health - Health check for CKG
router.get('/health', async (req, res) => {
  try {
    const migrationService = new EnhancedCKGMigrationService();
    const isConnected = await migrationService.neo4j.testConnection();
    await migrationService.close();
    
    res.json({
      success: true,
      data: {
        ckg_connected: isConnected,
        timestamp: new Date().toISOString()
      },
      message: 'CKG health check completed'
    });
  } catch (error) {
    console.error('❌ CKG health check failed:', error.message);
    res.status(500).json({
      success: false,
      error: 'Health check failed',
      message: error.message
    });
  }
});

// POST /api/ckg-migration/generate-permutations - Generate permutations for features
router.post('/generate-permutations', async (req, res) => {
  try {
    const { features, templateId } = req.body;
    
    if (!features || !Array.isArray(features) || features.length === 0) {
      return res.status(400).json({
        success: false,
        error: 'Invalid features',
        message: 'Features array is required and must not be empty'
      });
    }
    
    const migrationService = new EnhancedCKGMigrationService();
    
    // Generate permutations
    const permutations = migrationService.generatePermutations(features);
    
    // Generate combinations
    const combinations = migrationService.generateCombinations(features);
    
    await migrationService.close();
    
    res.json({
      success: true,
      data: {
        permutations: permutations,
        combinations: combinations,
        permutation_count: permutations.length,
        combination_count: combinations.length
      },
      message: `Generated ${permutations.length} permutations and ${combinations.length} combinations`
    });
  } catch (error) {
    console.error('❌ Failed to generate permutations/combinations:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to generate permutations/combinations',
      message: error.message
    });
  }
});

// POST /api/ckg-migration/analyze-feature-combination - Analyze feature combination
router.post('/analyze-feature-combination', async (req, res) => {
  try {
    const { features, combinationType = 'combination' } = req.body;
    
    if (!features || !Array.isArray(features) || features.length === 0) {
      return res.status(400).json({
        success: false,
        error: 'Invalid features',
        message: 'Features array is required and must not be empty'
      });
    }
    
    const migrationService = new EnhancedCKGMigrationService();
    
    // Calculate complexity score
    const complexityScore = migrationService.calculateComplexityScore(features);
    
    // Generate tech stack recommendation
    const techStack = migrationService.generateTechStackForFeatures(features);
    
    // Get complexity level and estimated effort
    const complexityLevel = migrationService.getComplexityLevel(features);
    const estimatedEffort = migrationService.getEstimatedEffort(features);
    
    await migrationService.close();
    
    res.json({
      success: true,
      data: {
        features: features,
        combination_type: combinationType,
        complexity_score: complexityScore,
        complexity_level: complexityLevel,
        estimated_effort: estimatedEffort,
        tech_stack: techStack
      },
      message: 'Feature combination analysis completed'
    });
  } catch (error) {
    console.error('❌ Failed to analyze feature combination:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to analyze feature combination',
      message: error.message
    });
  }
});

module.exports = router;
