/**
 * 消息过滤服务
 * 
 * 功能描述：
 * - 实施内容审核和频率控制
 * - 敏感词过滤和权限验证
 * - 防止恶意操作和滥用
 * - 与ConfigManager集成实现位置权限验证
 * 
 * 职责分离：
 * - 内容审核：检查消息内容是否包含敏感词和恶意链接
 * - 频率控制：防止用户发送消息过于频繁导致刷屏
 * - 权限验证：验证用户是否有权限向目标Stream发送消息
 * - 违规记录：记录和统计用户的违规行为
 * - 规则管理：动态管理敏感词列表和过滤规则
 * 
 * 主要方法：
 * - filterContent(): 内容过滤，敏感词检查
 * - checkRateLimit(): 频率限制检查
 * - validatePermission(): 权限验证，防止位置欺诈
 * - logViolation(): 记录违规行为
 * 
 * 使用场景：
 * - 消息发送前的内容审核
 * - 频率限制和防刷屏
 * - 权限验证和安全控制
 * 
 * 依赖模块：
 * - AppLoggerService: 日志记录服务
 * - IRedisService: Redis缓存服务
 * - ConfigManagerService: 配置管理服务
 * 
 * 最近修改：
 * - 2026-01-07: 代码规范优化 - 清理未使用的导入(forwardRef) (修改者: moyin)
 * - 2026-01-07: 代码规范优化 - 完善文件头注释和修改记录 (修改者: moyin)
 * 
 * @author angjustinl
 * @version 1.1.2
 * @since 2025-12-25
 * @lastModified 2026-01-07
 */

import { Injectable, Logger, Inject } from '@nestjs/common';
import { IRedisService } from '../../../core/redis/redis.interface';
import { IZulipConfigService } from '../../../core/zulip_core/zulip_core.interfaces';

/**
 * 内容过滤结果接口
 */
export interface ContentFilterResult {
  allowed: boolean;
  filtered?: string;
  reason?: string;
}

/**
 * 权限验证结果接口
 */
export interface PermissionValidationResult {
  allowed: boolean;
  reason?: string;
  expectedStream?: string;
  actualStream?: string;
}

/**
 * 频率限制结果接口
 */
export interface RateLimitResult {
  allowed: boolean;
  currentCount: number;
  limit: number;
  remainingTime?: number;
  reason?: string;
}

/**
 * 违规类型枚举
 */
export enum ViolationType {
  CONTENT = 'content',
  RATE = 'rate',
  PERMISSION = 'permission',
}

/**
 * 违规记录接口
 */
export interface ViolationRecord {
  userId: string;
  type: ViolationType;
  details: any;
  timestamp: Date;
}

/**
 * 敏感词配置接口
 */
export interface SensitiveWordConfig {
  word: string;
  level: 'block' | 'replace';  // block: 直接拒绝, replace: 替换为星号
  category?: string;
}

/**
 * 消息过滤服务类
 * 
 * 职责：
 * - 实施内容审核和频率控制
 * - 敏感词过滤和权限验证
 * - 防止恶意操作和滥用
 * - 与ConfigManager集成实现位置权限验证
 * 
 * 主要方法：
 * - filterContent(): 内容过滤，敏感词检查
 * - checkRateLimit(): 频率限制检查
 * - validatePermission(): 权限验证，防止位置欺诈
 * - validateMessage(): 综合消息验证
 * - logViolation(): 记录违规行为
 * 
 * 使用场景：
 * - 消息发送前的内容审核
 * - 频率限制和防刷屏
 * - 权限验证和安全控制
 * - 违规行为监控和记录
 */
@Injectable()
export class MessageFilterService {
  private readonly RATE_LIMIT_PREFIX = 'zulip:rate_limit:';
  private readonly VIOLATION_PREFIX = 'zulip:violation:';
  private readonly VIOLATION_COUNT_PREFIX = 'zulip:violation_count:';
  private readonly DEFAULT_RATE_LIMIT = 10; // 每分钟最多10条消息
  private readonly RATE_LIMIT_WINDOW = 60; // 60秒窗口
  private readonly MAX_MESSAGE_LENGTH = 1000; // 最大消息长度
  private readonly MIN_MESSAGE_LENGTH = 1; // 最小消息长度
  private readonly logger = new Logger(MessageFilterService.name);

