import test from 'node:test';
import assert from 'node:assert';
import { requireCommonJS } from './_helpers/commonjs-bridge.js';
import { AutoReporter } from './reporters/AutoReporter.js';

/**
 * TESTS D'INTÉGRATION EXHAUSTIFS - COMBINAISONS MODULAIRES
 * Test toutes les combinaisons raisonnables du système modulaire
 */

// Configuration test commune
const mockCsvData = {
  mc0: 'plaque test intégration',
  t0: 'Test intégration modulaire complete',
  personality: {
    nom: 'Marc',
    style: 'technique',
    description: 'Expert technique pour tests'
  }
};

const mockContent = {
  'Titre_H1': 'Test titre intégration',
  'Introduction': 'Test introduction modulaire',
  'Contenu_Principal': 'Test contenu principal détaillé avec informations techniques',
  'Conclusion': 'Test conclusion qui encourage action'
};

// =========================================
// AUTO-REPORTER CONFIGURATION
// =========================================
const autoReporter = new AutoReporter();

// =========================================
// TESTS SELECTIVE STACKS COMPLETS
// =========================================

test('Integration: Selective lightEnhancement (1 couche)', { timeout: 30000 }, async () => {
  const { applyPredefinedStack } = requireCommonJS('selective-enhancement/SelectiveLayers');

  const result = await applyPredefinedStack(mockContent, 'lightEnhancement', {
    csvData: mockCsvData,
    analysisMode: true
  });

  assert.ok(result, 'Résultat lightEnhancement');
  assert.ok(result.content, 'Contenu généré');
  assert.ok(result.stats, 'Stats disponibles');
  assert.equal(result.stats.stackName, 'lightEnhancement', 'Stack correct');

  console.log(`✅ lightEnhancement: ${result.stats.totalModifications} modifications en ${result.stats.totalDuration}ms`);
});

test('Integration: Selective standardEnhancement (2 couches)', { timeout: 45000 }, async () => {
  const { applyPredefinedStack } = requireCommonJS('selective-enhancement/SelectiveLayers');

  const result = await applyPredefinedStack(mockContent, 'standardEnhancement', {
    csvData: mockCsvData,
    analysisMode: true
  });

  assert.ok(result, 'Résultat standardEnhancement');
  assert.ok(result.content, 'Contenu généré');
  assert.equal(result.stats.stackName, 'standardEnhancement', 'Stack correct');
  assert.ok(result.stats.layers.length >= 2, 'Au moins 2 couches executées');

  console.log(`✅ standardEnhancement: ${result.stats.layers.length} couches, ${result.stats.totalModifications} modifications`);
});

test('Integration: Selective fullEnhancement (3 couches)', { timeout: 60000 }, async () => {
  const { applyPredefinedStack } = requireCommonJS('selective-enhancement/SelectiveLayers');

  const result = await applyPredefinedStack(mockContent, 'fullEnhancement', {
    csvData: mockCsvData,
    analysisMode: true
  });

  assert.ok(result, 'Résultat fullEnhancement');
  assert.ok(result.content, 'Contenu généré');
  assert.equal(result.stats.stackName, 'fullEnhancement', 'Stack correct');
  assert.ok(result.stats.layers.length >= 3, 'Au moins 3 couches executées');

  console.log(`✅ fullEnhancement: ${result.stats.layers.length} couches, ${result.stats.totalModifications} modifications`);
});

test('Integration: Selective personalityFocus (style prioritaire)', { timeout: 45000 }, async () => {
  const { applyPredefinedStack } = requireCommonJS('selective-enhancement/SelectiveLayers');

  const result = await applyPredefinedStack(mockContent, 'personalityFocus', {
    csvData: mockCsvData,
    analysisMode: true
  });

  assert.ok(result, 'Résultat personalityFocus');
  assert.ok(result.content, 'Contenu généré');
  assert.equal(result.stats.stackName, 'personalityFocus', 'Stack correct');

  console.log(`✅ personalityFocus: ${result.stats.totalModifications} modifications personnalité`);
});

test('Integration: Selective fluidityFocus (transitions prioritaires)', { timeout: 60000 }, async () => {
  const { applyPredefinedStack } = requireCommonJS('selective-enhancement/SelectiveLayers');

  const result = await applyPredefinedStack(mockContent, 'fluidityFocus', {
    csvData: mockCsvData,
    analysisMode: true
  });

  assert.ok(result, 'Résultat fluidityFocus');
  assert.ok(result.content, 'Contenu généré');
  assert.equal(result.stats.stackName, 'fluidityFocus', 'Stack correct');

  console.log(`✅ fluidityFocus: ${result.stats.totalModifications} modifications fluidité`);
});

// =========================================
// TESTS ADVERSARIAL MODES COMPLETS
// =========================================

test('Integration: Adversarial general standard', { timeout: 30000 }, async () => {
  const { applyAdversarialLayer } = requireCommonJS('adversarial-generation/AdversarialCore');

  const result = await applyAdversarialLayer(mockContent, {
    detectorTarget: 'general',
    method: 'regeneration',
    intensity: 0.8
  });

  assert.ok(result, 'Résultat adversarial general');
  console.log(`✅ Adversarial general: ${Object.keys(result).length} éléments traités`);
});

