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

export interface DeadLetterTask {
  jobId: string;
  queueName: string;
  failedReason: string;
  attemptsMade: number;
  data: any;
  timestamp: Date;
}

/**
 * [BIZ_KER_120] 全局异步任务死信队列监控 (DLQ)
 * @description 核心逻辑：监听 BullMQ 队列中的失败任务（死信）。
 * 自动提取失败原因并进行异常聚类，输出重试建议或人工介入提醒。
 * 遵循 Autocomplete-First (V31.5) 规范。
 */
export class BullMQDeadLetterService {
  private static readonly DLQ_PREFIX = 'dlq:monitor:';

  /**
   * 初始化死信监听
   * @description 模拟从 Redis 中扫描失败的任务流
   */
  static async init() {
    logger.info(`[DLQMonitor] Initializing async task dead-letter monitoring...`);
    // 实际生产环境下会监听 BullMQ 的 'failed' 事件
    this.startScanning();
  }

  /**
   * 记录并分析死信任务
   * @param task 失败的任务信息
   */
  static async reportDeadLetter(task: DeadLetterTask) {
    logger.warn(`[DLQMonitor] Dead letter detected in queue ${task.queueName}: ${task.jobId}`);

    const analysis = await this.analyzeFailure(task);
    const report = this.generateReport(task, analysis);

    await SemanticLogService.logSemantic(report, 'ERROR', 'ASYNC_WORKER');
    
    // 缓存分析结果以便前端展示
    const redis = RedisService.getClient();
    await redis.set(`${this.DLQ_PREFIX}${task.jobId}`, JSON.stringify({ task, analysis }), 'EX', 86400);
  }

  /**
   * 启动模拟扫描 (仅用于演示逻辑)
   * @private
   */
  private static startScanning() {
    setInterval(async () => {
      // 模拟发现一个失败任务
      const mockTask: DeadLetterTask = {
        jobId: `job_${Date.now()}`,
        queueName: 'ORDER_SYNC',
        failedReason: 'Connection timeout to Amazon SP-API',
        attemptsMade: 3,
        data: { orderId: '123-456' },
        timestamp: new Date()
      };
      await this.reportDeadLetter(mockTask);
    }, 3600000); // 每小时模拟一次
  }

  /**
   * 分析失败原因
   * @private
   */
  private static async analyzeFailure(task: DeadLetterTask) {
    if (task.failedReason.includes('timeout')) {
      return { category: 'NETWORK', recommendation: '建议检查代理节点稳定性或增加重试间隔。' };
    }
    if (task.failedReason.includes('auth')) {
      return { category: 'SECURITY', recommendation: 'API Key 已失效或权限不足，需人工核查配置。' };
    }
    return { category: 'LOGIC', recommendation: '业务逻辑异常，请检查数据一致性。' };
  }

  /**
   * 生成 Markdown 报告
   * @private
   */
  private static generateReport(task: DeadLetterTask, analysis: any): string {
    return `### 💀 Dead Letter Detected: \`${task.jobId}\`\n\n` +
           `**Queue:** ${task.queueName} | **Attempts:** ${task.attemptsMade}\n\n` +
           `**Failed Reason:** \`${task.failedReason}\`\n\n` +
           `**Category:** ${analysis.category}\n` +
           `**Recommendation:** ${analysis.recommendation}\n\n` +
           `**Payload Snapshot:** \`${JSON.stringify(task.data)}\``;
  }
}