  // 敏感词列表（可从配置文件或数据库加载）
  private sensitiveWords: SensitiveWordConfig[] = [
    { word: '垃圾', level: 'replace', category: 'offensive' },
    { word: '广告', level: 'replace', category: 'spam' },
    { word: '刷屏', level: 'replace', category: 'spam' },
    { word: '傻逼', level: 'block', category: 'offensive' },
    { word: '操你', level: 'block', category: 'offensive' },
  ];

  // 恶意链接黑名单域名
  private readonly BLACKLISTED_DOMAINS = [
    'malware.com',
    'phishing.net',
    'spam-site.org',
  ];

  // 允许的链接白名单域名
  private readonly WHITELISTED_DOMAINS = [
    'github.com',
    'datawhale.club',
    'zulip.com',
  ];

  constructor(
    @Inject('REDIS_SERVICE')
    private readonly redisService: IRedisService,
    @Inject('ZULIP_CONFIG_SERVICE')
    private readonly configManager: IZulipConfigService,
  ) {
    this.logger.log('MessageFilterService初始化完成');
  }

  /**
   * 内容过滤 - 敏感词检查
   * 
   * 功能描述：
   * 检查消息内容是否包含敏感词，进行内容过滤和替换
   * 
   * 业务逻辑：
   * 1. 检查消息长度限制
   * 2. 检查是否全为空白字符
   * 3. 扫描敏感词列表（区分block和replace级别）
   * 4. 检查重复字符和刷屏行为
   * 5. 检查恶意链接
   * 6. 返回过滤结果
   * 
   * @param content 消息内容
   * @returns Promise<ContentFilterResult> 过滤结果
   */
  async filterContent(content: string): Promise<ContentFilterResult> {
    this.logger.debug('开始内容过滤', {
      operation: 'filterContent',
      contentLength: content?.length || 0,
      timestamp: new Date().toISOString(),
    });

    try {
      // 1. 检查消息是否为空
      if (!content || content.trim().length === 0) {
        return {
          allowed: false,
          reason: '消息内容不能为空',
        };
      }

      // 2. 检查消息长度
      if (content.length > this.MAX_MESSAGE_LENGTH) {
        return {
          allowed: false,
          reason: `消息内容过长，最多${this.MAX_MESSAGE_LENGTH}字符`,
        };
      }

      if (content.trim().length < this.MIN_MESSAGE_LENGTH) {
        return {
          allowed: false,
          reason: '消息内容过短',
        };
      }

      // 3. 检查是否全为空白字符
      if (/^\s+$/.test(content)) {
        return {
          allowed: false,
          reason: '消息不能只包含空白字符',
        };
      }

      // 4. 敏感词检查
      let filteredContent = content;
      let hasBlockedWord = false;
      let hasReplacedWord = false;
      let blockedWord = '';

      for (const wordConfig of this.sensitiveWords) {
        if (content.toLowerCase().includes(wordConfig.word.toLowerCase())) {
          if (wordConfig.level === 'block') {
            hasBlockedWord = true;
            blockedWord = wordConfig.word;
            break;
          } else {
            hasReplacedWord = true;
            // 替换敏感词为星号
            const replacement = '*'.repeat(wordConfig.word.length);
            filteredContent = filteredContent.replace(
              new RegExp(this.escapeRegExp(wordConfig.word), 'gi'),
              replacement
            );
          }
        }
      }

      // 如果包含需要阻止的敏感词，直接拒绝
      if (hasBlockedWord) {
        this.logger.warn('消息包含禁止的敏感词', {
          operation: 'filterContent',
          blockedWord,
          contentLength: content.length,
        });
        return {
          allowed: false,
          reason: '消息包含不允许的内容',
        };
      }

      // 5. 检查是否包含过多重复字符（防刷屏）
      if (this.hasExcessiveRepetition(content)) {
        return {
          allowed: false,
          reason: '消息包含过多重复字符',
        };
      }

      // 6. 检查是否包含恶意链接
      const linkCheckResult = this.checkLinks(content);
      if (!linkCheckResult.allowed) {
        return {
          allowed: false,
          reason: linkCheckResult.reason,
        };
      }

      const result: ContentFilterResult = {
        allowed: true,
        filtered: hasReplacedWord ? filteredContent : undefined,
      };

      this.logger.debug('内容过滤完成', {
        operation: 'filterContent',
        allowed: result.allowed,
        hasReplacedWord,
        originalLength: content.length,
        filteredLength: filteredContent.length,
      });

      return result;

    } catch (error) {
      const err = error as Error;
      this.logger.error('内容过滤失败', {
        operation: 'filterContent',
        contentLength: content?.length || 0,
        error: err.message,
        timestamp: new Date().toISOString(),
      }, err.stack);

      // 过滤失败时默认拒绝
      return {
        allowed: false,
        reason: '内容过滤失败，请稍后重试',
      };
    }
  }

