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

/**
 * TESTS D'INTÉGRATION RAPIDES - COMBINAISONS ESSENTIELLES
 * Version optimisée des TI exhaustifs avec les combinaisons critiques
 */

// Reporter automatique pour génération de rapport
const reporter = new TestReporter();

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

const mockContent = {
  'Titre_H1': 'Test titre avec contenu générique nécessitant amélioration technique',
  'Introduction': 'Introduction générique avec vocabulaire basique à améliorer',
  'Contenu_Principal': 'Contenu principal avec termes génériques optimal et efficace nécessitant précision technique',
  'Conclusion': 'Conclusion basique qui nécessite enhancement professionnel'
};

// =========================================
// TESTS SELECTIVE ESSENTIELS (3 tests)
// =========================================


// Auto-Reporter Configuration
const autoReporter = new AutoReporter();

test('Fast TI: lightEnhancement (rapide)', { timeout: 30000 }, async () => {
  const testName = 'lightEnhancement (rapide)';
  const config = { stack: 'lightEnhancement', analysisMode: true, csvData: mockCsvData };

  reporter.startTest(testName, config);

  try {
    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.equal(result.stats.stackName, 'lightEnhancement', 'Stack correct');

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

    reporter.endTest(result);
  } catch (error) {
    reporter.endTest(null, error.message);
    throw error;
  }
});

test('Fast TI: standardEnhancement (complet)', { timeout: 60000 }, async () => {
  const testName = 'standardEnhancement (complet)';
  const config = { stack: 'standardEnhancement', analysisMode: true };

  reporter.startTest(testName, config);

  try {
    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');

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

    reporter.endTest(result);
  } catch (error) {
    reporter.endTest(null, error.message);
    throw error;
  }
});

test('Fast TI: fullEnhancement (maximum)', { timeout: 90000 }, 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');

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

// =========================================
// TESTS ADVERSARIAL ESSENTIELS (2 tests)
// =========================================

test('Fast TI: Adversarial general', { timeout: 45000 }, 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('Fast TI: Adversarial gptZero', { timeout: 45000 }, 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`);
});

// =========================================
// TESTS PIPELINE ESSENTIELS (2 tests)
// =========================================

test('Fast TI: Pipeline Standard → Adversarial', { timeout: 120000 }, 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 sur résultat
  const step2 = await applyAdversarialLayer(step1.content, {
    detectorTarget: 'general',
    method: 'enhancement',
    intensity: 0.7
  });

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

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

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

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

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

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

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

  console.log(`✅ Pipeline Full→GPTZero: 3 couches + anti-détection spécialisée`);
});

// =========================================
// TEST PERFORMANCE RAPIDE (1 test)
// =========================================

test('Fast TI: Performance Benchmark', { timeout: 90000 }, async () => {
  const { applyPredefinedStack } = requireCommonJS('selective-enhancement/SelectiveLayers');

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

  // Test light (rapide)
  const lightStart = Date.now();
  const lightResult = await applyPredefinedStack(mockContent, 'lightEnhancement', {
    csvData: mockCsvData,
    analysisMode: true
  });
  benchmark.stages.push({ name: 'light', duration: Date.now() - lightStart, modifications: lightResult.stats.totalModifications });

  // Test standard (complet)
  const standardStart = Date.now();
  const standardResult = await applyPredefinedStack(mockContent, 'standardEnhancement', {
    csvData: mockCsvData,
    analysisMode: true
  });
  benchmark.stages.push({ name: 'standard', duration: Date.now() - standardStart, modifications: standardResult.stats.totalModifications });

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

  assert.ok(lightResult?.content && standardResult?.content, 'Benchmark réussi');

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

// =========================================
// GÉNÉRATION AUTOMATIQUE DU RAPPORT
// =========================================

test.after(() => {
  // Génération automatique du rapport HTML détaillé
  reporter.generateReport();
});