#!/usr/bin/env node

/**
 * 测试修复脚本
 * 验证所有修复是否正确
 */

const fs = require('fs');
const path = require('path');

class FixValidator {
  constructor() {
    this.errors = [];
    this.warnings = [];
    this.passed = [];
  }

  /**
   * 运行所有验证
   */
  async run() {
    console.log('🧪 开始验证修复...\n');

    // 验证1: command-generator.js 导入路径
    console.log('📝 验证1: command-generator.js 导入路径修复');
    this.validateCommandGeneratorImport();

    // 验证2: BaseGenerator 存在性
    console.log('\n📝 验证2: BaseGenerator 基类存在性');
    this.validateBaseGenerator();

    // 验证3: entity-generator.js 继承 BaseGenerator
    console.log('\n📝 验证3: entity-generator.js 继承 BaseGenerator');
    this.validateEntityGeneratorInheritance();

    // 验证4: command-generator.js 继承 BaseGenerator
    console.log('\n📝 验证4: command-generator.js 继承 BaseGenerator');
    this.validateCommandGeneratorInheritance();

    // 验证5: Quality Gate 工具存在
    console.log('\n📝 验证5: Quality Gate 工具存在');
    this.validateQualityGate();

    // 验证6: migration-coordinator.js 集成 Quality Gate
    console.log('\n📝 验证6: migration-coordinator.js 集成 Quality Gate');
    this.validateCoordinatorQualityGate();

    // 验证7: README.md 文档更新
    console.log('\n📝 验证7: README.md 文档更新');
    this.validateReadmeUpdate();

    // 输出验证结果
    this.printResults();
  }

  /**
   * 验证 command-generator.js 导入路径
   */
  validateCommandGeneratorImport() {
    const filePath = path.join(__dirname, 'generators/command-generator.js');
    const content = fs.readFileSync(filePath, 'utf8');

    // 检查错误的导入
    if (content.includes("@wwjCore/exceptions/Customexceptions")) {
      this.errors.push('command-generator.js 仍使用错误的导入路径 @wwjCore/exceptions/Customexceptions');
      console.log('   ❌ 仍使用错误的导入路径');
    } else if (content.includes("@wwjCommon/exceptions/business.exception")) {
      this.passed.push('command-generator.js 使用正确的导入路径');
      console.log('   ✅ 使用正确的导入路径 @wwjCommon/exceptions/business.exception');
    } else {
      this.warnings.push('command-generator.js 未找到 BusinessException 导入');
      console.log('   ⚠️  未找到 BusinessException 导入');
    }
  }

  /**
   * 验证 BaseGenerator 存在
   */
  validateBaseGenerator() {
    const filePath = path.join(__dirname, 'generators/base-generator.js');
    
    if (!fs.existsSync(filePath)) {
      this.errors.push('base-generator.js 不存在');
      console.log('   ❌ base-generator.js 不存在');
      return;
    }

    const content = fs.readFileSync(filePath, 'utf8');

    // 检查关键方法
    const requiredMethods = ['writeFile', 'ensureDir', 'readFile', 'printStats'];
    let allMethodsPresent = true;

    for (const method of requiredMethods) {
      if (!content.includes(`${method}(`)) {
        this.errors.push(`base-generator.js 缺少方法: ${method}`);
        allMethodsPresent = false;
      }
    }

    if (allMethodsPresent) {
      this.passed.push('BaseGenerator 包含所有必需方法');
      console.log('   ✅ 包含所有必需方法');
    } else {
      console.log('   ❌ 缺少部分方法');
    }

    // 检查 dry-run 支持
    if (content.includes('this.dryRun')) {
      this.passed.push('BaseGenerator 支持 dry-run 模式');
      console.log('   ✅ 支持 dry-run 模式');
    } else {
      this.errors.push('BaseGenerator 不支持 dry-run 模式');
      console.log('   ❌ 不支持 dry-run 模式');
    }
  }

  /**
   * 验证 entity-generator.js 继承
   */
  validateEntityGeneratorInheritance() {
    const filePath = path.join(__dirname, 'generators/entity-generator.js');
    const content = fs.readFileSync(filePath, 'utf8');

    if (content.includes("extends BaseGenerator")) {
      this.passed.push('entity-generator.js 继承 BaseGenerator');
      console.log('   ✅ 继承 BaseGenerator');
    } else {
      this.errors.push('entity-generator.js 未继承 BaseGenerator');
      console.log('   ❌ 未继承 BaseGenerator');
    }

    if (content.includes("require('./base-generator')")) {
      this.passed.push('entity-generator.js 导入 BaseGenerator');
      console.log('   ✅ 导入 BaseGenerator');
    } else {
      this.errors.push('entity-generator.js 未导入 BaseGenerator');
      console.log('   ❌ 未导入 BaseGenerator');
    }

    if (content.includes("this.writeFile(")) {
      this.passed.push('entity-generator.js 使用 BaseGenerator.writeFile');
      console.log('   ✅ 使用 BaseGenerator.writeFile');
    } else {
      this.warnings.push('entity-generator.js 可能未使用 BaseGenerator.writeFile');
      console.log('   ⚠️  可能未使用 BaseGenerator.writeFile');
    }
  }

