/**
 * 错误处理服务
 * 
 * 功能描述：
 * - 实现错误处理和服务降级策略
 * - 提供API超时和重试机制
 * - 实现连接断开自动重连
 * - 系统负载监控和限流
 * 
 * 职责分离：
 * - 错误分类处理：根据错误类型采用不同的处理策略
 * - 重试机制：实现指数退避和智能重试
 * - 降级策略：在服务不可用时提供备用方案
 * 
 * 主要方法：
 * - handleZulipError(): 处理Zulip API错误
 * - enableDegradedMode(): 启用降级模式
 * - retryWithBackoff(): 指数退避重试
 * - handleConnectionError(): 处理连接错误
 * - executeWithTimeout(): 带超时的操作执行
 * - scheduleReconnect(): 调度自动重连
 * 
 * 使用场景：
 * - Zulip服务不可用时的降级处理
 * - API调用失败时的重试机制
 * - 网络连接异常时的恢复策略
 * - 系统负载过高时的限流处理
 * 
 * 依赖模块：
 * - AppLoggerService: 日志记录服务
 * 
 * 最近修改：
 * - 2026-01-12: 代码规范优化 - 修正注释规范和修改记录格式 (修改者: moyin)
 * - 2026-01-07: 代码规范优化 - 更新import路径和注释规范 (修改者: moyin)
 * 
 * @author moyin
 * @version 1.0.2
 * @since 2025-12-25
 * @lastModified 2026-01-12
 */