  /**
   * 频率限制检查
   * 
   * 功能描述：
   * 检查用户是否超过消息发送频率限制，防止刷屏
   * 
   * 业务逻辑：
   * 1. 获取用户当前发送计数
   * 2. 检查是否超过限制
   * 3. 更新发送计数
   * 4. 返回检查结果
   * 
   * @param userId 用户ID
   * @returns Promise<boolean> 是否允许发送（true表示允许）
   */
  async checkRateLimit(userId: string): Promise<boolean> {
    const result = await this.checkRateLimitDetailed(userId);
    return result.allowed;
  }

  /**
   * 频率限制检查（详细版本）
   * 
   * 功能描述：
   * 检查用户是否超过消息发送频率限制，返回详细信息
   * 
   * @param userId 用户ID
   * @param customLimit 自定义限制（可选）
   * @returns Promise<RateLimitResult> 频率限制检查结果
   */
  async checkRateLimitDetailed(userId: string, customLimit?: number): Promise<RateLimitResult> {
    this.logger.debug('开始频率限制检查', {
      operation: 'checkRateLimitDetailed',
      userId,
      timestamp: new Date().toISOString(),
    });

    const limit = customLimit || this.DEFAULT_RATE_LIMIT;

    try {
      const rateLimitKey = `${this.RATE_LIMIT_PREFIX}${userId}`;
      
      // 获取当前计数
      const currentCount = await this.redisService.get(rateLimitKey);
      const count = currentCount ? parseInt(currentCount, 10) : 0;

      // 检查是否超过限制
      if (count >= limit) {
        this.logger.warn('用户超过频率限制', {
          operation: 'checkRateLimitDetailed',
          userId,
          currentCount: count,
          limit,
        });

        // 获取剩余时间
        const ttl = await this.redisService.ttl(rateLimitKey);

        // 记录违规行为
        await this.logViolation(userId, ViolationType.RATE, {
          currentCount: count,
          limit,
          remainingTime: ttl,
        });

        return {
          allowed: false,
          currentCount: count,
          limit,
          remainingTime: ttl > 0 ? ttl : undefined,
          reason: `发送频率过高，请${ttl > 0 ? `${ttl}秒后` : '稍后'}重试`,
        };
      }

      // 增加计数
      if (count === 0) {
        // 首次发送，设置计数和过期时间
        await this.redisService.setex(rateLimitKey, this.RATE_LIMIT_WINDOW, '1');
      } else {
        // 增加计数
        await this.redisService.incr(rateLimitKey);
      }

      this.logger.debug('频率限制检查通过', {
        operation: 'checkRateLimitDetailed',
        userId,
        newCount: count + 1,
        limit,
      });

      return {
        allowed: true,
        currentCount: count + 1,
        limit,
      };

    } catch (error) {
      const err = error as Error;
      this.logger.error('频率限制检查失败', {
        operation: 'checkRateLimitDetailed',
        userId,
        error: err.message,
        timestamp: new Date().toISOString(),
      }, err.stack);

      // 检查失败时默认允许，避免影响正常用户
      return {
        allowed: true,
        currentCount: 0,
        limit,
        reason: '频率检查服务暂时不可用',
      };
    }
  }

  /**
   * 权限验证 - 防止位置欺诈
   * 
   * 功能描述：
   * 验证用户是否有权限向目标Stream发送消息，防止位置欺诈
   * 使用ConfigManager获取地图到Stream的映射关系
   * 
   * 业务逻辑：
   * 1. 从ConfigManager获取地图到Stream的映射
   * 2. 检查目标Stream是否匹配当前地图
   * 3. 检查用户是否有特殊权限（如管理员）
   * 4. 返回验证结果
   * 
   * @param userId 用户ID
   * @param targetStream 目标Stream名称
   * @param currentMap 当前地图ID
   * @returns Promise<boolean> 是否有权限（true表示有权限）
   */
  async validatePermission(userId: string, targetStream: string, currentMap: string): Promise<boolean> {
    const result = await this.validatePermissionDetailed(userId, targetStream, currentMap);
    return result.allowed;
  }