  /**
   * 验证 command-generator.js 继承
   */
  validateCommandGeneratorInheritance() {
    const filePath = path.join(__dirname, 'generators/command-generator.js');
    const content = fs.readFileSync(filePath, 'utf8');

    if (content.includes("extends BaseGenerator")) {
      this.passed.push('command-generator.js 继承 BaseGenerator');
      console.log('   ✅ 继承 BaseGenerator');
    } else {
      this.errors.push('command-generator.js 未继承 BaseGenerator');
      console.log('   ❌ 未继承 BaseGenerator');
    }

    if (content.includes("this.writeFile(")) {
      this.passed.push('command-generator.js 使用 BaseGenerator.writeFile');
      console.log('   ✅ 使用 BaseGenerator.writeFile');
    } else {
      this.warnings.push('command-generator.js 可能未使用 BaseGenerator.writeFile');
      console.log('   ⚠️  可能未使用 BaseGenerator.writeFile');
    }
  }

  /**
   * 验证 Quality Gate 工具
   */
  validateQualityGate() {
    const filePath = path.join(__dirname, 'generators/quality-gate.js');
    
    if (!fs.existsSync(filePath)) {
      this.errors.push('quality-gate.js 不存在');
      console.log('   ❌ quality-gate.js 不存在');
      return;
    }

    const content = fs.readFileSync(filePath, 'utf8');

    // 检查关键方法
    const requiredMethods = ['checkTypeScript', 'checkESLint', 'run', 'printStats'];
    let allMethodsPresent = true;

    for (const method of requiredMethods) {
      if (!content.includes(`${method}(`)) {
        this.errors.push(`quality-gate.js 缺少方法: ${method}`);
        allMethodsPresent = false;
      }
    }

    if (allMethodsPresent) {
      this.passed.push('Quality Gate 包含所有必需方法');
      console.log('   ✅ 包含所有必需方法');
    } else {
      console.log('   ❌ 缺少部分方法');
    }
  }

  /**
   * 验证 migration-coordinator.js 集成
   */
  validateCoordinatorQualityGate() {
    const filePath = path.join(__dirname, 'migration-coordinator.js');
    const content = fs.readFileSync(filePath, 'utf8');

    if (content.includes("require('./generators/quality-gate')")) {
      this.passed.push('migration-coordinator.js 导入 QualityGate');
      console.log('   ✅ 导入 QualityGate');
    } else {
      this.errors.push('migration-coordinator.js 未导入 QualityGate');
      console.log('   ❌ 未导入 QualityGate');
    }

    if (content.includes("runQualityGate")) {
      this.passed.push('migration-coordinator.js 包含 runQualityGate 方法');
      console.log('   ✅ 包含 runQualityGate 方法');
    } else {
      this.errors.push('migration-coordinator.js 未包含 runQualityGate 方法');
      console.log('   ❌ 未包含 runQualityGate 方法');
    }

    if (content.includes("await this.runQualityGate()")) {
      this.passed.push('migration-coordinator.js 调用 runQualityGate');
      console.log('   ✅ 在流程中调用 runQualityGate');
    } else {
      this.errors.push('migration-coordinator.js 未在流程中调用 runQualityGate');
      console.log('   ❌ 未在流程中调用 runQualityGate');
    }
  }

  /**
   * 验证 README.md 更新
   */
  validateReadmeUpdate() {
    const filePath = path.join(__dirname, 'README.md');
    const content = fs.readFileSync(filePath, 'utf8');

    if (content.includes('dry-run') || content.includes('DRY_RUN')) {
      this.passed.push('README.md 包含 dry-run 使用说明');
      console.log('   ✅ 包含 dry-run 使用说明');
    } else {
      this.warnings.push('README.md 缺少 dry-run 使用说明');
      console.log('   ⚠️  缺少 dry-run 使用说明');
    }

    if (content.includes('quality-gate') || content.includes('Quality Gate')) {
      this.passed.push('README.md 包含 Quality Gate 说明');
      console.log('   ✅ 包含 Quality Gate 说明');
    } else {
      this.warnings.push('README.md 缺少 Quality Gate 说明');
      console.log('   ⚠️  缺少 Quality Gate 说明');
    }

    if (content.includes('base-generator')) {
      this.passed.push('README.md 包含 BaseGenerator 说明');
      console.log('   ✅ 包含 BaseGenerator 说明');
    } else {
      this.warnings.push('README.md 缺少 BaseGenerator 说明');
      console.log('   ⚠️  缺少 BaseGenerator 说明');
    }
  }

  /**
   * 输出验证结果
   */
  printResults() {
    console.log('\n\n📊 验证结果汇总');
    console.log('='.repeat(60));
    
    console.log(`\n✅ 通过项 (${this.passed.length}):`);
    this.passed.forEach(item => console.log(`   - ${item}`));

    if (this.warnings.length > 0) {
      console.log(`\n⚠️  警告项 (${this.warnings.length}):`);
      this.warnings.forEach(item => console.log(`   - ${item}`));
    }

    if (this.errors.length > 0) {
      console.log(`\n❌ 错误项 (${this.errors.length}):`);
      this.errors.forEach(item => console.log(`   - ${item}`));
    }

    console.log('\n' + '='.repeat(60));

    const totalChecks = this.passed.length + this.warnings.length + this.errors.length;
    const successRate = totalChecks > 0 
      ? ((this.passed.length / totalChecks) * 100).toFixed(2) 
      : '0.00';

    console.log(`📈 成功率: ${successRate}% (${this.passed.length}/${totalChecks})`);

    if (this.errors.length === 0) {
      console.log('\n🎉 所有必需检查已通过！');
      return true;
    } else {
      console.log(`\n💔 发现 ${this.errors.length} 个错误，需要修复`);
      return false;
    }
  }
}

// 运行验证
if (require.main === module) {
  const validator = new FixValidator();
  validator.run().then(passed => {
    process.exit(passed ? 0 : 1);
  });
}

module.exports = FixValidator;