test('Integration: Adversarial gptZero spécialisé', { timeout: 30000 }, async () => {
  const { applyAdversarialLayer } = requireCommonJS('adversarial-generation/AdversarialCore');

  const result = await applyAdversarialLayer(mockContent, {
    detectorTarget: 'gptZero',
    method: 'regeneration',
    intensity: 1.0
  });

  assert.ok(result, 'Résultat adversarial gptZero');
  console.log(`✅ Adversarial gptZero: anti-détection spécialisée`);
});

test('Integration: Adversarial originality spécialisé', { timeout: 30000 }, async () => {
  const { applyAdversarialLayer } = requireCommonJS('adversarial-generation/AdversarialCore');

  const result = await applyAdversarialLayer(mockContent, {
    detectorTarget: 'originality',
    method: 'hybrid',
    intensity: 1.1
  });

  assert.ok(result, 'Résultat adversarial originality');
  console.log(`✅ Adversarial originality: méthode hybrid`);
});

test('Integration: Adversarial enhancement method', { timeout: 30000 }, async () => {
  const { applyAdversarialLayer } = requireCommonJS('adversarial-generation/AdversarialCore');

  const result = await applyAdversarialLayer(mockContent, {
    detectorTarget: 'general',
    method: 'enhancement',
    intensity: 0.6
  });

  assert.ok(result, 'Résultat adversarial enhancement');
  console.log(`✅ Adversarial enhancement: méthode douce`);
});

// =========================================
// TESTS COMBINAISONS PIPELINES
// =========================================

test('Integration: Pipeline Light → Adversarial', { timeout: 60000 }, async () => {
  const { applyPredefinedStack } = requireCommonJS('selective-enhancement/SelectiveLayers');
  const { applyAdversarialLayer } = requireCommonJS('adversarial-generation/AdversarialCore');

  // Étape 1: Selective lightEnhancement
  const step1 = await applyPredefinedStack(mockContent, 'lightEnhancement', {
    csvData: mockCsvData,
    analysisMode: true
  });

  assert.ok(step1?.content, 'Étape 1 selective réussie');

  // Étape 2: Adversarial sur résultat
  const step2 = await applyAdversarialLayer(step1.content, {
    detectorTarget: 'general',
    method: 'enhancement',
    intensity: 0.5
  });

  assert.ok(step2, 'Étape 2 adversarial réussie');

  console.log(`✅ Pipeline Light→Adversarial: ${step1.stats.totalModifications} + adversarial`);
});

test('Integration: Pipeline Standard → Adversarial Intense', { timeout: 90000 }, async () => {
  const { applyPredefinedStack } = requireCommonJS('selective-enhancement/SelectiveLayers');
  const { applyAdversarialLayer } = requireCommonJS('adversarial-generation/AdversarialCore');

  // Étape 1: Selective standardEnhancement
  const step1 = await applyPredefinedStack(mockContent, 'standardEnhancement', {
    csvData: mockCsvData,
    analysisMode: true
  });

  assert.ok(step1?.content, 'Étape 1 standard réussie');

  // Étape 2: Adversarial intense
  const step2 = await applyAdversarialLayer(step1.content, {
    detectorTarget: 'gptZero',
    method: 'regeneration',
    intensity: 1.0
  });

  assert.ok(step2, 'Étape 2 adversarial intense réussie');

  console.log(`✅ Pipeline Standard→AdversarialIntense: 2 couches + gptZero`);
});

test('Integration: Pipeline Full → Multi-Adversarial', { timeout: 120000 }, async () => {
  const { applyPredefinedStack } = requireCommonJS('selective-enhancement/SelectiveLayers');
  const { applyAdversarialLayer } = requireCommonJS('adversarial-generation/AdversarialCore');

  // Étape 1: Selective fullEnhancement (3 couches)
  const step1 = await applyPredefinedStack(mockContent, 'fullEnhancement', {
    csvData: mockCsvData,
    analysisMode: true
  });

  assert.ok(step1?.content, 'Étape 1 full réussie');

  // Étape 2: Premier adversarial general
  const step2 = await applyAdversarialLayer(step1.content, {
    detectorTarget: 'general',
    method: 'enhancement',
    intensity: 0.7
  });

  assert.ok(step2, 'Étape 2 adversarial general réussie');

  // Étape 3: Second adversarial spécialisé
  const step3 = await applyAdversarialLayer(step2, {
    detectorTarget: 'originality',
    method: 'hybrid',
    intensity: 0.9
  });

  assert.ok(step3, 'Étape 3 adversarial spécialisé réussie');

  console.log(`✅ Pipeline Full→Multi-Adversarial: 3 couches + 2 adversarial`);
});

// =========================================
// TESTS COMBINAISONS AVANCÉES
// =========================================

