/**
 * 上下文感知转换器
 * 为AI自动生成打下基石
 */

class ContextAwareConverter {
  constructor() {
    this.contextPatterns = {
      // 文件类型模式
      fileTypes: {
        service: {
          patterns: [/Service\.php$/, /class\s+\w+Service/],
          strategies: ['service_injection', 'repository_pattern', 'business_logic']
        },
        controller: {
          patterns: [/Controller\.php$/, /class\s+\w+Controller/],
          strategies: ['http_decorators', 'dto_validation', 'response_formatting']
        },
        entity: {
          patterns: [/\.php$/, /class\s+\w+(?!Service|Controller)/],
          strategies: ['typeorm_decorators', 'property_mapping', 'relationship_mapping']
        },
        dto: {
          patterns: [/Dto\.php$/, /class\s+\w+Dto/],
          strategies: ['validation_decorators', 'property_types', 'serialization']
        }
      },
      
      // 业务领域模式
      businessDomains: {
        user: {
          patterns: [/User/, /Auth/, /Login/],
          strategies: ['jwt_auth', 'role_based_access', 'user_validation']
        },
        payment: {
          patterns: [/Pay/, /Order/, /Transaction/],
          strategies: ['payment_processing', 'order_management', 'transaction_logging']
        },
        content: {
          patterns: [/Content/, /Article/, /Post/],
          strategies: ['content_management', 'seo_optimization', 'media_handling']
        },
        system: {
          patterns: [/System/, /Config/, /Setting/],
          strategies: ['configuration_management', 'system_monitoring', 'admin_functions']
        }
      },
      
      // 代码模式
      codePatterns: {
        crud: {
          patterns: [/create/, /read/, /update/, /delete/],
          strategies: ['repository_methods', 'validation_rules', 'error_handling']
        },
        api: {
          patterns: [/get/, /post/, /put/, /delete/],
          strategies: ['http_methods', 'route_decorators', 'request_validation']
        },
        validation: {
          patterns: [/validate/, /check/, /verify/],
          strategies: ['validation_pipes', 'custom_validators', 'error_messages']
        },
        cache: {
          patterns: [/cache/, /redis/, /memcache/],
          strategies: ['cache_decorators', 'cache_keys', 'expiration_handling']
        }
      }
    };
    
    this.conversionStrategies = {
      service_injection: this.applyServiceInjection.bind(this),
      repository_pattern: this.applyRepositoryPattern.bind(this),
      business_logic: this.applyBusinessLogic.bind(this),
      http_decorators: this.applyHttpDecorators.bind(this),
      dto_validation: this.applyDtoValidation.bind(this),
      response_formatting: this.applyResponseFormatting.bind(this),
      typeorm_decorators: this.applyTypeOrmDecorators.bind(this),
      property_mapping: this.applyPropertyMapping.bind(this),
      relationship_mapping: this.applyRelationshipMapping.bind(this),
      validation_decorators: this.applyValidationDecorators.bind(this),
      property_types: this.applyPropertyTypes.bind(this),
      serialization: this.applySerialization.bind(this),
      jwt_auth: this.applyJwtAuth.bind(this),
      role_based_access: this.applyRoleBasedAccess.bind(this),
      user_validation: this.applyUserValidation.bind(this),
      payment_processing: this.applyPaymentProcessing.bind(this),
      order_management: this.applyOrderManagement.bind(this),
      transaction_logging: this.applyTransactionLogging.bind(this),
      content_management: this.applyContentManagement.bind(this),
      seo_optimization: this.applySeoOptimization.bind(this),
      media_handling: this.applyMediaHandling.bind(this),
      configuration_management: this.applyConfigurationManagement.bind(this),
      system_monitoring: this.applySystemMonitoring.bind(this),
      admin_functions: this.applyAdminFunctions.bind(this),
      repository_methods: this.applyRepositoryMethods.bind(this),
      validation_rules: this.applyValidationRules.bind(this),
      error_handling: this.applyErrorHandling.bind(this),
      http_methods: this.applyHttpMethods.bind(this),
      route_decorators: this.applyRouteDecorators.bind(this),
      request_validation: this.applyRequestValidation.bind(this),
      validation_pipes: this.applyValidationPipes.bind(this),
      custom_validators: this.applyCustomValidators.bind(this),
      error_messages: this.applyErrorMessages.bind(this),
      cache_decorators: this.applyCacheDecorators.bind(this),
      cache_keys: this.applyCacheKeys.bind(this),
      expiration_handling: this.applyExpirationHandling.bind(this)
    };
  }
  
