/**
 * Validate Generator Test Coverage
 *
 * Ensures all enhanced generators have both unit tests and E2E tests.
 * This script enforces consistent test coverage across all generators.
 */

import * as fs from 'fs';
import * as path from 'path';

interface GeneratorTestStatus {
  generator: string;
  hasUnitTests: boolean;
  hasE2ETests: boolean;
  unitTestPath?: string;
  e2eTestPath?: string;
}

const ENHANCED_GENERATORS_DIR = path.join(__dirname, '../src/generators');
const E2E_DIR = path.join(__dirname, '../src/e2e');

// List of enhanced generators that should have full test coverage
const ENHANCED_GENERATORS = [
  'enhanced-testing-generator',
  'enhanced-monitoring-generator',
  'enhanced-security-generator', // To be implemented
];

function findEnhancedGenerators(): string[] {
  const generators: string[] = [];

  // Search for enhanced generators in all subdirectories
  const searchDir = (dir: string) => {
    const entries = fs.readdirSync(dir, { withFileTypes: true });

    for (const entry of entries) {
      if (entry.isDirectory()) {
        searchDir(path.join(dir, entry.name));
      } else if (entry.isFile() && entry.name.startsWith('enhanced-') && entry.name.endsWith('-generator.ts')) {
        // Exclude test files
        if (!entry.name.includes('.test.') && !entry.name.includes('.spec.')) {
          const generatorName = entry.name.replace('.ts', '');
          generators.push(generatorName);
        }
      }
    }
  };

  searchDir(ENHANCED_GENERATORS_DIR);
  return generators;
}

function checkTestCoverage(): GeneratorTestStatus[] {
  const generators = findEnhancedGenerators();
  const results: GeneratorTestStatus[] = [];

  for (const generator of generators) {
    const generatorBase = generator.replace('enhanced-', '').replace('-generator', '');

    // Check for unit tests
    const unitTestPath = path.join(ENHANCED_GENERATORS_DIR, '**', `${generator}.test.ts`);
    const hasUnitTests = findFileRecursive(ENHANCED_GENERATORS_DIR, `${generator}.test.ts`) !== null;
    const unitTestFile = findFileRecursive(ENHANCED_GENERATORS_DIR, `${generator}.test.ts`);

    // Check for E2E tests
    const e2eTestPath = path.join(E2E_DIR, `enhanced-${generatorBase}.e2e.test.ts`);
    const hasE2ETests = fs.existsSync(e2eTestPath);

    results.push({
      generator,
      hasUnitTests,
      hasE2ETests,
      unitTestPath: unitTestFile || undefined,
      e2eTestPath: hasE2ETests ? e2eTestPath : undefined,
    });
  }

  return results;
}

function findFileRecursive(dir: string, filename: string): string | null {
  const entries = fs.readdirSync(dir, { withFileTypes: true });

  for (const entry of entries) {
    const fullPath = path.join(dir, entry.name);

    if (entry.isDirectory()) {
      const found = findFileRecursive(fullPath, filename);
      if (found) return found;
    } else if (entry.name === filename) {
      return fullPath;
    }
  }

  return null;
}

function validateCoverage(): { passed: boolean; message: string } {
  const results = checkTestCoverage();

  if (results.length === 0) {
    return {
      passed: true,
      message: '✓ No enhanced generators found (none to validate)',
    };
  }

  const missingTests: string[] = [];
  let totalTests = 0;
  let passedTests = 0;

  console.log('\n📊 Enhanced Generator Test Coverage Report\n');
  console.log('Generator'.padEnd(40) + 'Unit Tests'.padEnd(15) + 'E2E Tests');
  console.log('='.repeat(70));

  for (const result of results) {
    const unitStatus = result.hasUnitTests ? '✓' : '✗';
    const e2eStatus = result.hasE2ETests ? '✓' : '✗';

    console.log(
      result.generator.padEnd(40) +
      unitStatus.padEnd(15) +
      e2eStatus
    );

    totalTests += 2; // Unit + E2E
    if (result.hasUnitTests) passedTests++;
    if (result.hasE2ETests) passedTests++;

    if (!result.hasUnitTests) {
      missingTests.push(`${result.generator}: Missing unit tests`);
    }
    if (!result.hasE2ETests) {
      missingTests.push(`${result.generator}: Missing E2E tests`);
    }
  }

  console.log('='.repeat(70));
  console.log(`\nCoverage: ${passedTests}/${totalTests} (${Math.round(passedTests / totalTests * 100)}%)\n`);

  if (missingTests.length > 0) {
    console.log('❌ Test Coverage Issues:\n');
    missingTests.forEach(msg => console.log(`  • ${msg}`));
    console.log('\n');

    return {
      passed: false,
      message: `Missing ${missingTests.length} required test file(s)`,
    };
  }

  console.log('✅ All enhanced generators have complete test coverage!\n');

  return {
    passed: true,
    message: 'All enhanced generators have unit and E2E tests',
  };
}

// Main execution
if (require.main === module) {
  const result = validateCoverage();

  if (!result.passed) {
    console.error(`\n❌ Validation failed: ${result.message}\n`);
    console.log('Required: Each enhanced generator must have:');
    console.log('  1. Unit tests: <generator-name>.test.ts in the same directory');
    console.log('  2. E2E tests: enhanced-<name>.e2e.test.ts in src/e2e/\n');
    process.exit(1);
  }

  process.exit(0);
}

export { validateCoverage, checkTestCoverage };