  /**
   * 权限验证（详细版本）
   * 
   * 功能描述：
   * 验证用户是否有权限向目标Stream发送消息，返回详细信息
   * 
   * @param userId 用户ID
   * @param targetStream 目标Stream名称
   * @param currentMap 当前地图ID
   * @returns Promise<PermissionValidationResult> 权限验证结果
   */
  async validatePermissionDetailed(
    userId: string,
    targetStream: string,
    currentMap: string
  ): Promise<PermissionValidationResult> {
    this.logger.debug('开始权限验证', {
      operation: 'validatePermissionDetailed',
      userId,
      targetStream,
      currentMap,
      timestamp: new Date().toISOString(),
    });

    try {
      // 1. 参数验证
      if (!userId || !userId.trim()) {
        return {
          allowed: false,
          reason: '用户ID无效',
        };
      }

      if (!targetStream || !targetStream.trim()) {
        return {
          allowed: false,
          reason: '目标Stream无效',
        };
      }

      if (!currentMap || !currentMap.trim()) {
        return {
          allowed: false,
          reason: '当前地图无效',
        };
      }

      // 2. 从ConfigManager获取地图对应的Stream
      const allowedStream = this.configManager.getStreamByMap(currentMap);
      
      if (!allowedStream) {
        this.logger.warn('未知地图，拒绝发送', {
          operation: 'validatePermissionDetailed',
          userId,
          currentMap,
          targetStream,
        });

        await this.logViolation(userId, ViolationType.PERMISSION, {
          reason: 'unknown_map',
          currentMap,
          targetStream,
        });

        return {
          allowed: false,
          reason: '当前地图未配置对应的聊天频道',
        };
      }

      // 3. 检查目标Stream是否匹配（不区分大小写）
      if (targetStream.toLowerCase() !== allowedStream.toLowerCase()) {
        this.logger.warn('位置与目标Stream不匹配', {
          operation: 'validatePermissionDetailed',
          userId,
          currentMap,
          targetStream,
          allowedStream,
        });

        await this.logViolation(userId, ViolationType.PERMISSION, {
          reason: 'location_mismatch',
          currentMap,
          targetStream,
          allowedStream,
        });

        return {
          allowed: false,
          reason: '您当前位置无法向该频道发送消息',
          expectedStream: allowedStream,
          actualStream: targetStream,
        };
      }

      this.logger.debug('权限验证通过', {
        operation: 'validatePermissionDetailed',
        userId,
        targetStream,
        currentMap,
      });

      return {
        allowed: true,
        expectedStream: allowedStream,
        actualStream: targetStream,
      };

    } catch (error) {
      const err = error as Error;
      this.logger.error('权限验证失败', {
        operation: 'validatePermissionDetailed',
        userId,
        targetStream,
        currentMap,
        error: err.message,
        timestamp: new Date().toISOString(),
      }, err.stack);

      // 验证失败时默认拒绝
      return {
        allowed: false,
        reason: '权限验证服务暂时不可用',
      };
    }
  }

  /**
   * 综合消息验证
   * 
   * 功能描述：
   * 对消息进行综合验证，包括内容过滤、频率限制和权限验证
   * 
   * @param userId 用户ID
   * @param content 消息内容
   * @param targetStream 目标Stream
   * @param currentMap 当前地图
   * @returns Promise<{allowed: boolean, reason?: string, filteredContent?: string}>
   */
  async validateMessage(
    userId: string,
    content: string,
    targetStream: string,
    currentMap: string
  ): Promise<{
    allowed: boolean;
    reason?: string;
    filteredContent?: string;
  }> {
    this.logger.debug('开始综合消息验证', {
      operation: 'validateMessage',
      userId,
      contentLength: content?.length || 0,
      targetStream,
      currentMap,
      timestamp: new Date().toISOString(),
    });

    try {
      // 1. 频率限制检查
      const rateLimitResult = await this.checkRateLimitDetailed(userId);
      if (!rateLimitResult.allowed) {
        return {
          allowed: false,
          reason: rateLimitResult.reason,
        };
      }

      // 2. 内容过滤
      const contentResult = await this.filterContent(content);
      if (!contentResult.allowed) {
        return {
          allowed: false,
          reason: contentResult.reason,
        };
      }

      // 3. 权限验证
      const permissionResult = await this.validatePermissionDetailed(userId, targetStream, currentMap);
      if (!permissionResult.allowed) {
        return {
          allowed: false,
          reason: permissionResult.reason,
        };
      }

      this.logger.log('消息验证通过', {
        operation: 'validateMessage',
        userId,
        targetStream,
        currentMap,
        hasFilteredContent: !!contentResult.filtered,
      });

      return {
        allowed: true,
        filteredContent: contentResult.filtered,
      };

    } catch (error) {
      const err = error as Error;
      this.logger.error('综合消息验证失败', {
        operation: 'validateMessage',
        userId,
        error: err.message,
        timestamp: new Date().toISOString(),
      }, err.stack);

      return {
        allowed: false,
        reason: '消息验证失败，请稍后重试',
      };
    }
  }

