// ========================================
// BATCH PROCESSOR - REFACTORISÉ
// Responsabilité: Traitement batch interface web avec configuration flexible
// ========================================

const { QueueProcessor } = require('../shared/QueueProcessor');
const { logSh } = require('../ErrorReporting');
const path = require('path');

/**
 * BATCH PROCESSOR
 * Spécialisé pour interface web avec configuration modulaire flexible
 */
class BatchProcessor extends QueueProcessor {

  constructor() {
    super({
      name: 'BatchProcessor',
      configPath: path.join(__dirname, '../../config/batch-config.json'),
      statusPath: path.join(__dirname, '../../config/batch-status.json'),
      queuePath: path.join(__dirname, '../../config/batch-queue.json'),
      config: {
        selective: 'standardEnhancement',
        adversarial: 'light',
        humanSimulation: 'none',
        patternBreaking: 'none',
        intensity: 1.0,
        rowRange: { start: 2, end: 10 },
        saveIntermediateSteps: false,
        maxRetries: 3,
        delayBetweenItems: 1000
      }
    });

    // Initialisation différée pour éviter le blocage au démarrage serveur
    // this.initialize().catch(error => {
    //   logSh(`❌ Erreur initialisation BatchProcessor: ${error.message}`, 'ERROR');
    // });
  }

  /**
   * Alias pour compatibilité - Initialise les fichiers
   */
  async initializeFiles() {
    return await super.initializeFiles();
  }

  /**
   * Alias pour compatibilité - Initialise le processeur
   */
  async initializeProcessor() {
    return await this.initialize();
  }

  /**
   * Construit la configuration spécifique BatchProcessor
   */
  buildRowConfig(rowNumber, data = null) {
    return {
      rowNumber,
      source: 'batch_processor',
      selectiveStack: this.config.selective,
      adversarialMode: this.config.adversarial,
      humanSimulationMode: this.config.humanSimulation,
      patternBreakingMode: this.config.patternBreaking,
      intensity: this.config.intensity,
      saveIntermediateSteps: this.config.saveIntermediateSteps
    };
  }

  /**
   * API spécifique BatchProcessor - Configuration
   */
  async updateConfiguration(newConfig) {
    try {
      // Validation basique
      const requiredFields = ['selective', 'adversarial', 'humanSimulation', 'patternBreaking', 'intensity', 'rowRange'];
      for (const field of requiredFields) {
        if (!(field in newConfig)) {
          throw new Error(`Champ requis manquant: ${field}`);
        }
      }

      // Validation intensité
      if (newConfig.intensity < 0.5 || newConfig.intensity > 1.5) {
        throw new Error('Intensité doit être entre 0.5 et 1.5');
      }

      // Validation rowRange
      if (!newConfig.rowRange.start || !newConfig.rowRange.end || newConfig.rowRange.start >= newConfig.rowRange.end) {
        throw new Error('Plage de lignes invalide');
      }

      // Mettre à jour la configuration
      this.config = { ...this.config, ...newConfig };
      this.config.lastUpdated = new Date().toISOString();

      // Sauvegarder
      if (this.configPath) {
        const fs = require('fs').promises;
        await fs.writeFile(this.configPath, JSON.stringify(this.config, null, 2));
      }

      logSh(`✅ Configuration BatchProcessor mise à jour: ${JSON.stringify(newConfig)}`, 'INFO');

      return { success: true, config: this.config };

    } catch (error) {
      logSh(`❌ Erreur mise à jour configuration: ${error.message}`, 'ERROR');
      throw error;
    }
  }

  /**
   * Retourne les options disponibles
   */
  getAvailableOptions() {
    return {
      selective: ['lightEnhancement', 'standardEnhancement', 'fullEnhancement', 'personalityFocus', 'fluidityFocus'],
      adversarial: ['none', 'light', 'standard', 'heavy', 'adaptive'],
      humanSimulation: ['none', 'lightSimulation', 'personalityFocus', 'adaptive'],
      patternBreaking: ['none', 'syntaxFocus', 'connectorsFocus', 'adaptive'],
      intensityRange: { min: 0.5, max: 1.5, step: 0.1 }
    };
  }

  /**
   * Status étendu avec options disponibles
   */
  getExtendedStatus() {
    const baseStatus = this.getStatus();
    return {
      ...baseStatus,
      availableOptions: this.getAvailableOptions(),
      mode: 'BATCH_MANUAL',
      timestamp: new Date().toISOString()
    };
  }
}

// ============= EXPORTS =============
module.exports = { BatchProcessor };