const TKGMigrationService = require('./tkg-migration-service');

/**
 * Automatic TKG Migration Service
 * Handles automatic migration of templates and features to Neo4j TKG
 */
class AutoTKGMigrationService {
  constructor() {
    this.migrationService = new TKGMigrationService();
    this.isRunning = false;
    this.lastMigrationTime = null;
  }

  /**
   * Initialize auto-migration on service startup
   */
  async initialize() {
    console.log('🚀 Initializing Auto TKG Migration Service...');
    
    try {
      // Run initial migration on startup
      await this.runStartupMigration();
      
      // Set up periodic migration checks
      this.setupPeriodicMigration();
      
      console.log('✅ Auto TKG Migration Service initialized');
    } catch (error) {
      console.error('❌ Failed to initialize Auto TKG Migration Service:', error.message);
    }
  }

  /**
   * Run migration on service startup
   */
  async runStartupMigration() {
    console.log('🔄 Running startup TKG migration...');
    
    try {
      // Step 1: Clean up any existing duplicates
      console.log('🧹 Cleaning up duplicate templates in TKG...');
      const cleanupResult = await this.migrationService.neo4j.cleanupDuplicates();
      if (cleanupResult.success) {
        console.log(`✅ TKG cleanup completed: removed ${cleanupResult.removedCount} duplicates`);
      } else {
        console.error('❌ TKG cleanup failed:', cleanupResult.error);
      }
      
      // Step 2: Run migration
      await this.migrationService.migrateAllTemplates();
      this.lastMigrationTime = new Date();
      console.log('✅ Startup TKG migration completed');
      
      // Step 3: Run automated comprehensive fix for TKG
      console.log('🔧 Running automated TKG comprehensive fix...');
      const tkgFixResult = await this.migrationService.neo4j.cleanupDuplicates();
      if (tkgFixResult.success) {
        console.log('✅ Automated TKG comprehensive fix completed');
      } else {
        console.error('❌ Automated TKG comprehensive fix failed:', tkgFixResult.error);
      }
    } catch (error) {
      console.error('❌ Startup TKG migration failed:', error.message);
      // Don't throw error, continue with service startup
    }
  }

  /**
   * Set up periodic migration checks
   */
  setupPeriodicMigration() {
    // DISABLED: Periodic migration was causing infinite loops
    // Check for new data every 5 minutes
    // setInterval(async () => {
    //   await this.checkAndMigrateNewData();
    // }, 5 * 60 * 1000); // 5 minutes

    console.log('⏰ Periodic TKG migration checks DISABLED to prevent infinite loops');
  }

  /**
   * Check for new data and migrate if needed
   */
  async checkAndMigrateNewData() {
    if (this.isRunning) {
      console.log('⏳ TKG migration already in progress, skipping...');
      return;
    }

    try {
      this.isRunning = true;
      
      // Check if there are new templates or features since last migration
      const hasNewData = await this.checkForNewData();
      
      if (hasNewData) {
        console.log('🔄 New data detected, running TKG migration...');
        await this.migrationService.migrateAllTemplates();
        this.lastMigrationTime = new Date();
        console.log('✅ Auto TKG migration completed');
      }
    } catch (error) {
      console.error('❌ Auto TKG migration failed:', error.message);
    } finally {
      this.isRunning = false;
    }
  }

  /**
   * Check if there's new data since last migration
   */
  async checkForNewData() {
    try {
      const database = require('../config/database');
      
      // Check for new templates
      const templatesQuery = this.lastMigrationTime 
        ? 'SELECT COUNT(*) as count FROM templates WHERE created_at > $1 OR updated_at > $1'
        : 'SELECT COUNT(*) as count FROM templates';
      
      const templatesParams = this.lastMigrationTime ? [this.lastMigrationTime] : [];
      const templatesResult = await database.query(templatesQuery, templatesParams);
      
      // Check for new features
      const featuresQuery = this.lastMigrationTime
        ? 'SELECT COUNT(*) as count FROM template_features WHERE created_at > $1 OR updated_at > $1'
        : 'SELECT COUNT(*) as count FROM template_features';
      
      const featuresParams = this.lastMigrationTime ? [this.lastMigrationTime] : [];
      const featuresResult = await database.query(featuresQuery, featuresParams);
      
      const newTemplates = parseInt(templatesResult.rows[0].count) || 0;
      const newFeatures = parseInt(featuresResult.rows[0].count) || 0;
      
      if (newTemplates > 0 || newFeatures > 0) {
        console.log(`📊 Found ${newTemplates} new templates and ${newFeatures} new features`);
        return true;
      }
      
      return false;
    } catch (error) {
      console.error('❌ Error checking for new data:', error.message);
      return false;
    }
  }

  /**
   * Trigger immediate migration (for webhook/API calls)
   */
  async triggerMigration() {
    console.log('🔄 Manual TKG migration triggered...');
    
    if (this.isRunning) {
      console.log('⏳ Migration already in progress, queuing...');
      return { success: false, message: 'Migration already in progress' };
    }

    try {
      this.isRunning = true;
      await this.migrationService.migrateAllTemplates();
      this.lastMigrationTime = new Date();
      
      console.log('✅ Manual TKG migration completed');
      return { success: true, message: 'Migration completed successfully' };
    } catch (error) {
      console.error('❌ Manual TKG migration failed:', error.message);
      return { success: false, message: error.message };
    } finally {
      this.isRunning = false;
    }
  }

  /**
   * Migrate specific template to TKG
   */
  async migrateTemplate(templateId) {
    console.log(`🔄 Migrating template ${templateId} to TKG...`);
    
    try {
      await this.migrationService.migrateTemplateToTKG(templateId);
      console.log(`✅ Template ${templateId} migrated to TKG`);
      return { success: true, message: 'Template migrated successfully' };
    } catch (error) {
      console.error(`❌ Failed to migrate template ${templateId}:`, error.message);
      return { success: false, message: error.message };
    }
  }

  /**
   * Get migration status
   */
  async getStatus() {
    try {
      const stats = await this.migrationService.getMigrationStats();
      return {
        success: true,
        data: {
          lastMigration: this.lastMigrationTime,
          isRunning: this.isRunning,
          stats: stats
        }
      };
    } catch (error) {
      return {
        success: false,
        error: error.message
      };
    }
  }

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

module.exports = AutoTKGMigrationService;