  /**
   * 分析代码上下文
   */
  analyzeContext(filePath, className, content) {
    const context = {
      filePath,
      className,
      fileType: this.detectFileType(filePath, className, content),
      businessDomain: this.detectBusinessDomain(content),
      codePatterns: this.detectCodePatterns(content),
      strategies: [],
      imports: [],
      decorators: [],
      methods: [],
      properties: []
    };
    
    // 根据检测到的模式选择转换策略
    context.strategies = this.selectStrategies(context);
    
    // 分析代码结构
    this.analyzeCodeStructure(content, context);
    
    return context;
  }
  
  /**
   * 检测文件类型
   */
  detectFileType(filePath, className, content) {
    for (const [type, config] of Object.entries(this.contextPatterns.fileTypes)) {
      for (const pattern of config.patterns) {
        if (pattern.test(filePath) || pattern.test(className) || pattern.test(content)) {
          return type;
        }
      }
    }
    return 'unknown';
  }
  
  /**
   * 检测业务领域
   */
  detectBusinessDomain(content) {
    for (const [domain, config] of Object.entries(this.contextPatterns.businessDomains)) {
      for (const pattern of config.patterns) {
        if (pattern.test(content)) {
          return domain;
        }
      }
    }
    return 'general';
  }
  
  /**
   * 检测代码模式
   */
  detectCodePatterns(content) {
    const patterns = [];
    
    for (const [pattern, config] of Object.entries(this.contextPatterns.codePatterns)) {
      for (const regex of config.patterns) {
        if (regex.test(content)) {
          patterns.push(pattern);
          break;
        }
      }
    }
    
    return patterns;
  }
  
  /**
   * 选择转换策略
   */
  selectStrategies(context) {
    const strategies = new Set();
    
    // 根据文件类型添加策略
    if (context.fileType !== 'unknown') {
      const fileTypeConfig = this.contextPatterns.fileTypes[context.fileType];
      fileTypeConfig.strategies.forEach(strategy => strategies.add(strategy));
    }
    
    // 根据业务领域添加策略
    if (context.businessDomain !== 'general') {
      const domainConfig = this.contextPatterns.businessDomains[context.businessDomain];
      domainConfig.strategies.forEach(strategy => strategies.add(strategy));
    }
    
    // 根据代码模式添加策略
    context.codePatterns.forEach(pattern => {
      const patternConfig = this.contextPatterns.codePatterns[pattern];
      patternConfig.strategies.forEach(strategy => strategies.add(strategy));
    });
    
    return Array.from(strategies);
  }
  
  /**
   * 分析代码结构
   */
  analyzeCodeStructure(content, context) {
    // 提取类名
    const classMatch = content.match(/class\s+(\w+)/);
    if (classMatch) {
      context.className = classMatch[1];
    }
    
    // 提取方法
    const methodMatches = content.match(/function\s+(\w+)\s*\([^)]*\)/g);
    if (methodMatches) {
      context.methods = methodMatches.map(match => {
        const methodMatch = match.match(/function\s+(\w+)/);
        return methodMatch ? methodMatch[1] : null;
      }).filter(Boolean);
    }
    
    // 提取属性
    const propertyMatches = content.match(/\$(\w+)/g);
    if (propertyMatches) {
      context.properties = [...new Set(propertyMatches.map(match => match.substring(1)))];
    }
    