import { Injectable, OnModuleDestroy, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { EventEmitter } from 'events';

/**
 * 错误类型枚举
 */
export enum ErrorType {
  ZULIP_API_ERROR = 'zulip_api_error',
  CONNECTION_ERROR = 'connection_error',
  TIMEOUT_ERROR = 'timeout_error',
  AUTHENTICATION_ERROR = 'authentication_error',
  RATE_LIMIT_ERROR = 'rate_limit_error',
  UNKNOWN_ERROR = 'unknown_error',
}

/**
 * 错误处理结果接口
 */
export interface ErrorHandlingResult {
  success: boolean;
  shouldRetry: boolean;
  retryAfter?: number; // 重试延迟（毫秒）
  degradedMode?: boolean;
  message: string;
}

/**
 * 重试配置接口
 */
export interface RetryConfig {
  maxRetries: number;
  baseDelay: number;
  maxDelay: number;
  backoffMultiplier: number;
}

/**
 * 超时配置接口
 */
export interface TimeoutConfig {
  timeout: number; // 超时时间（毫秒）
  operation: string; // 操作名称
}

/**
 * 重连配置接口
 */
export interface ReconnectConfig {
  userId: string;
  reconnectCallback: () => Promise<boolean>;
  maxAttempts: number;
  baseDelay: number;
}

/**
 * 重连状态接口
 */
export interface ReconnectState {
  userId: string;
  attempts: number;
  maxAttempts: number;
  isReconnecting: boolean;
  lastAttempt: Date | null;
  nextAttempt: Date | null;
  timeoutId: NodeJS.Timeout | null;
}

/**
 * 服务状态枚举
 */
export enum ServiceStatus {
  NORMAL = 'normal',
  DEGRADED = 'degraded',
  UNAVAILABLE = 'unavailable',
}

/**
 * 系统负载状态枚举
 */
export enum LoadStatus {
  NORMAL = 'normal',
  HIGH = 'high',
  CRITICAL = 'critical',
}

/**
 * 错误处理服务类
 * 
 * 职责：
 * - 统一处理系统错误和异常
 * - 实现重试机制和服务降级
 * - 监控系统健康状态和负载
 * - 提供错误恢复和告警功能
 * 
 * 主要方法：
 * - handleError(): 处理各类错误和异常
 * - retryWithBackoff(): 带退避策略的重试机制
 * - enableDegradedMode(): 启用服务降级模式
 * - getServiceStatus(): 获取服务状态
 * - recordError(): 记录错误统计
 * 
 * 使用场景：
 * - Zulip API调用失败时的错误处理
 * - 网络连接异常的重试机制
 * - 系统负载过高时的服务降级
 * - 错误监控和告警通知
 */
@Injectable()
export class ErrorHandlerService extends EventEmitter implements OnModuleDestroy {
  private readonly logger = new Logger(ErrorHandlerService.name);
  private serviceStatus: ServiceStatus = ServiceStatus.NORMAL;
  private loadStatus: LoadStatus = LoadStatus.NORMAL;
  private degradedModeStartTime: Date | null = null;
  private errorCounts = new Map<ErrorType, number>();
  private lastErrors = new Map<ErrorType, Date>();
  private reconnectStates = new Map<string, ReconnectState>();
  private recoveryCheckInterval: NodeJS.Timeout | null = null;
  private activeConnections = 0;
  private maxConnections: number;

  // 配置项
  private readonly degradedModeEnabled: boolean;
  private readonly autoReconnectEnabled: boolean;
  private readonly maxReconnectAttempts: number;
  private readonly reconnectBaseDelay: number;
  private readonly apiTimeout: number;
  private readonly maxRetries: number;

  // 默认重试配置 - 将在构造函数后更新
  private readonly DEFAULT_RETRY_CONFIG: RetryConfig;

  // 错误阈值配置
  private readonly ERROR_THRESHOLDS: Record<ErrorType, number> = {
    [ErrorType.ZULIP_API_ERROR]: 5,
    [ErrorType.CONNECTION_ERROR]: 3,
    [ErrorType.TIMEOUT_ERROR]: 5,
    [ErrorType.AUTHENTICATION_ERROR]: 1,
    [ErrorType.RATE_LIMIT_ERROR]: 10,
    [ErrorType.UNKNOWN_ERROR]: 10,
  };

  constructor(
    private readonly configService: ConfigService,
  ) {
    super(); // 初始化EventEmitter

    // 从环境变量读取配置
    this.degradedModeEnabled = this.configService.get<string>('ZULIP_DEGRADED_MODE_ENABLED', 'false') === 'true';
    this.autoReconnectEnabled = this.configService.get<string>('ZULIP_AUTO_RECONNECT_ENABLED', 'true') === 'true';
    this.maxReconnectAttempts = this.configService.get<number>('ZULIP_MAX_RECONNECT_ATTEMPTS', 5);
    this.reconnectBaseDelay = this.configService.get<number>('ZULIP_RECONNECT_BASE_DELAY', 5000);
    this.apiTimeout = this.configService.get<number>('ZULIP_API_TIMEOUT', 30000);
    this.maxRetries = this.configService.get<number>('ZULIP_MAX_RETRIES', 3);
    this.maxConnections = this.configService.get<number>('ZULIP_MAX_CONNECTIONS', 1000);

    // 初始化默认重试配置
    this.DEFAULT_RETRY_CONFIG = {
      maxRetries: this.maxRetries,
      baseDelay: 1000,
      maxDelay: 30000,
      backoffMultiplier: 2,
    };

    this.logger.log('ErrorHandlerService初始化完成');
  }

  /**
   * 模块销毁时清理资源
   */
  async onModuleDestroy(): Promise<void> {
    this.logger.log('ErrorHandlerService模块销毁，开始清理资源');

    // 停止恢复检测
    if (this.recoveryCheckInterval) {
      clearInterval(this.recoveryCheckInterval);
      this.recoveryCheckInterval = null;
    }

    // 清理所有重连定时器
    for (const [userId, state] of this.reconnectStates) {
      if (state.timeoutId) {
        clearTimeout(state.timeoutId);
      }
    }
    this.reconnectStates.clear();

    this.logger.log('ErrorHandlerService清理完成');
  }

  /**
   * 处理Zulip API错误
   * 
   * 功能描述：
   * 分析Zulip API错误类型，决定处理策略和是否需要降级
   * 
   * 处理流程：
   * 1. 分析错误类型和严重程度
   * 2. 更新错误统计
   * 3. 决定是否启用降级模式
   * 4. 返回处理建议
   * 
   * @param error 错误对象
   * @param operation 操作名称
   * @returns Promise<ErrorHandlingResult> 错误处理结果
   */
  async handleZulipError(error: any, operation: string): Promise<ErrorHandlingResult> {
    this.logger.warn('处理Zulip API错误', {
      operation: 'handleZulipError',
      targetOperation: operation,
      errorMessage: error?.message || 'Unknown error',
      errorCode: error?.code || 'UNKNOWN',
      timestamp: new Date().toISOString(),
    });

    try {
      // 1. 分析错误类型
      const errorType = this.classifyError(error);
      
      // 2. 更新错误统计
      this.updateErrorStats(errorType);

      // 3. 根据错误类型决定处理策略
      const result = await this.determineHandlingStrategy(errorType, error, operation);

      // 4. 检查是否需要启用降级模式
      if (this.shouldEnableDegradedMode(errorType)) {
        await this.enableDegradedMode();
        result.degradedMode = true;
      }

      this.logger.log(`Zulip错误处理完成: ${operation}`);

      return result;

    } catch (handlingError) {
      const err = handlingError as Error;
      this.logger.error('错误处理过程中发生异常', {
        operation: 'handleZulipError',
        targetOperation: operation,
        originalError: error?.message || 'Unknown error',
        handlingError: err.message,
        timestamp: new Date().toISOString(),
      }, err.stack);

      return {
        success: false,
        shouldRetry: false,
        message: '错误处理失败',
      };
    }
  }

  /**
   * 启用降级模式
   * 
   * 功能描述：
   * 当Zulip服务不可用时，切换到本地聊天模式
   * 
   * 处理流程：
   * 1. 检查降级模式是否启用
   * 2. 更新服务状态
   * 3. 记录降级开始时间
   * 4. 通知相关组件
   * 5. 启动恢复检测
   * 
   * @returns Promise<void>
   */
  async enableDegradedMode(): Promise<void> {
    // 检查降级模式是否启用
    if (!this.degradedModeEnabled) {
      this.logger.log('降级模式已禁用，跳过启用');
      return;
    }

    if (this.serviceStatus === ServiceStatus.DEGRADED) {
      this.logger.debug('服务已处于降级模式', {
        operation: 'enableDegradedMode',
      });
      return;
    }

    this.serviceStatus = ServiceStatus.DEGRADED;
    this.degradedModeStartTime = new Date();

    this.logger.warn('启用Zulip服务降级模式', {
      operation: 'enableDegradedMode',
      previousStatus: ServiceStatus.NORMAL,
      degradedModeStartTime: this.degradedModeStartTime,
      timestamp: new Date().toISOString(),
    });

    // 发出降级模式启用事件
    this.emit('degraded_mode_enabled', {
      startTime: this.degradedModeStartTime,
    });

    // 启动恢复检测
    this.startRecoveryDetection();
  }

  /**
   * 恢复正常模式
   * 
   * @returns Promise<void>
   */
  async enableNormalMode(): Promise<void> {
    if (this.serviceStatus === ServiceStatus.NORMAL) {
      return;
    }

    const previousStatus = this.serviceStatus;
    const degradedDuration = this.degradedModeStartTime 
      ? Date.now() - this.degradedModeStartTime.getTime()
      : 0;

    this.serviceStatus = ServiceStatus.NORMAL;
    this.degradedModeStartTime = null;

    this.logger.log('恢复Zulip服务正常模式');

    // 清理错误统计
    this.resetErrorStats();

    // 通知其他组件恢复正常模式
    this.emit('service-recovered', {
      timestamp: new Date(),
      previousMode: this.loadStatus,
    });
  }

  /**
   * 指数退避重试
   * 
   * 功能描述：
   * 使用指数退避算法进行重试，避免对服务造成过大压力
   * 
   * @param operation 要重试的操作函数
   * @param config 重试配置
   * @returns Promise<T> 操作结果
   */
  async retryWithBackoff<T>(
    operation: () => Promise<T>,
    config: Partial<RetryConfig> = {}
  ): Promise<T> {
    const retryConfig = { ...this.DEFAULT_RETRY_CONFIG, ...config };
    let lastError: any;

    this.logger.debug('开始指数退避重试', {
      operation: 'retryWithBackoff',
      maxRetries: retryConfig.maxRetries,
      baseDelay: retryConfig.baseDelay,
      timestamp: new Date().toISOString(),
    });

    for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt++) {
      try {
        const result = await operation();
        
        if (attempt > 0) {
          this.logger.log(`重试操作成功，尝试次数: ${attempt + 1}`);
        }

        return result;

      } catch (error) {
        const err = error as Error;
        lastError = error;

        if (attempt === retryConfig.maxRetries) {
          this.logger.error('重试操作最终失败', {
            operation: 'retryWithBackoff',
            totalAttempts: attempt + 1,
            error: err.message,
            timestamp: new Date().toISOString(),
          }, err.stack);
          break;
        }

        // 计算延迟时间
        const delay = Math.min(
          retryConfig.baseDelay * Math.pow(retryConfig.backoffMultiplier, attempt),
          retryConfig.maxDelay
        );

        this.logger.warn('重试操作失败，等待后重试', {
          operation: 'retryWithBackoff',
          attempt: attempt + 1,
          totalAttempts: retryConfig.maxRetries + 1,
          delay,
          error: err.message,
          timestamp: new Date().toISOString(),
        });

        // 等待指定时间
        await this.sleep(delay);
      }
    }

    throw lastError;
  }

  /**
   * 处理连接错误
   * 
   * @param error 连接错误
   * @param connectionType 连接类型
   * @returns Promise<ErrorHandlingResult>
   */
  async handleConnectionError(error: any, connectionType: string): Promise<ErrorHandlingResult> {
    this.logger.warn('处理连接错误', {
      operation: 'handleConnectionError',
      connectionType,
      errorMessage: error?.message || 'Unknown connection error',
      timestamp: new Date().toISOString(),
    });

    const errorType = ErrorType.CONNECTION_ERROR;
    this.updateErrorStats(errorType);

    // 连接错误通常需要重试
    const result: ErrorHandlingResult = {
      success: false,
      shouldRetry: true,
      retryAfter: 5000, // 5秒后重试
      message: `${connectionType}连接错误，将自动重试`,
    };

    // 如果连接错误过多，启用降级模式
    if (this.shouldEnableDegradedMode(errorType)) {
      await this.enableDegradedMode();
      result.degradedMode = true;
    }

    return result;
  }

  /**
   * 检查服务健康状态
   * 
   * @returns Promise<{status: ServiceStatus, details: any}>
   */
  async checkServiceHealth(): Promise<{
    status: ServiceStatus;
    details: any;
  }> {
    const details = {
      serviceStatus: this.serviceStatus,
      degradedModeStartTime: this.degradedModeStartTime,
      errorCounts: Object.fromEntries(this.errorCounts),
      lastErrors: Object.fromEntries(
        Array.from(this.lastErrors.entries()).map(([type, date]) => [type, date.toISOString()])
      ),
    };

    this.logger.debug('检查服务健康状态', {
      operation: 'checkServiceHealth',
      status: this.serviceStatus,
      errorCount: this.errorCounts.size,
      timestamp: new Date().toISOString(),
    });

    return {
      status: this.serviceStatus,
      details,
    };
  }

  /**
   * 重置错误统计
   * 
   * @returns void
   */
  resetErrorStats(): void {
    this.errorCounts.clear();
    this.lastErrors.clear();

    this.logger.log('重置错误统计');
  }

  /**
   * 获取错误统计信息
   * 
   * @returns 错误统计信息
   */
  getErrorStats(): {
    serviceStatus: ServiceStatus;
    degradedModeStartTime: Date | null;
    errorCounts: Record<string, number>;
    recentErrors: Record<string, string>;
  } {
    return {
      serviceStatus: this.serviceStatus,
      degradedModeStartTime: this.degradedModeStartTime,
      errorCounts: Object.fromEntries(this.errorCounts),
      recentErrors: Object.fromEntries(
        Array.from(this.lastErrors.entries()).map(([type, date]) => [type, date.toISOString()])
      ),
    };
  }

  /**
   * 分类错误类型
   * 
   * @param error 错误对象
   * @returns ErrorType 错误类型
   * @private
   */
  private classifyError(error: any): ErrorType {
    if (!error) {
      return ErrorType.UNKNOWN_ERROR;
    }

    const message = error.message?.toLowerCase() || '';
    const code = error.code;

    // 根据错误码和消息分类
    if (code === 401 || message.includes('unauthorized') || message.includes('authentication')) {
      return ErrorType.AUTHENTICATION_ERROR;
    }

    if (code === 429 || message.includes('rate limit') || message.includes('too many requests')) {
      return ErrorType.RATE_LIMIT_ERROR;
    }

    if (code === 'ECONNREFUSED' || code === 'ENOTFOUND' || message.includes('connection')) {
      return ErrorType.CONNECTION_ERROR;
    }

    if (code === 'ETIMEDOUT' || message.includes('timeout')) {
      return ErrorType.TIMEOUT_ERROR;
    }

    if (code >= 400 && code < 500) {
      return ErrorType.ZULIP_API_ERROR;
    }

    return ErrorType.UNKNOWN_ERROR;
  }

  /**
   * 更新错误统计
   * 
   * @param errorType 错误类型
   * @private
   */
  private updateErrorStats(errorType: ErrorType): void {
    const currentCount = this.errorCounts.get(errorType) || 0;
    this.errorCounts.set(errorType, currentCount + 1);
    this.lastErrors.set(errorType, new Date());

    this.logger.debug('更新错误统计', {
      operation: 'updateErrorStats',
      errorType,
      newCount: currentCount + 1,
    });
  }

  /**
   * 确定处理策略
   * 
   * @param errorType 错误类型
   * @param error 错误对象
   * @param operation 操作名称
   * @returns Promise<ErrorHandlingResult>
   * @private
   */
  private async determineHandlingStrategy(
    errorType: ErrorType,
    error: any,
    operation: string
  ): Promise<ErrorHandlingResult> {
    switch (errorType) {
      case ErrorType.AUTHENTICATION_ERROR:
        return {
          success: false,
          shouldRetry: false,
          message: 'API Key认证失败，请检查配置',
        };

      case ErrorType.RATE_LIMIT_ERROR:
        return {
          success: false,
          shouldRetry: true,
          retryAfter: 60000, // 1分钟后重试
          message: '触发频率限制，稍后重试',
        };

      case ErrorType.CONNECTION_ERROR:
        return {
          success: false,
          shouldRetry: true,
          retryAfter: 5000, // 5秒后重试
          message: '连接错误，将自动重试',
        };

      case ErrorType.TIMEOUT_ERROR:
        return {
          success: false,
          shouldRetry: true,
          retryAfter: 3000, // 3秒后重试
          message: '请求超时，将自动重试',
        };

      case ErrorType.ZULIP_API_ERROR:
        return {
          success: false,
          shouldRetry: error?.code >= 500, // 服务器错误可以重试
          retryAfter: 2000,
          message: `Zulip API错误: ${error?.message || 'Unknown API error'}`,
        };

      default:
        return {
          success: false,
          shouldRetry: false,
          message: `未知错误: ${error?.message || 'Unknown error'}`,
        };
    }
  }

  /**
   * 判断是否应该启用降级模式
   * 
   * @param errorType 错误类型
   * @returns boolean
   * @private
   */
  private shouldEnableDegradedMode(errorType: ErrorType): boolean {
    const threshold = this.ERROR_THRESHOLDS[errorType];
    const currentCount = this.errorCounts.get(errorType) || 0;

    return threshold && currentCount >= threshold;
  }

  /**
   * 启动恢复检测
   * 
   * 功能描述：
   * 定期检查Zulip服务是否恢复，如果恢复则切换回正常模式
   * 
   * @private
   */
  private startRecoveryDetection(): void {
    // 如果已有恢复检测在运行，先停止
    if (this.recoveryCheckInterval) {
      clearInterval(this.recoveryCheckInterval);
    }

    this.logger.log('启动服务恢复检测');

    // 每30秒检查一次服务状态
    this.recoveryCheckInterval = setInterval(async () => {
      if (this.serviceStatus !== ServiceStatus.DEGRADED) {
        // 如果不在降级模式，停止检测
        if (this.recoveryCheckInterval) {
          clearInterval(this.recoveryCheckInterval);
          this.recoveryCheckInterval = null;
        }
        return;
      }

      this.logger.debug('执行服务恢复检测', {
        operation: 'recoveryCheck',
        degradedDuration: this.degradedModeStartTime 
          ? Date.now() - this.degradedModeStartTime.getTime()
          : 0,
      });

      // 检查错误计数是否已重置（表示服务可能已恢复）
      const totalErrors = Array.from(this.errorCounts.values()).reduce((a, b) => a + b, 0);
      
      // 如果最近没有新错误，尝试恢复
      if (totalErrors === 0) {
        this.logger.log('错误计数已清零，尝试恢复正常模式');
        
        // 发出恢复检测事件，让外部服务进行实际的健康检查
        this.emit('recovery_check', {
          degradedDuration: this.degradedModeStartTime 
            ? Date.now() - this.degradedModeStartTime.getTime()
            : 0,
        });
      }
    }, 30000);
  }

  /**
   * 休眠指定毫秒数
   * 
   * @param ms 毫秒数
   * @returns Promise<void>
   * @private
   */
  private sleep(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  /**
   * 带超时的操作执行
   * 
   * 功能描述：
   * 执行操作并在超时时自动取消，返回超时错误
   * 
   * 处理流程：
   * 1. 创建超时Promise
   * 2. 与操作Promise竞争
   * 3. 超时则抛出超时错误
   * 4. 成功则返回操作结果
   * 
   * @param operation 要执行的操作函数
   * @param config 超时配置
   * @returns Promise<T> 操作结果
   * 
   * @throws Error 当操作超时时
   */
  async executeWithTimeout<T>(
    operation: () => Promise<T>,
    config: TimeoutConfig
  ): Promise<T> {
    this.logger.debug('开始带超时的操作执行', {
      operation: 'executeWithTimeout',
      targetOperation: config.operation,
      timeout: config.timeout,
      timestamp: new Date().toISOString(),
    });

    const timeoutPromise = new Promise<never>((_, reject) => {
      setTimeout(() => {
        reject(new Error(`操作超时: ${config.operation} (${config.timeout}ms)`));
      }, config.timeout);
    });

    try {
      const result = await Promise.race([operation(), timeoutPromise]);
      
      this.logger.debug('操作执行成功', {
        operation: 'executeWithTimeout',
        targetOperation: config.operation,
        timestamp: new Date().toISOString(),
      });

      return result;

    } catch (error) {
      const err = error as Error;
      const isTimeout = err.message.includes('操作超时');
      
      if (isTimeout) {
        this.updateErrorStats(ErrorType.TIMEOUT_ERROR);
        
        this.logger.warn('操作执行超时', {
          operation: 'executeWithTimeout',
          targetOperation: config.operation,
          timeout: config.timeout,
          timestamp: new Date().toISOString(),
        });
      }

      throw error;
    }
  }

  /**
   * 带超时和重试的操作执行
   * 
   * 功能描述：
   * 结合超时控制和指数退避重试的操作执行
   * 
   * @param operation 要执行的操作函数
   * @param timeoutConfig 超时配置
   * @param retryConfig 重试配置
   * @returns Promise<T> 操作结果
   */
  async executeWithTimeoutAndRetry<T>(
    operation: () => Promise<T>,
    timeoutConfig: TimeoutConfig,
    retryConfig: Partial<RetryConfig> = {}
  ): Promise<T> {
    const wrappedOperation = () => this.executeWithTimeout(operation, timeoutConfig);
    return this.retryWithBackoff(wrappedOperation, retryConfig);
  }

  /**
   * 调度自动重连
   * 
   * 功能描述：
   * 当连接断开时，调度自动重连尝试
   * 
   * 处理流程：
   * 1. 检查自动重连是否启用
   * 2. 检查是否已在重连中
   * 3. 创建重连状态
   * 4. 使用指数退避调度重连
   * 5. 重连成功则清理状态
   * 6. 达到最大尝试次数则放弃
   * 
   * @param config 重连配置
   * @returns Promise<boolean> 是否成功调度重连
   */
  async scheduleReconnect(config: ReconnectConfig): Promise<boolean> {
    // 检查自动重连是否启用
    if (!this.autoReconnectEnabled) {
      this.logger.log(`自动重连已禁用，跳过调度: ${config.userId}`);
      return false;
    }

    const { userId, reconnectCallback } = config;
    // 使用配置的值或传入的值
    const maxAttempts = config.maxAttempts || this.maxReconnectAttempts;
    const baseDelay = config.baseDelay || this.reconnectBaseDelay;

    this.logger.log(`调度自动重连: ${userId}`);

    // 检查是否已在重连中
    const existingState = this.reconnectStates.get(userId);
    if (existingState?.isReconnecting) {
      this.logger.log(`用户已在重连中，跳过调度: ${userId}`);
      return false;
    }

    // 创建重连状态
    const state: ReconnectState = {
      userId,
      attempts: 0,
      maxAttempts,
      isReconnecting: true,
      lastAttempt: null,
      nextAttempt: null,
      timeoutId: null,
    };
    this.reconnectStates.set(userId, state);

    // 执行重连尝试
    const attemptReconnect = async (): Promise<void> => {
      state.attempts++;
      state.lastAttempt = new Date();

      this.logger.log(`执行重连尝试: ${userId} (${state.attempts}/${state.maxAttempts})`);

      try {
        const success = await reconnectCallback();

        if (success) {
          this.logger.log(`重连成功: ${userId}`);

          // 清理重连状态
          this.cancelReconnect(userId);
          
          // 发出重连成功事件
          this.emit('reconnect_success', { userId, attempts: state.attempts });
          return;
        }

        // 重连失败，检查是否继续尝试
        if (state.attempts >= state.maxAttempts) {
          this.logger.warn('重连达到最大尝试次数，放弃重连', {
            operation: 'attemptReconnect',
            userId,
            totalAttempts: state.attempts,
            timestamp: new Date().toISOString(),
          });

          // 清理重连状态
          this.cancelReconnect(userId);
          
          // 发出重连失败事件
          this.emit('reconnect_failed', { userId, attempts: state.attempts });
          return;
        }

        // 计算下次重连延迟（指数退避）
        const delay = Math.min(
          baseDelay * Math.pow(2, state.attempts - 1),
          30000 // 最大延迟30秒
        );
        state.nextAttempt = new Date(Date.now() + delay);

        this.logger.log(`重连失败，等待后重试: ${userId}`);

        // 调度下次重连
        state.timeoutId = setTimeout(attemptReconnect, delay);

      } catch (error) {
        const err = error as Error;
        this.logger.error('重连尝试异常', {
          operation: 'attemptReconnect',
          userId,
          attempt: state.attempts,
          error: err.message,
          timestamp: new Date().toISOString(),
        }, err.stack);

        // 检查是否继续尝试
        if (state.attempts >= state.maxAttempts) {
          this.cancelReconnect(userId);
          this.emit('reconnect_failed', { userId, attempts: state.attempts, error: err.message });
          return;
        }

        // 调度下次重连
        const delay = Math.min(baseDelay * Math.pow(2, state.attempts - 1), 30000);
        state.nextAttempt = new Date(Date.now() + delay);
        state.timeoutId = setTimeout(attemptReconnect, delay);
      }
    };

    // 立即开始第一次重连尝试
    attemptReconnect();

    return true;
  }

  /**
   * 取消重连
   * 
   * @param userId 用户ID
   */
  cancelReconnect(userId: string): void {
    const state = this.reconnectStates.get(userId);
    if (state) {
      if (state.timeoutId) {
        clearTimeout(state.timeoutId);
      }
      this.reconnectStates.delete(userId);

      this.logger.log(`取消重连: ${userId}`);
    }
  }

  /**
   * 获取重连状态
   * 
   * @param userId 用户ID
   * @returns ReconnectState | null 重连状态
   */
  getReconnectState(userId: string): ReconnectState | null {
    return this.reconnectStates.get(userId) || null;
  }

  /**
   * 检查是否应该限制新连接
   * 
   * 功能描述：
   * 当系统负载过高时，限制新连接
   * 
   * @returns boolean 是否应该限制
   */
  shouldLimitNewConnections(): boolean {
    return this.loadStatus === LoadStatus.CRITICAL || 
           this.activeConnections >= this.maxConnections;
  }

  /**
   * 更新活跃连接数
   * 
   * @param delta 变化量（正数增加，负数减少）
   */
  updateActiveConnections(delta: number): void {
    this.activeConnections = Math.max(0, this.activeConnections + delta);
    
    // 更新负载状态
    const loadRatio = this.activeConnections / this.maxConnections;
    if (loadRatio >= 0.9) {
      this.loadStatus = LoadStatus.CRITICAL;
    } else if (loadRatio >= 0.7) {
      this.loadStatus = LoadStatus.HIGH;
    } else {
      this.loadStatus = LoadStatus.NORMAL;
    }

    this.logger.debug('更新活跃连接数', {
      operation: 'updateActiveConnections',
      activeConnections: this.activeConnections,
      maxConnections: this.maxConnections,
      loadStatus: this.loadStatus,
    });
  }

  /**
   * 获取负载状态
   * 
   * @returns LoadStatus 当前负载状态
   */
  getLoadStatus(): LoadStatus {
    return this.loadStatus;
  }

  /**
   * 设置最大连接数
   * 
   * @param max 最大连接数
   */
  setMaxConnections(max: number): void {
    this.maxConnections = max;
    this.logger.log(`设置最大连接数: ${max}`);
  }

  /**
   * 获取服务状态
   * 
   * @returns ServiceStatus 当前服务状态
   */
  getServiceStatus(): ServiceStatus {
    return this.serviceStatus;
  }

  /**
   * 检查服务是否可用
   * 
   * @returns boolean 服务是否可用
   */
  isServiceAvailable(): boolean {
    return this.serviceStatus !== ServiceStatus.UNAVAILABLE;
  }

  /**
   * 检查是否处于降级模式
   * 
   * @returns boolean 是否处于降级模式
   */
  isDegradedMode(): boolean {
    return this.serviceStatus === ServiceStatus.DEGRADED;
  }

  /**
   * 检查降级模式是否启用
   * 
   * @returns boolean 降级模式是否启用
   */
  isDegradedModeEnabled(): boolean {
    return this.degradedModeEnabled;
  }

  /**
   * 检查自动重连是否启用
   * 
   * @returns boolean 自动重连是否启用
   */
  isAutoReconnectEnabled(): boolean {
    return this.autoReconnectEnabled;
  }

  /**
   * 获取API超时配置
   * 
   * @returns number API超时时间（毫秒）
   */
  getApiTimeout(): number {
    return this.apiTimeout;
  }

  /**
   * 获取最大重试次数配置
   * 
   * @returns number 最大重试次数
   */
  getMaxRetries(): number {
    return this.maxRetries;
  }

  /**
   * 获取最大重连尝试次数配置
   * 
   * @returns number 最大重连尝试次数
   */
  getMaxReconnectAttempts(): number {
    return this.maxReconnectAttempts;
  }

  /**
   * 获取重连基础延迟配置
   * 
   * @returns number 重连基础延迟（毫秒）
   */
  getReconnectBaseDelay(): number {
    return this.reconnectBaseDelay;
  }

  /**
   * 获取默认重试配置
   * 
   * @returns RetryConfig 默认重试配置
   */
  getDefaultRetryConfig(): RetryConfig {
    return { ...this.DEFAULT_RETRY_CONFIG };
  }

  /**
   * 获取完整配置信息
   * 
   * @returns 配置信息对象
   */
  getConfig(): {
    degradedModeEnabled: boolean;
    autoReconnectEnabled: boolean;
    maxReconnectAttempts: number;
    reconnectBaseDelay: number;
    apiTimeout: number;
    maxRetries: number;
    maxConnections: number;
  } {
    return {
      degradedModeEnabled: this.degradedModeEnabled,
      autoReconnectEnabled: this.autoReconnectEnabled,
      maxReconnectAttempts: this.maxReconnectAttempts,
      reconnectBaseDelay: this.reconnectBaseDelay,
      apiTimeout: this.apiTimeout,
      maxRetries: this.maxRetries,
      maxConnections: this.maxConnections,
    };
  }
}

