class LogManager {
  constructor() {
    this.logs = [];
    this.errors = [];
    this.maxLogs = 2000;
    this.maxErrors = 100;
    this.listeners = new Set(); // 使用 Set 提高性能
    this.isEnabled = false;
    
    // 搜索缓存
    this.searchCache = new Map();
    this.cacheMaxSize = 50;
    
    // 防抖定时器
    this.notifyTimer = null;
    this.pendingNotifications = new Set();
    
    // 保存原始的控制台方法
    this.originalConsole = {
      log: console.log,
      warn: console.warn,
      error: console.error,
      info: console.info,
      debug: console.debug,
    };
  }

  // 启用日志捕获
  enable() {
    if (this.isEnabled) return;
    this.isEnabled = true;
    
    // 重写控制台方法
    console.log = (...args) => {
      this.originalConsole.log(...args);
      this.addLog('log', args);
    };
    
    console.warn = (...args) => {
      this.originalConsole.warn(...args);
      this.addLog('warn', args);
    };
    
    console.error = (...args) => {
      this.originalConsole.error(...args);
      this.addLog('error', args);
      this.addError('console', args);
    };
    
    console.info = (...args) => {
      this.originalConsole.info(...args);
      this.addLog('info', args);
    };
    
    console.debug = (...args) => {
      this.originalConsole.debug(...args);
      this.addLog('debug', args);
    };
    
    // 设置全局错误处理
    this.setupGlobalErrorHandling();
  }

  // 禁用日志捕获
  disable() {
    if (!this.isEnabled) return;
    this.isEnabled = false;
    
    // 恢复原始控制台方法
    Object.assign(console, this.originalConsole);
  }

  // 添加日志
  addLog(type, args) {
    const logEntry = {
      id: Date.now() + Math.random(),
      type,
      message: this.formatMessage(args),
      timestamp: new Date().toLocaleTimeString(),
      fullTimestamp: new Date().toISOString(),
    };
    
    this.logs.unshift(logEntry);
    if (this.logs.length > this.maxLogs) {
      this.logs.length = this.maxLogs; // 更高效的截断方式
    }
    
    // 清空搜索缓存
    this.clearSearchCache();
    
    this.scheduleNotification('log', logEntry);
  }

  // 添加错误
  addError(source, args) {
    const errorEntry = {
      id: Date.now() + Math.random(),
      source, // 'console', 'global', 'react'
      message: this.formatMessage(args),
      timestamp: new Date().toLocaleTimeString(),
      fullTimestamp: new Date().toISOString(),
    };
    
    this.errors.unshift(errorEntry);
    if (this.errors.length > this.maxErrors) {
      this.errors.length = this.maxErrors; // 更高效的截断方式
    }
    
    // 清空搜索缓存
    this.clearSearchCache();
    
    this.scheduleNotification('error', errorEntry);
  }

  // 格式化消息
  formatMessage(args) {
    return args.map(arg => {
      if (typeof arg === 'object') {
        try {
          return JSON.stringify(arg, null, 2);
        } catch (e) {
          return String(arg);
        }
      }
      return String(arg);
    }).join(' ');
  }

  // 设置全局错误处理
  setupGlobalErrorHandling() {
    // React Native 全局错误处理
    if (global.ErrorUtils) {
      const originalHandler = global.ErrorUtils.getGlobalHandler();
      
      global.ErrorUtils.setGlobalHandler((error, isFatal) => {
        this.addError('global', [
          `${isFatal ? '[FATAL] ' : ''}${error.message}`,
          error.stack
        ]);
        
        // 调用原始处理器
        if (originalHandler) {
          originalHandler(error, isFatal);
        }
      });
    }
    
    // Promise 拒绝处理
    if (global.addEventListener) {
      global.addEventListener('unhandledrejection', (event) => {
        this.addError('promise', [
          'Unhandled Promise Rejection:',
          event.reason
        ]);
      });
    }
  }

  // 添加监听器
  addListener(callback) {
    this.listeners.add(callback);
    return () => {
      this.listeners.delete(callback);
    };
  }

  // 调度通知（防抖）
  scheduleNotification(type, data) {
    this.pendingNotifications.add({ type, data });
    
    if (this.notifyTimer) {
      clearTimeout(this.notifyTimer);
    }
    
    this.notifyTimer = setTimeout(() => {
      this.flushNotifications();
    }, 16); // 约 60fps 的频率
  }
  
  // 批量发送通知
  flushNotifications() {
    if (this.pendingNotifications.size === 0) return;
    
    const notifications = Array.from(this.pendingNotifications);
    this.pendingNotifications.clear();
    
    this.listeners.forEach(callback => {
      try {
        notifications.forEach(({ type, data }) => {
          callback(type, data);
        });
      } catch (e) {
        // 避免监听器错误影响日志系统
      }
    });
  }
  
  // 立即通知监听器（用于清空等操作）
  notifyListeners(type, data) {
    this.listeners.forEach(callback => {
      try {
        callback(type, data);
      } catch (e) {
        // 避免监听器错误影响日志系统
      }
    });
  }

  // 获取日志
  getLogs() {
    return [...this.logs];
  }

  // 获取错误
  getErrors() {
    return [...this.errors];
  }

  // 清空日志
  clearLogs() {
    this.logs = [];
    this.notifyListeners('clear', 'logs');
  }

  // 清空错误
  clearErrors() {
    this.errors = [];
    this.notifyListeners('clear', 'errors');
  }

  // 清空所有
  clearAll() {
    this.logs = [];
    this.errors = [];
    this.notifyListeners('clear', 'all');
  }

  // 导出日志
  exportLogs() {
    return {
      logs: this.logs,
      errors: this.errors,
      exportTime: new Date().toISOString(),
    };
  }

  // 清空搜索缓存
  clearSearchCache() {
    this.searchCache.clear();
  }
  
  // 管理缓存大小
  manageCacheSize() {
    if (this.searchCache.size > this.cacheMaxSize) {
      // 删除最旧的缓存项
      const firstKey = this.searchCache.keys().next().value;
      this.searchCache.delete(firstKey);
    }
  }

  // 搜索日志（带缓存）
  searchLogs(query) {
    if (!query || !query.trim()) return this.logs;
    
    const cacheKey = `logs:${query.toLowerCase()}`;
    
    // 检查缓存
    if (this.searchCache.has(cacheKey)) {
      return this.searchCache.get(cacheKey);
    }
    
    const lowerQuery = query.toLowerCase();
    const results = this.logs.filter(log => 
      log.message.toLowerCase().includes(lowerQuery) ||
      log.type.toLowerCase().includes(lowerQuery)
    );
    
    // 缓存结果
    this.manageCacheSize();
    this.searchCache.set(cacheKey, results);
    
    return results;
  }

  // 搜索错误（带缓存）
  searchErrors(query) {
    if (!query || !query.trim()) return this.errors;
    
    const cacheKey = `errors:${query.toLowerCase()}`;
    
    // 检查缓存
    if (this.searchCache.has(cacheKey)) {
      return this.searchCache.get(cacheKey);
    }
    
    const lowerQuery = query.toLowerCase();
    const results = this.errors.filter(error => 
      error.message.toLowerCase().includes(lowerQuery) ||
      error.source.toLowerCase().includes(lowerQuery)
    );
        // 缓存结果
    this.manageCacheSize();
    this.searchCache.set(cacheKey, results);
    
    return results;
  }
}

// 单例实例
const logManager = new LogManager();

export default logManager;