import { RedisService } from '../cache/RedisService';
import { RuleEngineService } from '../engine/RuleEngineService';
import { WorkflowEngineService } from '../engine/WorkflowEngineService';

/**
 * 核心业务逻辑引擎服务
 * 提供统一的业务处理框架，集成规则引擎、工作流引擎和缓存系统
 * 
 * @task_id CORE_ENG_01
 * @description 系统核心业务逻辑引擎，提供统一的业务处理框架
 * @tech_stack TypeScript + 规则引擎 + 工作流引擎 + 缓存系统
 * @acceptance_criteria 业务处理<100ms，支持1000并发请求，错误率<0.1%
 */
export class CoreEngineService {
  constructor(
    private readonly ruleEngineService: RuleEngineService,
    private readonly workflowEngineService: WorkflowEngineService,
    private readonly redisService: RedisService
  ) {}

  /**
   * 处理业务请求
   * @param request 业务请求数据
   * @param context 业务上下文
   * @returns 处理结果
   */
  async processBusinessRequest(request: any, context: any): Promise<any> {
    const startTime = Date.now();
    
    try {
      // 1. 检查缓存
      const cacheKey = this.generateCacheKey(request);
      const cachedResult = await this.redisService.get(cacheKey);
      if (cachedResult) {
        return cachedResult;
      }

      // 2. 执行业务规则
      const ruleResult = await this.ruleEngineService.executeRules(request, context);
      
      // 3. 执行工作流
      const workflowResult = await this.workflowEngineService.executeWorkflow(
        ruleResult.workflowId,
        ruleResult.data
      );

      // 4. 缓存结果
      await this.redisService.set(cacheKey, workflowResult, 3600);

      const processingTime = Date.now() - startTime;
      console.log(`CoreEngineService: Business request processed in ${processingTime}ms`);

      return workflowResult;
    } catch (error) {
      console.error('CoreEngineService: Error processing business request:', error);
      throw error;
    }
  }

  /**
   * 生成缓存键
   * @param request 业务请求数据
   * @returns 缓存键
   */
  private generateCacheKey(request: any): string {
    return `core-engine:${JSON.stringify(request)}`;
  }

  /**
   * 注册业务规则
   * @param rule 业务规则
   * @returns 规则ID
   */
  async registerBusinessRule(rule: any): Promise<string> {
    return this.ruleEngineService.registerRule(rule);
  }

  /**
   * 注册工作流
   * @param workflow 工作流定义
   * @returns 工作流ID
   */
  async registerWorkflow(workflow: any): Promise<string> {
    return this.workflowEngineService.registerWorkflow(workflow);
  }

  /**
   * 获取系统状态
   * @returns 系统状态
   */
  async getSystemStatus(): Promise<any> {
    return {
      status: 'healthy',
      timestamp: new Date().toISOString(),
      services: {
        ruleEngine: await this.ruleEngineService.getStatus(),
        workflowEngine: await this.workflowEngineService.getStatus(),
        redis: await this.redisService.getStatus()
      }
    };
  }
}
