import { DomainEventBus } from '../runtime/DomainEventBus';

// 异常知识条目
export interface ExceptionKnowledgeItem {
  id: string;
  exceptionType: string;
  messagePattern: string;
  description: string;
  cause: string;
  solution: string;
  prevention: string;
  severity: 'low' | 'medium' | 'high' | 'critical';
  frequency: number;
  references?: string[];
  createdAt: Date;
  lastUpdated: Date;
  lastSeen: Date;
}

// 异常知识查询结果
export interface ExceptionKnowledgeQueryResult {
  items: ExceptionKnowledgeItem[];
  total: number;
  page: number;
  pageSize: number;
  query: string;
  filters?: Record<string, string>;
}

// 异常知识统计
export interface ExceptionKnowledgeStats {
  totalItems: number;
  bySeverity: {
    low: number;
    medium: number;
    high: number;
    critical: number;
  };
  byType: Record<string, number>;
  mostFrequent: ExceptionKnowledgeItem[];
  recentlyUpdated: ExceptionKnowledgeItem[];
  averageFrequency: number;
}

// 异常知识库
export class ExceptionKnowledgeBase {
  private static instance: ExceptionKnowledgeBase;
  private knowledgeItems: Map<string, ExceptionKnowledgeItem> = new Map();
  private eventBus: DomainEventBus;

  private constructor() {
    this.eventBus = DomainEventBus.getInstance();
  }

  static getInstance(): ExceptionKnowledgeBase {
    if (!ExceptionKnowledgeBase.instance) {
      ExceptionKnowledgeBase.instance = new ExceptionKnowledgeBase();
    }
    return ExceptionKnowledgeBase.instance;
  }