  /**
   * 记录违规行为
   * 
   * 功能描述：
   * 记录用户的违规行为，用于监控和分析
   * 
   * @param userId 用户ID
   * @param type 违规类型
   * @param details 违规详情
   * @returns Promise<void>
   */
  async logViolation(userId: string, type: ViolationType, details: any): Promise<void> {
    this.logger.warn('记录违规行为', {
      operation: 'logViolation',
      userId,
      type,
      details,
      timestamp: new Date().toISOString(),
    });

    try {
      const violation: ViolationRecord = {
        userId,
        type,
        details,
        timestamp: new Date(),
      };

      // 存储违规记录到Redis（保留7天）
      const violationKey = `${this.VIOLATION_PREFIX}${userId}:${Date.now()}`;
      await this.redisService.setex(violationKey, 7 * 24 * 3600, JSON.stringify(violation));

      // TODO: 可以考虑发送告警通知或更新用户信誉度

    } catch (error) {
      const err = error as Error;
      this.logger.error('记录违规行为失败', {
        operation: 'logViolation',
        userId,
        type,
        error: err.message,
        timestamp: new Date().toISOString(),
      }, err.stack);
    }
  }

  /**
   * 检查是否包含过多重复字符
   * 
   * @param content 消息内容
   * @returns boolean 是否包含过多重复字符
   * @private
   */
  private hasExcessiveRepetition(content: string): boolean {
    // 检查连续重复字符（超过5个相同字符）
    const repetitionPattern = /(.)\1{4,}/;
    if (repetitionPattern.test(content)) {
      return true;
    }

    // 检查重复短语（同一个词重复超过3次）
    const words = content.split(/\s+/);
    const wordCount = new Map<string, number>();
    
    for (const word of words) {
      if (word.length > 1) {
        const normalizedWord = word.toLowerCase();
        const count = (wordCount.get(normalizedWord) || 0) + 1;
        wordCount.set(normalizedWord, count);
        
        if (count > 3) {
          return true;
        }
      }
    }

    // 检查连续重复的短语模式（如 "哈哈哈哈哈"）
    const phrasePattern = /(.{2,})\1{2,}/;
    if (phrasePattern.test(content)) {
      return true;
    }

    return false;
  }

  /**
   * 检查链接安全性
   * 
   * @param content 消息内容
   * @returns {allowed: boolean, reason?: string} 检查结果
   * @private
   */
  private checkLinks(content: string): { allowed: boolean; reason?: string } {
    // 提取所有URL
    const urlPattern = /(https?:\/\/[^\s]+)/gi;
    const urls = content.match(urlPattern);
    
    if (!urls || urls.length === 0) {
      return { allowed: true };
    }

    for (const url of urls) {
      try {
        const urlObj = new URL(url);
        const domain = urlObj.hostname.toLowerCase();

        // 检查黑名单
        for (const blacklisted of this.BLACKLISTED_DOMAINS) {
          if (domain.includes(blacklisted)) {
            return {
              allowed: false,
              reason: '消息包含不允许的链接',
            };
          }
        }

        // 可选：只允许白名单域名
        // const isWhitelisted = this.WHITELISTED_DOMAINS.some(
        //   whitelisted => domain.includes(whitelisted)
        // );
        // if (!isWhitelisted) {
        //   return {
        //     allowed: false,
        //     reason: '消息包含未授权的链接',
        //   };
        // }

      } catch {
        // URL解析失败，可能是格式不正确的链接
        // 暂时允许，避免误判
      }
    }

    return { allowed: true };
  }

  /**
   * 转义正则表达式特殊字符
   * 
   * @param string 要转义的字符串
   * @returns string 转义后的字符串
   * @private
   */
  private escapeRegExp(string: string): string {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  }

