import { logger } from '../../utils/logger';
import { RedisService } from '../../utils/RedisService';

export enum TaskPriority {
  IMMEDIATE = 0, // 极高优先级：如订单处理、支付回调
  BUSINESS_CORE = 1, // 核心业务：如刊登、同步
  AGI_HEAVY = 2, // AGI 重型：如策略演化、大批量分析
  BACKGROUND = 3, // 背景任务：如数据归档、冷热分层
  TOC_LOCALIZATION = 4 // ToC 本地化：如图片翻译、SEO 优化 (New)
}

export interface BizTask {
  id: string;
  tenantId: string;
  type: string;
  priority: TaskPriority;
  payload: any;
  createdAt: number;
}

/**
 * [ARCH_OPT_02] 基于优先级的异步处理引擎 (Priority-based Async Engine)
 * @description 核心逻辑：解耦轻量业务与重型 AGI。
 * 业务初期的高频、低延迟需求（如：刊登、连接）通过 IMMEDIATE/BUSINESS_CORE 队列快速处理。
 * 重型 AGI 任务（如：策略深度博弈）则异步排队，确保不阻塞主流程。
 */
export class PriorityAsyncEngine {
  private static readonly QUEUE_PREFIX = 'biz:queue:';
  private static isRunning = false;

  /**
   * 提交任务
   */
  static async submitTask(task: BizTask) {
    const queueKey = `${this.QUEUE_PREFIX}${task.priority}`;
    await RedisService.lPush(queueKey, JSON.stringify(task));
    logger.info(`[AsyncEngine] Task ${task.id} (Priority: ${task.priority}) submitted by Tenant ${task.tenantId}`);
  }

  /**
   * 启动处理器 (Worker 模拟)
   */
  static startProcessor() {
    if (this.isRunning) return;
    this.isRunning = true;
    logger.info('[AsyncEngine] Priority processor started.');

    // 轮询队列 (按优先级)
    this.poll();
  }

  private static async poll() {
    while (this.isRunning) {
      let taskFound = false;

      // 按优先级顺序检查队列 (0 -> 1 -> 2 -> 3 -> 4)
      for (let p = 0; p <= 4; p++) {
        const queueKey = `${this.QUEUE_PREFIX}${p}`;
        const taskData = await RedisService.rPop(queueKey);

        if (taskData) {
          taskFound = true;
          const task: BizTask = JSON.parse(taskData);
          await this.executeTask(task);
          break; // 处理完一个高优先级的，重新从最高优先级开始轮询
        }
      }

      if (!taskFound) {
        await new Promise(resolve => setTimeout(resolve, 1000)); // 无任务时休眠
      }
    }
  }

  private static async executeTask(task: BizTask) {
    logger.info(`[AsyncEngine] Executing Task ${task.id} [${task.type}] (Priority: ${task.priority})`);
    
    try {
      const { EarlyStageBizService } = await import('../biz/EarlyStageBizService');
      const { ProductService } = await import('../../services/ProductService');
      
      switch (task.type) {
        case 'STORE_INITIALIZATION':
          // 模拟初始化逻辑：同步分类、设置默认规则
          logger.info(`[AsyncEngine] Initializing store ${task.payload.storeName} for ${task.payload.platform}`);
          await new Promise(resolve => setTimeout(resolve, 2000)); // 模拟耗时操作
          break;

        case 'QUICK_LISTING':
          await EarlyStageBizService.quickListing(task.payload);
          break;

        case 'PRODUCT_SYNC':
          await ProductService.syncProduct(task.payload.productId, task.payload.tenantId);
          break;

        case 'TOC_LOCALIZATION':
          // 处理 ToC 本地化任务 (图片翻译、多语言 SEO)
          logger.info(`[AsyncEngine] Localization task for product ${task.payload.productId}`);
          // 逻辑：调用 AIService 完成翻译并回写
          break;

        default:
          logger.warn(`[AsyncEngine] Unknown task type: ${task.type}`);
      }
      
      logger.info(`[AsyncEngine] Task ${task.id} completed successfully.`);
    } catch (err: any) {
      logger.error(`[AsyncEngine] Task ${task.id} failed: ${err.message}`);
    }
  }
}
