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

/**
 * [BIZ_KER_111] 多平台 API 响应延迟监控 (Latency)
 * @description 核心逻辑：记录各平台（Amazon, Temu, 1688 等）API 请求的延迟。
 * 利用 Redis 实现秒级聚合，并生成响应时间的直方图（P50, P90, P99）。
 * 帮助识别网络抖动或平台侧服务降级。
 */
export class APIMetricsService {
  private static readonly METRICS_PREFIX = 'api_metrics:';
  private static readonly BUCKETS = [50, 100, 200, 500, 1000, 2000, 5000]; // 延迟分桶 (ms)

  /**
   * 记录 API 请求延迟
   */
  static async recordLatency(platform: string, endpoint: string, latencyMs: number) {
    const redis = RedisService.getClient();
    const dateKey = new Date().toISOString().split('T')[0];
    const baseKey = `${this.METRICS_PREFIX}${platform}:${endpoint}:${dateKey}`;

    try {
      // 1. 记录总次数与总耗时
      await redis.hincrby(baseKey, 'count', 1);
      await redis.hincrby(baseKey, 'total_latency', latencyMs);

      // 2. 记录延迟分桶 (用于生成直方图)
      const bucket = this.BUCKETS.find(b => latencyMs <= b) || 'over_5000';
      await redis.hincrby(baseKey, `bucket:${bucket}`, 1);

      // 3. 设置过期时间（保留 7 天）
      await redis.expire(baseKey, 7 * 24 * 60 * 60);

    } catch (err: any) {
      logger.error(`[APIMetrics] Failed to record latency: ${err.message}`);
    }
  }

  /**
   * 获取 API 性能报告
   */
  static async getPerformanceReport(platform: string, endpoint: string): Promise<any> {
    const redis = RedisService.getClient();
    const dateKey = new Date().toISOString().split('T')[0];
    const baseKey = `${this.METRICS_PREFIX}${platform}:${endpoint}:${dateKey}`;

    try {
      const stats = await redis.hgetall(baseKey);
      if (!stats || Object.keys(stats).length === 0) return null;

      const count = parseInt(stats.count);
      const avgLatency = parseInt(stats.total_latency) / count;

      const histogram: Record<string, number> = {};
      for (const bucket of [...this.BUCKETS, 'over_5000']) {
        histogram[bucket.toString()] = parseInt(stats[`bucket:${bucket}`] || '0');
      }

      return {
        platform,
        endpoint,
        date: dateKey,
        count,
        avgLatency: avgLatency.toFixed(2),
        histogram
      };
    } catch (err: any) {
      logger.error(`[APIMetrics] Failed to get report: ${err.message}`);
      return null;
    }
  }
}