test('Integration: Personality → GPTZero Pipeline', { timeout: 75000 }, async () => {
  const { applyPredefinedStack } = requireCommonJS('selective-enhancement/SelectiveLayers');
  const { applyAdversarialLayer } = requireCommonJS('adversarial-generation/AdversarialCore');

  // Étape 1: Focus personnalité
  const step1 = await applyPredefinedStack(mockContent, 'personalityFocus', {
    csvData: mockCsvData,
    analysisMode: true
  });

  // Étape 2: Anti-GPTZero spécialisé
  const step2 = await applyAdversarialLayer(step1.content, {
    detectorTarget: 'gptZero',
    method: 'regeneration',
    intensity: 1.2
  });

  assert.ok(step1?.content && step2, 'Pipeline personality→gptZero réussi');
  console.log(`✅ Pipeline Personality→GPTZero: style + anti-détection`);
});

test('Integration: Fluidity → Originality Pipeline', { timeout: 75000 }, async () => {
  const { applyPredefinedStack } = requireCommonJS('selective-enhancement/SelectiveLayers');
  const { applyAdversarialLayer } = requireCommonJS('adversarial-generation/AdversarialCore');

  // Étape 1: Focus fluidité
  const step1 = await applyPredefinedStack(mockContent, 'fluidityFocus', {
    csvData: mockCsvData,
    analysisMode: true
  });

  // Étape 2: Anti-Originality
  const step2 = await applyAdversarialLayer(step1.content, {
    detectorTarget: 'originality',
    method: 'hybrid',
    intensity: 1.0
  });

  assert.ok(step1?.content && step2, 'Pipeline fluidity→originality réussi');
  console.log(`✅ Pipeline Fluidity→Originality: transitions + hybrid`);
});

// =========================================
// TESTS INTENSITÉS VARIABLES
// =========================================

test('Integration: Selective Intensities Test', { timeout: 90000 }, async () => {
  const { applyPredefinedStack } = requireCommonJS('selective-enhancement/SelectiveLayers');

  const intensities = [0.5, 0.8, 1.0, 1.2];
  const results = [];

  for (const intensity of intensities) {
    const result = await applyPredefinedStack(mockContent, 'standardEnhancement', {
      csvData: mockCsvData,
      analysisMode: true,
      globalIntensity: intensity
    });

    results.push({
      intensity,
      modifications: result.stats.totalModifications,
      duration: result.stats.totalDuration
    });
  }

  assert.ok(results.length === 4, 'Tous les tests intensité réussis');
  console.log(`✅ Tests intensités:`, results.map(r => `${r.intensity}→${r.modifications}mod`).join(', '));
});

test('Integration: Adversarial Intensities Test', { timeout: 90000 }, async () => {
  const { applyAdversarialLayer } = requireCommonJS('adversarial-generation/AdversarialCore');

  const configs = [
    { intensity: 0.3, method: 'enhancement' },
    { intensity: 0.7, method: 'regeneration' },
    { intensity: 1.0, method: 'hybrid' },
    { intensity: 1.3, method: 'regeneration' }
  ];

  const results = [];

  for (const config of configs) {
    const result = await applyAdversarialLayer(mockContent, {
      detectorTarget: 'general',
      ...config
    });

    results.push({
      config: `${config.intensity}/${config.method}`,
      success: !!result
    });
  }

  assert.ok(results.length === 4, 'Tous les tests adversarial réussis');
  console.log(`✅ Tests adversarial:`, results.map(r => r.config).join(', '));
});

// =========================================
// TEST PERFORMANCE PIPELINE
// =========================================

test('Integration: Performance Benchmark Pipeline', { timeout: 120000 }, async () => {
  const { applyPredefinedStack } = requireCommonJS('selective-enhancement/SelectiveLayers');
  const { applyAdversarialLayer } = requireCommonJS('adversarial-generation/AdversarialCore');

  const benchmark = {
    start: Date.now(),
    stages: []
  };

  // Stage 1: Light (rapide)
  const stage1Start = Date.now();
  const stage1 = await applyPredefinedStack(mockContent, 'lightEnhancement', {
    csvData: mockCsvData,
    analysisMode: true
  });
  benchmark.stages.push({ name: 'light', duration: Date.now() - stage1Start });

  // Stage 2: Standard (moyen)
  const stage2Start = Date.now();
  const stage2 = await applyPredefinedStack(stage1.content, 'standardEnhancement', {
    csvData: mockCsvData,
    analysisMode: true
  });
  benchmark.stages.push({ name: 'standard', duration: Date.now() - stage2Start });

  // Stage 3: Adversarial (variable)
  const stage3Start = Date.now();
  const stage3 = await applyAdversarialLayer(stage2.content, {
    detectorTarget: 'general',
    method: 'enhancement',
    intensity: 0.8
  });
  benchmark.stages.push({ name: 'adversarial', duration: Date.now() - stage3Start });

  benchmark.total = Date.now() - benchmark.start;

  assert.ok(stage1?.content && stage2?.content && stage3, 'Pipeline benchmark réussi');

  console.log(`✅ Benchmark Pipeline:`, benchmark.stages.map(s => `${s.name}:${s.duration}ms`).join(', '));
  console.log(`   📊 Total: ${benchmark.total}ms`);
});