    // 提取导入
    const importMatches = content.match(/use\s+([^;]+);/g);
    if (importMatches) {
      context.imports = importMatches.map(match => {
        const importMatch = match.match(/use\s+([^;]+);/);
        return importMatch ? importMatch[1] : null;
      }).filter(Boolean);
    }
  }
  
  /**
   * 应用上下文感知转换
   */
  applyContextAwareConversion(code, context) {
    let convertedCode = code;
    
    console.log(`🎭 应用上下文感知转换: ${context.fileType} - ${context.businessDomain}`);
    console.log(`📋 转换策略: ${context.strategies.join(', ')}`);
    
    // 应用选定的转换策略
    context.strategies.forEach(strategy => {
      if (this.conversionStrategies[strategy]) {
        convertedCode = this.conversionStrategies[strategy](convertedCode, context);
      }
    });
    
    return convertedCode;
  }
  
  // 转换策略实现
  applyServiceInjection(code, context) {
    // 服务注入转换逻辑
    return code.replace(/new\s+(\w+Service)\(\)/g, 'this.$1');
  }
  
  applyRepositoryPattern(code, context) {
    // 仓储模式转换逻辑
    return code.replace(/this->model/g, 'this.repository');
  }
  
  applyBusinessLogic(code, context) {
    // 业务逻辑转换
    return code;
  }
  
  applyHttpDecorators(code, context) {
    // HTTP装饰器转换
    return code;
  }
  
  applyDtoValidation(code, context) {
    // DTO验证转换
    return code;
  }
  
  applyResponseFormatting(code, context) {
    // 响应格式化转换
    return code.replace(/return\s+success\s*\(([^)]+)\)/g, 'return { success: true, data: $1 };');
  }
  
  applyTypeOrmDecorators(code, context) {
    // TypeORM装饰器转换
    return code;
  }
  
  applyPropertyMapping(code, context) {
    // 属性映射转换
    return code;
  }
  
  applyRelationshipMapping(code, context) {
    // 关系映射转换
    return code;
  }
  
  applyValidationDecorators(code, context) {
    // 验证装饰器转换
    return code;
  }
  
  applyPropertyTypes(code, context) {
    // 属性类型转换
    return code;
  }
  
  applySerialization(code, context) {
    // 序列化转换
    return code;
  }
  
  applyJwtAuth(code, context) {
    // JWT认证转换
    return code;
  }
  
  applyRoleBasedAccess(code, context) {
    // 基于角色的访问控制转换
    return code;
  }
  
  applyUserValidation(code, context) {
    // 用户验证转换
    return code;
  }
  
  applyPaymentProcessing(code, context) {
    // 支付处理转换
    return code;
  }
  
  applyOrderManagement(code, context) {
    // 订单管理转换
    return code;
  }
  
  applyTransactionLogging(code, context) {
    // 事务日志转换
    return code;
  }
  
  applyContentManagement(code, context) {
    // 内容管理转换
    return code;
  }
  
  applySeoOptimization(code, context) {
    // SEO优化转换
    return code;
  }
  
  applyMediaHandling(code, context) {
    // 媒体处理转换
    return code;
  }
  
  applyConfigurationManagement(code, context) {
    // 配置管理转换
    return code;
  }
  
  applySystemMonitoring(code, context) {
    // 系统监控转换
    return code;
  }
  
  applyAdminFunctions(code, context) {
    // 管理功能转换
    return code;
  }
  
  applyRepositoryMethods(code, context) {
    // 仓储方法转换
    return code;
  }
  
  applyValidationRules(code, context) {
    // 验证规则转换
    return code;
  }
  
  applyErrorHandling(code, context) {
    // 错误处理转换
    return code.replace(/throw\s+new\s+CommonException/g, 'throw new BusinessException');
  }
  
  applyHttpMethods(code, context) {
    // HTTP方法转换
    return code;
  }
  
  applyRouteDecorators(code, context) {
    // 路由装饰器转换
    return code;
  }
  
  applyRequestValidation(code, context) {
    // 请求验证转换
    return code;
  }
  
  applyValidationPipes(code, context) {
    // 验证管道转换
    return code;
  }
  
  applyCustomValidators(code, context) {
    // 自定义验证器转换
    return code;
  }
  
  applyErrorMessages(code, context) {
    // 错误消息转换
    return code;
  }
  
  applyCacheDecorators(code, context) {
    // 缓存装饰器转换
    return code;
  }
  
  applyCacheKeys(code, context) {
    // 缓存键转换
    return code;
  }
  
  applyExpirationHandling(code, context) {
    // 过期处理转换
    return code;
  }
  
  /**
   * 生成上下文报告
   */
  generateContextReport(context) {
    return {
      fileType: context.fileType,
      businessDomain: context.businessDomain,
      codePatterns: context.codePatterns,
      strategies: context.strategies,
      methods: context.methods,
      properties: context.properties,
      imports: context.imports,
      complexity: this.calculateComplexity(context)
    };
  }
  
  /**
   * 计算代码复杂度
   */
  calculateComplexity(context) {
    let complexity = 0;
    
    // 基于方法数量
    complexity += context.methods.length * 2;
    
    // 基于属性数量
    complexity += context.properties.length;
    
    // 基于策略数量
    complexity += context.strategies.length * 3;
    
    // 基于代码模式
    complexity += context.codePatterns.length * 5;
    
    return complexity;
  }
}

module.exports = ContextAwareConverter;
