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

export interface WorkerMetric {
  queueName: string;
  processedCount: number;
  failedCount: number;
  avgDurationMs: number;
  maxDurationMs: number;
}

/**
 * [BIZ_KER_132] 全局异步任务性能瓶颈分析 (Worker Profiler)
 * @description 核心逻辑：记录并分析 BullMQ 异步任务的执行耗时。
 * 识别执行时间过长、失败率过高的队列任务（Worker）。
 * 输出性能瓶颈分析报告，辅助 AGI 进行任务分片建议。
 * 遵循 Autocomplete-First (V31.5) 规范。
 */
export class WorkerProfilerService {
  private static readonly METRICS_PREFIX = 'worker_metrics:';

  /**
   * 记录任务执行性能
   * @param queueName 队列名称
   * @param durationMs 执行耗时
   * @param success 是否成功
   */
  static async recordTaskPerformance(queueName: string, durationMs: number, success: boolean) {
    const redis = RedisService.getClient();
    const baseKey = `${this.METRICS_PREFIX}${queueName}`;

    try {
      await redis.hincrby(baseKey, 'count', 1);
      if (!success) await redis.hincrby(baseKey, 'failed', 1);
      await redis.hincrby(baseKey, 'total_duration', durationMs);
      
      // 更新最大耗时
      const currentMax = await redis.hget(baseKey, 'max_duration');
      if (!currentMax || durationMs > parseInt(currentMax)) {
        await redis.hset(baseKey, 'max_duration', durationMs);
      }
    } catch (err: any) {
      logger.error(`[WorkerProfiler] Failed to record metrics: ${err.message}`);
    }
  }

  /**
   * 初始化每日分析任务
   */
  static async init() {
    logger.info(`[WorkerProfiler] Initializing performance profiler...`);
    setInterval(() => this.runAnalysis(), 86400000); // 每日分析一次
  }

  /**
   * 执行瓶颈分析
   * @private
   */
  private static async runAnalysis() {
    try {
      const redis = RedisService.getClient();
      const keys = await redis.keys(`${this.METRICS_PREFIX}*`);
      const reports: string[] = [];

      for (const key of keys) {
        const stats = await redis.hgetall(key);
        const queueName = key.replace(this.METRICS_PREFIX, '');
        const avg = parseInt(stats.total_duration) / parseInt(stats.count);

        if (avg > 5000 || parseInt(stats.failed) / parseInt(stats.count) > 0.1) {
          reports.push(`⚠️ Queue \`${queueName}\`: Avg ${avg.toFixed(0)}ms, Failure Rate ${(parseInt(stats.failed)/parseInt(stats.count)*100).toFixed(1)}%`);
        }
      }

      const mdReport = this.generateMarkdownReport(reports);
      await SemanticLogService.logSemantic(mdReport, reports.length > 0 ? 'WARN' : 'INFO', 'PERF_AUDIT');

    } catch (err: any) {
      logger.error(`[WorkerProfiler] Analysis failed: ${err.message}`);
    }
  }

  /**
   * 生成 Markdown 报告
   * @private
   */
  private static generateMarkdownReport(bottlenecks: string[]): string {
    return `### ⚡ Async Worker Performance Profiler\n\n` +
           `**Status:** ${bottlenecks.length > 0 ? '🚨 Bottlenecks Detected' : '✅ Healthy'}\n\n` +
           `**Findings:**\n` +
           (bottlenecks.length > 0 ? bottlenecks.map(b => `- ${b}`).join('\n') : '- All workers performing within normal parameters.') +
           (bottlenecks.length > 0 ? `\n\n**Recommendation:** 识别到耗时较长的 Worker，建议对任务进行分片（Sharding）处理，或优化下游 API 调用响应速度。` : '');
  }
}