  /**
   * 获取用户违规统计
   * 
   * @param userId 用户ID
   * @returns Promise<{totalViolations: number, recentViolations: number, violationsByType: Record<string, number>}>
   */
  async getUserViolationStats(userId: string): Promise<{
    totalViolations: number;
    recentViolations: number;
    violationsByType: Record<string, number>;
  }> {
    try {
      // 获取违规计数
      const countKey = `${this.VIOLATION_COUNT_PREFIX}${userId}`;
      const totalCount = await this.redisService.get(countKey);
      
      // 获取最近24小时的违规记录
      const now = Date.now();
      const oneDayAgo = now - 24 * 60 * 60 * 1000;
      
      // 统计各类型违规
      const violationsByType: Record<string, number> = {
        [ViolationType.CONTENT]: 0,
        [ViolationType.RATE]: 0,
        [ViolationType.PERMISSION]: 0,
      };

      // 注意：这里简化了实现，实际应该使用Redis的有序集合来存储和查询违规记录
      
      return {
        totalViolations: totalCount ? parseInt(totalCount, 10) : 0,
        recentViolations: 0, // 需要更复杂的实现
        violationsByType,
      };

    } catch (error) {
      const err = error as Error;
      this.logger.error('获取用户违规统计失败', {
        operation: 'getUserViolationStats',
        userId,
        error: err.message,
      });

      return {
        totalViolations: 0,
        recentViolations: 0,
        violationsByType: {},
      };
    }
  }

  /**
   * 重置用户频率限制
   * 
   * @param userId 用户ID
   * @returns Promise<void>
   */
  async resetUserRateLimit(userId: string): Promise<void> {
    try {
      const rateLimitKey = `${this.RATE_LIMIT_PREFIX}${userId}`;
      await this.redisService.del(rateLimitKey);

      this.logger.log('重置用户频率限制', {
        operation: 'resetUserRateLimit',
        userId,
        timestamp: new Date().toISOString(),
      });

    } catch (error) {
      const err = error as Error;
      this.logger.error('重置用户频率限制失败', {
        operation: 'resetUserRateLimit',
        userId,
        error: err.message,
      });
    }
  }

  /**
   * 添加敏感词
   * 
   * 功能描述：
   * 动态添加敏感词到过滤列表
   * 
   * @param word 敏感词
   * @param level 过滤级别
   * @param category 分类（可选）
   * @returns void
   */
  addSensitiveWord(word: string, level: 'block' | 'replace', category?: string): void {
    if (!word || !word.trim()) {
      this.logger.warn('添加敏感词失败：词为空', {
        operation: 'addSensitiveWord',
      });
      return;
    }

    // 检查是否已存在
    const exists = this.sensitiveWords.some(
      w => w.word.toLowerCase() === word.toLowerCase()
    );

    if (exists) {
      this.logger.debug('敏感词已存在', {
        operation: 'addSensitiveWord',
        word,
      });
      return;
    }

    this.sensitiveWords.push({
      word: word.trim(),
      level,
      category,
    });

    this.logger.log('添加敏感词成功', {
      operation: 'addSensitiveWord',
      word,
      level,
      category,
      totalCount: this.sensitiveWords.length,
    });
  }

  /**
   * 移除敏感词
   * 
   * @param word 敏感词
   * @returns boolean 是否成功移除
   */
  removeSensitiveWord(word: string): boolean {
    const index = this.sensitiveWords.findIndex(
      w => w.word.toLowerCase() === word.toLowerCase()
    );

    if (index === -1) {
      return false;
    }

    this.sensitiveWords.splice(index, 1);

    this.logger.log('移除敏感词成功', {
      operation: 'removeSensitiveWord',
      word,
      totalCount: this.sensitiveWords.length,
    });

    return true;
  }

  /**
   * 获取敏感词列表
   * 
   * @returns SensitiveWordConfig[] 敏感词配置列表
   */
  getSensitiveWords(): SensitiveWordConfig[] {
    return [...this.sensitiveWords];
  }

  /**
   * 获取过滤服务统计信息
   * 
   * @returns 统计信息
   */
  getFilterStats(): {
    sensitiveWordsCount: number;
    blacklistedDomainsCount: number;
    whitelistedDomainsCount: number;
    rateLimit: number;
    rateLimitWindow: number;
    maxMessageLength: number;
  } {
    return {
      sensitiveWordsCount: this.sensitiveWords.length,
      blacklistedDomainsCount: this.BLACKLISTED_DOMAINS.length,
      whitelistedDomainsCount: this.WHITELISTED_DOMAINS.length,
      rateLimit: this.DEFAULT_RATE_LIMIT,
      rateLimitWindow: this.RATE_LIMIT_WINDOW,
      maxMessageLength: this.MAX_MESSAGE_LENGTH,
    };
  }
}