  // 添加异常知识条目
  async addKnowledgeItem(item: Omit<ExceptionKnowledgeItem, 'id' | 'frequency' | 'createdAt' | 'lastUpdated' | 'lastSeen'>): Promise<ExceptionKnowledgeItem> {
    const id = `knowledge_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    
    const newItem: ExceptionKnowledgeItem = {
      ...item,
      id,
      frequency: 1,
      createdAt: new Date(),
      lastUpdated: new Date(),
      lastSeen: new Date()
    };

    this.knowledgeItems.set(id, newItem);
    this.eventBus.publish('exception.knowledge.added', newItem);
    return newItem;
  }

  // 获取异常知识条目
  getKnowledgeItem(itemId: string): ExceptionKnowledgeItem | undefined {
    return this.knowledgeItems.get(itemId);
  }

  // 获取所有异常知识条目
  getAllKnowledgeItems(filters?: {
    severity?: string;
    exceptionType?: string;
    minFrequency?: number;
  }): ExceptionKnowledgeItem[] {
    let result = Array.from(this.knowledgeItems.values());

    if (filters) {
      if (filters.severity) {
        result = result.filter(item => item.severity === filters.severity);
      }

      if (filters.exceptionType) {
        result = result.filter(item => item.exceptionType === filters.exceptionType);
      }

      if (filters.minFrequency !== undefined) {
        result = result.filter(item => item.frequency >= filters.minFrequency!);
      }
    }

    return result.sort((a, b) => b.frequency - a.frequency);
  }

  // 更新异常知识条目
  async updateKnowledgeItem(itemId: string, updates: Partial<ExceptionKnowledgeItem>): Promise<ExceptionKnowledgeItem | null> {
    const item = this.knowledgeItems.get(itemId);
    if (!item) {
      return null;
    }

    const updatedItem = {
      ...item,
      ...updates,
      lastUpdated: new Date()
    };

    this.knowledgeItems.set(itemId, updatedItem);
    this.eventBus.publish('exception.knowledge.updated', updatedItem);
    return updatedItem;
  }

  // 删除异常知识条目
  async deleteKnowledgeItem(itemId: string): Promise<boolean> {
    const item = this.knowledgeItems.get(itemId);
    if (!item) {
      return false;
    }

    this.knowledgeItems.delete(itemId);
    this.eventBus.publish('exception.knowledge.deleted', item);
    return true;
  }

  // 搜索异常知识
  searchKnowledge(query: string, page: number = 1, pageSize: number = 10, filters?: Record<string, string>): ExceptionKnowledgeQueryResult {
    let results = Array.from(this.knowledgeItems.values());

    // 应用过滤器
    if (filters) {
      for (const [key, value] of Object.entries(filters)) {
        if (key === 'severity') {
          results = results.filter(item => item.severity === value);
        } else if (key === 'exceptionType') {
          results = results.filter(item => item.exceptionType === value);
        }
      }
    }

    // 搜索查询
    if (query) {
      const lowerQuery = query.toLowerCase();
      results = results.filter(item => 
        item.exceptionType.toLowerCase().includes(lowerQuery) ||
        item.messagePattern.toLowerCase().includes(lowerQuery) ||
        item.description.toLowerCase().includes(lowerQuery) ||
        item.cause.toLowerCase().includes(lowerQuery) ||
        item.solution.toLowerCase().includes(lowerQuery)
      );
    }

    // 排序
    results.sort((a, b) => b.frequency - a.frequency);

    // 分页
    const total = results.length;
    const start = (page - 1) * pageSize;
    const end = start + pageSize;
    const paginatedResults = results.slice(start, end);

    return {
      items: paginatedResults,
      total,
      page,
      pageSize,
      query,
      filters
    };
  }

  // 匹配异常
  matchException(exceptionType: string, message: string): ExceptionKnowledgeItem[] {
    const results: ExceptionKnowledgeItem[] = [];

    for (const item of this.knowledgeItems.values()) {
      // 检查异常类型匹配
      if (item.exceptionType === exceptionType) {
        // 检查消息模式匹配
        try {
          const regex = new RegExp(item.messagePattern);
          if (regex.test(message)) {
            results.push(item);
          }
        } catch (error) {
          // 正则表达式错误，使用简单字符串匹配
          if (message.includes(item.messagePattern)) {
            results.push(item);
          }
        }
      }
    }

    // 按频率排序
    return results.sort((a, b) => b.frequency - a.frequency);
  }

  // 增加异常频率
  async incrementFrequency(itemId: string): Promise<ExceptionKnowledgeItem | null> {
    const item = this.knowledgeItems.get(itemId);
    if (!item) {
      return null;
    }

    const updatedItem = {
      ...item,
      frequency: item.frequency + 1,
      lastSeen: new Date(),
      lastUpdated: new Date()
    };

    this.knowledgeItems.set(itemId, updatedItem);
    this.eventBus.publish('exception.knowledge.frequency.updated', updatedItem);
    return updatedItem;
  }

  // 批量增加异常频率
  async batchIncrementFrequency(itemIds: string[]): Promise<ExceptionKnowledgeItem[]> {
    const updatedItems: ExceptionKnowledgeItem[] = [];

    for (const itemId of itemIds) {
      const updatedItem = await this.incrementFrequency(itemId);
      if (updatedItem) {
        updatedItems.push(updatedItem);
      }
    }

    return updatedItems;
  }

  // 获取异常知识统计
  getKnowledgeStats(): ExceptionKnowledgeStats {
    const items = Array.from(this.knowledgeItems.values());
    const totalItems = items.length;

    const bySeverity = {
      low: 0,
      medium: 0,
      high: 0,
      critical: 0
    };

    const byType: Record<string, number> = {};

    let totalFrequency = 0;

    for (const item of items) {
      bySeverity[item.severity]++;
      byType[item.exceptionType] = (byType[item.exceptionType] || 0) + 1;
      totalFrequency += item.frequency;
    }

    const mostFrequent = [...items].sort((a, b) => b.frequency - a.frequency).slice(0, 10);
    const recentlyUpdated = [...items].sort((a, b) => b.lastUpdated.getTime() - a.lastUpdated.getTime()).slice(0, 10);

    const averageFrequency = totalItems > 0 ? totalFrequency / totalItems : 0;

    return {
      totalItems,
      bySeverity,
      byType,
      mostFrequent,
      recentlyUpdated,
      averageFrequency
    };
  }

  // 导入异常知识
  async importKnowledge(items: Omit<ExceptionKnowledgeItem, 'id' | 'frequency' | 'createdAt' | 'lastUpdated' | 'lastSeen'>[]): Promise<{
    success: number;
    failed: number;
  }> {
    let success = 0;
    let failed = 0;

    for (const item of items) {
      try {
        await this.addKnowledgeItem(item);
        success++;
      } catch (error) {
        failed++;
      }
    }

    return { success, failed };
  }

  // 导出异常知识
  exportKnowledge(filters?: {
    severity?: string;
    exceptionType?: string;
    minFrequency?: number;
  }): ExceptionKnowledgeItem[] {
    return this.getAllKnowledgeItems(filters);
  }

  // 生成异常知识报告
  async generateKnowledgeReport(): Promise<{
    stats: ExceptionKnowledgeStats;
    mostCommonExceptions: ExceptionKnowledgeItem[];
    leastCommonExceptions: ExceptionKnowledgeItem[];
    recentlyAdded: ExceptionKnowledgeItem[];
  }> {
    const items = Array.from(this.knowledgeItems.values());
    const stats = this.getKnowledgeStats();

    const mostCommonExceptions = [...items].sort((a, b) => b.frequency - a.frequency).slice(0, 20);
    const leastCommonExceptions = [...items].sort((a, b) => a.frequency - b.frequency).slice(0, 20);
    const recentlyAdded = [...items].sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()).slice(0, 20);

    return {
      stats,
      mostCommonExceptions,
      leastCommonExceptions,
      recentlyAdded
    };
  }

  // 清理旧的异常知识
  async cleanupOldKnowledge(days: number = 365): Promise<number> {
    const cutoffDate = new Date();
    cutoffDate.setDate(cutoffDate.getDate() - days);

    let removedCount = 0;

    for (const [id, item] of this.knowledgeItems.entries()) {
      if (item.lastSeen < cutoffDate && item.frequency < 5) {
        this.knowledgeItems.delete(id);
        removedCount++;
      }
    }

    if (removedCount > 0) {
      this.eventBus.publish('exception.knowledge.cleanup', {
        removedCount,
        cutoffDate,
        timestamp: new Date()
      });
    }

    return removedCount;
  }
}
