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

export interface LogCluster {
  pattern: string;
  count: number;
  lastOccurrence: Date;
  isAnomaly: boolean;
}

/**
 * [CORE_DEV_10] 分布式日志聚合与异常聚类分析 (Log Clustering)
 * @description 基于模式识别实现日志的自动分类与异常聚类，支持在大规模节点环境下快速定位系统异常
 */
export class LogAnalyticsService {
  private static clusters: Map<string, LogCluster> = new Map();

  /**
   * 分析日志并归类
   * @param message 日志消息
   */
  static analyzeLog(message: string): void {
    // 1. 提取模式：通过正则屏蔽动态变量（如 UUID, IP, Timestamp）
    const pattern = message
      .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '<UUID>')
      .replace(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/g, '<IP>')
      .replace(/\d+/g, '<NUM>')
      .trim();

    // 2. 更新或创建聚类
    const cluster = this.clusters.get(pattern) || {
      pattern,
      count: 0,
      lastOccurrence: new Date(),
      isAnomaly: false
    };

    cluster.count++;
    cluster.lastOccurrence = new Date();

    // 3. 简单的异常检测逻辑 (模拟)
    // 逻辑：如果错误类日志在短时间内激增，则标记为异常
    if (message.toLowerCase().includes('error') && cluster.count > 100) {
      cluster.isAnomaly = true;
      logger.error(`[LogAnalytics] Anomaly detected for pattern: ${pattern}`);
    }

    this.clusters.set(pattern, cluster);
  }

  /**
   * 获取当前活跃的日志聚类报告
   */
  static getClusterReport(): LogCluster[] {
    return Array.from(this.clusters.values()).sort((a, b) => b.count - a.count);
  }

  /**
   * 模拟从多节点聚合日志
   */
  static async ingestRemoteLogs(nodeId: string, logs: string[]): Promise<void> {
    logger.info(`[LogAnalytics] Ingesting ${logs.length} logs from node: ${nodeId}`);
    logs.forEach(log => this.analyzeLog(log));
  }
}
