/**
 * 🏦 统一账户管理器 v2.0 - Delta中性控制平面账户管理核心
 *
 * 基于tasks规范重构的统一账户管理器，支持：
 * - Delta中性控制平面账户模型集成
 * - 多平台多账户统一管理（Pacifica、Aster、Binance）
 * - 企业级风险包络集成
 * - 多平台认证策略支持
 * - 资金利用率目标管理（50%-80%）
 * - 实时状态同步和账户健康监控
 * - WebSocket + HTTP双模式数据更新
 */

import { EventEmitter } from 'events'
import { ExchangeAccount, ExchangeAccountConfig, AccountMetrics, DeltaControlParams } from './ExchangeAccount'
import { RiskEnvelope, RiskEnvelopeConfig } from './RiskEnvelope'
import { TradingService, ServiceStatus, AccountState } from '../shared/types/index'
import { logger } from '../shared/utils/logger'

/**
 * 多平台账户配置
 */
export interface UnifiedAccountConfig extends ExchangeAccountConfig {
  // 账户元信息
  alias?: string // 显示别名
  enabled: boolean // 是否启用
  priority: number // 优先级 (1-10)

  // 交易和对冲控制
  tradingEnabled: boolean // 是否允许交易
  hedgingEnabled: boolean // 是否允许参与对冲

  // 风险控制参数
  maxDailyVolumeUsd: number // 最大日交易量
  emergencyContactInfo?: string // 紧急联系信息

  // 平台特定配置
  proxySessionId?: string // 代理会话ID
  authenticationMethod: 'ed25519' | 'eip191' | 'hmac' // 认证方法
  requiresProxy: boolean // 是否需要代理
  sessionManagement: boolean // 是否需要会话管理
}

/**
 * 账户摘要信息
 */
export interface AccountSummary {
  accountId: string
  exchange: 'pacifica' | 'aster' | 'binance'
  alias?: string
  status: 'active' | 'paused' | 'emergency' | 'offline' | 'error'

  // 财务指标
  metrics: AccountMetrics
  deltaParams: DeltaControlParams

  // 实时状态
  isOnline: boolean
  lastHeartbeat: Date
  lastTradeTime?: Date
  connectionQuality: 'excellent' | 'good' | 'poor' | 'disconnected'

  // 风险状态
  riskEnvelopeId?: string
  riskViolations: number
  emergencyMode: boolean

  // 配置信息
  config: UnifiedAccountConfig

  // 性能指标
  totalEquityUsd: number
  dailyVolumeUsd: number
  openOrdersCount: number
  lastUpdateTime: Date

  // 错误信息
  errors: string[]
  warnings: string[]
}

/**
 * 对冲组配置
 */
export interface HedgingGroup {
  groupId: string
  name: string
  strategy: 'delta-neutral' | 'cross-platform-arbitrage' | 'funding-rate-arbitrage'
  accounts: string[] // 参与账户ID列表
  maxExposureUsd: number // 最大敞口
  targetUtilization: number // 目标利用率
  enabled: boolean
  priority: number
  createdAt: Date
  lastRebalance?: Date
}

/**
 * 账户性能指标
 */
export interface AccountPerformanceMetrics {
  accountId: string

  // Delta中性指标
  avgDeltaDeviation: number // 平均Delta偏差
  deltaViolationCount: number // Delta违规次数
  maxDeltaDeviation: number // 最大Delta偏差
  deltaControlEfficiency: number // Delta控制效率 (0-1)

  // 利用率指标
  avgUtilization: number // 平均利用率
  utilizationStability: number // 利用率稳定性
  targetUtilizationHitRate: number // 目标利用率命中率

  // 交易指标
  totalTrades: number // 总交易数
  successfulTrades: number // 成功交易数
  avgExecutionTime: number // 平均执行时间

  // 风险指标
  maxDrawdown: number // 最大回撤
  sharpeRatio: number // 夏普比率
  riskAdjustedReturn: number // 风险调整收益

  // 时间范围
  periodStart: Date
  periodEnd: Date
}

/**
 * 统一账户管理器
 */
export class UnifiedAccountManager extends EventEmitter implements TradingService {
  private status: 'stopped' | 'initializing' | 'running' | 'stopping' | 'error' = 'stopped'
  private lastStatusChange = Date.now()

  // 核心存储
  private accounts: Map<string, ExchangeAccount> = new Map()
  private accountConfigs: Map<string, UnifiedAccountConfig> = new Map()
  private hedgingGroups: Map<string, HedgingGroup> = new Map()
  private performanceMetrics: Map<string, AccountPerformanceMetrics> = new Map()

  // 运行时状态
  private updateIntervals: Map<string, NodeJS.Timeout> = new Map()
  private connectionHealthChecks: Map<string, NodeJS.Timeout> = new Map()
  private lastAccountUpdates: Map<string, Date> = new Map()

  // 配置参数
  private readonly config = {
    accountUpdateInterval: 30000, // 30秒账户状态更新
    healthCheckInterval: 10000, // 10秒健康检查
    performanceReportInterval: 300000, // 5分钟性能报告
    maxAccountsPerGroup: 10, // 每组最大账户数
    deltaThreshold: 0.0005, // 全局Delta阈值
    utilizationTargetMin: 0.5, // 50%最小利用率
    utilizationTargetMax: 0.8, // 80%最大利用率
    emergencyResponseTime: 5000, // 5秒紧急响应时间
  }

  constructor() {
    super()
    this.setupEventHandlers()
  }

  /**
   * 初始化统一账户管理器
   */
  async initialize(): Promise<void> {
    logger.info('🏦 UnifiedAccountManager v2.0 初始化开始')
    this.status = 'initializing'
    this.lastStatusChange = Date.now()

    try {
      // 1. 验证系统配置
      await this.validateSystemConfiguration()

      // 2. 初始化所有注册账户
      await this.initializeRegisteredAccounts()

      // 3. 设置监控和健康检查
      this.setupMonitoringAndHealthChecks()

      this.status = 'running'
      this.lastStatusChange = Date.now()

      logger.info('✅ UnifiedAccountManager v2.0 初始化完成')
      logger.info(`📊 管理账户数: ${this.accounts.size}`)
      logger.info(`🔗 对冲组数: ${this.hedgingGroups.size}`)
      logger.info(`🎯 Delta阈值: ±${this.config.deltaThreshold} BTC`)
      logger.info(`📈 利用率目标: ${this.config.utilizationTargetMin * 100}-${this.config.utilizationTargetMax * 100}%`)
    } catch (error) {
      this.status = 'error'
      this.lastStatusChange = Date.now()
      logger.error('❌ UnifiedAccountManager 初始化失败:', error)
      throw error
    }
  }

  /**
   * 启动统一账户管理器
   */
  async start(): Promise<void> {
    if (this.status !== 'running') {
      throw new Error('UnifiedAccountManager 必须先完成初始化')
    }

    logger.info('🚀 UnifiedAccountManager v2.0 启动中')

    try {
      // 1. 启动所有账户的定期更新
      this.startAccountUpdates()

      // 2. 启动健康检查
      this.startHealthChecks()

      // 3. 启动性能监控
      this.startPerformanceMonitoring()

      // 4. 执行初始状态同步
      await this.performInitialStateSynchronization()

      logger.info('✅ UnifiedAccountManager v2.0 启动完成')
      logger.info(`🔄 账户更新间隔: ${this.config.accountUpdateInterval}ms`)
      logger.info(`💚 健康检查间隔: ${this.config.healthCheckInterval}ms`)
      logger.info(`📊 性能报告间隔: ${this.config.performanceReportInterval}ms`)

      this.emit('manager-started', {
        timestamp: new Date(),
        accountCount: this.accounts.size,
        hedgingGroupCount: this.hedgingGroups.size,
      })
    } catch (error) {
      this.status = 'error'
      this.lastStatusChange = Date.now()
      logger.error('❌ UnifiedAccountManager 启动失败:', error)
      throw error
    }
  }

  /**
   * 停止统一账户管理器
   */
  async stop(): Promise<void> {
    logger.info('🛑 UnifiedAccountManager v2.0 停止中')
    this.status = 'stopping'
    this.lastStatusChange = Date.now()

    try {
      // 1. 停止所有定时器
      this.stopAllTimers()

      // 2. 执行优雅关闭
      await this.performGracefulShutdown()

      // 3. 清理资源
      this.cleanup()

      this.status = 'stopped'
      this.lastStatusChange = Date.now()

      logger.info('✅ UnifiedAccountManager v2.0 已安全停止')

      this.emit('manager-stopped', {
        timestamp: new Date(),
        finalAccountCount: this.accounts.size,
      })
    } catch (error) {
      this.status = 'error'
      this.lastStatusChange = Date.now()
      logger.error('❌ UnifiedAccountManager 停止失败:', error)
      throw error
    }
  }

  /**
   * 添加账户
   */
  async addAccount(config: UnifiedAccountConfig): Promise<void> {
    logger.info(`📝 添加账户: ${config.accountId} (${config.exchange})`)

    try {
      // 1. 验证账户配置
      this.validateAccountConfig(config)

      // 2. 检查重复
      if (this.accounts.has(config.accountId)) {
        throw new Error(`账户 ${config.accountId} 已存在`)
      }

      // 3. 创建ExchangeAccount实例
      const exchangeAccountConfig: ExchangeAccountConfig = {
        accountId: config.accountId,
        exchange: config.exchange,
        accountName: config.alias || config.accountId,
        publicKey: config.publicKey,
        privateKey: config.privateKey,
        proxyProfile: config.proxyProfile,
        utilizationTargetMin: config.utilizationTargetMin,
        utilizationTargetMax: config.utilizationTargetMax,
        deltaThreshold: config.deltaThreshold,
        maxPositionValue: config.maxPositionValue,
        stopLossConfigId: `stop-loss-${config.accountId}`,
        status: config.enabled ? 'active' : 'paused',
      }

      const account = new ExchangeAccount(exchangeAccountConfig)

      // 4. 存储账户和配置
      this.accounts.set(config.accountId, account)
      this.accountConfigs.set(config.accountId, config)

      // 5. 初始化性能指标
      this.initializeAccountPerformanceMetrics(config.accountId)

      // 6. 如果管理器正在运行，立即启动此账户的监控
      if (this.status === 'running') {
        this.startAccountMonitoring(config.accountId)
      }

      logger.info(`✅ 账户 ${config.accountId} 添加成功`)

      this.emit('account-added', {
        accountId: config.accountId,
        exchange: config.exchange,
        timestamp: new Date(),
      })
    } catch (error) {
      logger.error(`❌ 添加账户 ${config.accountId} 失败:`, error)
      throw error
    }
  }

  /**
   * 移除账户
   */
  async removeAccount(accountId: string): Promise<void> {
    logger.info(`🗑️ 移除账户: ${accountId}`)

    try {
      const account = this.accounts.get(accountId)
      if (!account) {
        throw new Error(`账户 ${accountId} 不存在`)
      }

      // 1. 检查是否在对冲组中
      const hedgingGroupsWithAccount = Array.from(this.hedgingGroups.values()).filter(group =>
        group.accounts.includes(accountId),
      )

      if (hedgingGroupsWithAccount.length > 0) {
        logger.warn(`⚠️ 账户 ${accountId} 属于 ${hedgingGroupsWithAccount.length} 个对冲组，将从所有组中移除`)

        for (const group of hedgingGroupsWithAccount) {
          await this.removeAccountFromHedgingGroup(group.groupId, accountId)
        }
      }

      // 2. 停止监控
      this.stopAccountMonitoring(accountId)

      // 3. 清理数据
      this.accounts.delete(accountId)
      this.accountConfigs.delete(accountId)
      this.performanceMetrics.delete(accountId)
      this.lastAccountUpdates.delete(accountId)

      logger.info(`✅ 账户 ${accountId} 移除成功`)

      this.emit('account-removed', {
        accountId,
        timestamp: new Date(),
      })
    } catch (error) {
      logger.error(`❌ 移除账户 ${accountId} 失败:`, error)
      throw error
    }
  }

  /**
   * 获取账户
   */
  getAccount(accountId: string): ExchangeAccount | undefined {
    return this.accounts.get(accountId)
  }

  /**
   * 获取所有账户
   */
  getAllAccounts(): ExchangeAccount[] {
    return Array.from(this.accounts.values())
  }

  /**
   * 获取活跃账户
   */
  getActiveAccounts(): ExchangeAccount[] {
    return this.getAllAccounts().filter(account => account.getConfig().status === 'active')
  }

  /**
   * 获取需要对冲的账户
   */
  getAccountsNeedingHedge(): ExchangeAccount[] {
    return this.getAllAccounts().filter(account => account.needsEmergencyHedge() || account.needsRebalance())
  }

  /**
   * 获取账户摘要
   */
  getAccountSummary(accountId: string): AccountSummary | undefined {
    const account = this.accounts.get(accountId)
    const config = this.accountConfigs.get(accountId)

    if (!account || !config) {
      return undefined
    }

    const lastUpdate = this.lastAccountUpdates.get(accountId) || new Date(0)
    const timeSinceUpdate = Date.now() - lastUpdate.getTime()

    // 确定连接质量
    let connectionQuality: 'excellent' | 'good' | 'poor' | 'disconnected' = 'disconnected'
    if (timeSinceUpdate < 30000) connectionQuality = 'excellent'
    else if (timeSinceUpdate < 60000) connectionQuality = 'good'
    else if (timeSinceUpdate < 180000) connectionQuality = 'poor'

    const summary: AccountSummary = {
      accountId: account.getConfig().accountId,
      exchange: account.getConfig().exchange,
      alias: config.alias,
      status: account.getConfig().status,

      metrics: account.getMetrics(),
      deltaParams: account.getDeltaParams(),

      isOnline: connectionQuality !== 'disconnected',
      lastHeartbeat: lastUpdate,
      connectionQuality,

      riskEnvelopeId: config.stopLossConfigId,
      riskViolations: 0, // 需要从RiskEnvelope获取
      emergencyMode: account.getConfig().status === 'emergency',

      config,

      totalEquityUsd: account.getMetrics().totalBalance,
      dailyVolumeUsd: 0, // 需要计算
      openOrdersCount: 0, // 需要获取
      lastUpdateTime: lastUpdate,

      errors: [],
      warnings: [],
    }

    // 添加警告信息
    if (account.needsEmergencyHedge()) {
      summary.warnings.push('需要紧急对冲')
    }
    if (account.needsRebalance()) {
      summary.warnings.push('需要利用率再平衡')
    }

    return summary
  }

  /**
   * 获取所有账户摘要
   */
  getAllAccountSummaries(): AccountSummary[] {
    return Array.from(this.accounts.keys())
      .map(accountId => this.getAccountSummary(accountId))
      .filter(summary => summary !== undefined) as AccountSummary[]
  }

  /**
   * 计算全局Delta
   */
  calculateGlobalDelta(): number {
    return this.getAllAccounts().reduce((total, account) => {
      return total + account.getMetrics().currentDelta
    }, 0)
  }

  /**
   * 计算全局利用率
   */
  calculateGlobalUtilization(): number {
    const accounts = this.getAllAccounts()
    if (accounts.length === 0) return 0

    let totalValue = 0
    let totalBalance = 0

    accounts.forEach(account => {
      const metrics = account.getMetrics()
      totalValue += Math.abs(metrics.netPosition) * 65000 // 假设BTC价格
      totalBalance += metrics.totalBalance
    })

    return totalBalance > 0 ? totalValue / totalBalance : 0
  }

  /**
   * 获取系统状态摘要
   */
  getSystemSummary() {
    const accounts = this.getAllAccounts()
    const activeAccounts = this.getActiveAccounts()
    const needHedgeAccounts = this.getAccountsNeedingHedge()

    return {
      totalAccounts: accounts.length,
      activeAccounts: activeAccounts.length,
      accountsNeedingHedge: needHedgeAccounts.length,
      globalDelta: this.calculateGlobalDelta(),
      globalUtilization: this.calculateGlobalUtilization(),
      hedgingGroups: this.hedgingGroups.size,
      accounts: accounts.map(account => account.getStatusSummary()),
      lastUpdate: new Date(),
    }
  }

  /**
   * 获取服务状态
   */
  getStatus(): ServiceStatus {
    return {
      name: 'UnifiedAccountManager',
      status: this.status === 'running' ? 'running' : this.status === 'error' ? 'error' : 'stopped',
      lastUpdate: this.lastStatusChange,
      details: {
        accountCount: this.accounts.size,
        activeAccounts: this.getActiveAccounts().length,
        hedgingGroups: this.hedgingGroups.size,
        globalDelta: this.calculateGlobalDelta(),
        globalUtilization: this.calculateGlobalUtilization(),
      },
    }
  }

  getLastStatusChange(): number {
    return this.lastStatusChange
  }

  // ========== 私有方法 ==========

  /**
   * 设置事件处理器
   */
  private setupEventHandlers(): void {
    this.on('account-delta-violation', data => {
      logger.warn(`🚨 账户 ${data.accountId} Delta违规: ${data.delta}`)
    })

    this.on('account-utilization-violation', data => {
      logger.warn(`⚠️ 账户 ${data.accountId} 利用率违规: ${data.utilization}`)
    })

    this.on('account-emergency', data => {
      logger.error(`🆘 账户 ${data.accountId} 进入紧急状态: ${data.reason}`)
    })
  }

  /**
   * 验证系统配置
   */
  private async validateSystemConfiguration(): Promise<void> {
    // 验证配置参数
    if (this.config.deltaThreshold <= 0) {
      throw new Error('Delta阈值必须大于0')
    }

    if (this.config.utilizationTargetMin >= this.config.utilizationTargetMax) {
      throw new Error('最小利用率必须小于最大利用率')
    }

    logger.info('✅ 系统配置验证通过')
  }

  /**
   * 初始化已注册账户
   */
  private async initializeRegisteredAccounts(): Promise<void> {
    // 这里可以从配置文件或环境变量加载账户
    logger.info('📋 初始化已注册账户完成')
  }

  /**
   * 设置监控和健康检查
   */
  private setupMonitoringAndHealthChecks(): void {
    logger.info('🔧 设置监控和健康检查完成')
  }

  /**
   * 验证账户配置
   */
  private validateAccountConfig(config: UnifiedAccountConfig): void {
    if (!config.accountId) {
      throw new Error('accountId 是必需的')
    }

    if (!config.exchange) {
      throw new Error('exchange 是必需的')
    }

    if (!['pacifica', 'aster', 'binance'].includes(config.exchange)) {
      throw new Error('不支持的交易所')
    }

    if (!config.publicKey || !config.privateKey) {
      throw new Error('publicKey 和 privateKey 是必需的')
    }

    if (config.utilizationTargetMin >= config.utilizationTargetMax) {
      throw new Error('utilizationTargetMin 必须小于 utilizationTargetMax')
    }

    if (config.deltaThreshold <= 0) {
      throw new Error('deltaThreshold 必须大于0')
    }
  }

  /**
   * 初始化账户性能指标
   */
  private initializeAccountPerformanceMetrics(accountId: string): void {
    const metrics: AccountPerformanceMetrics = {
      accountId,
      avgDeltaDeviation: 0,
      deltaViolationCount: 0,
      maxDeltaDeviation: 0,
      deltaControlEfficiency: 1,
      avgUtilization: 0.65,
      utilizationStability: 1,
      targetUtilizationHitRate: 1,
      totalTrades: 0,
      successfulTrades: 0,
      avgExecutionTime: 0,
      maxDrawdown: 0,
      sharpeRatio: 0,
      riskAdjustedReturn: 0,
      periodStart: new Date(),
      periodEnd: new Date(),
    }

    this.performanceMetrics.set(accountId, metrics)
  }

  /**
   * 启动账户更新
   */
  private startAccountUpdates(): void {
    for (const accountId of this.accounts.keys()) {
      this.startAccountMonitoring(accountId)
    }
  }

  /**
   * 启动单个账户监控
   */
  private startAccountMonitoring(accountId: string): void {
    const interval = setInterval(async () => {
      try {
        await this.updateAccountState(accountId)
      } catch (error) {
        logger.error(`账户 ${accountId} 状态更新失败:`, error)
      }
    }, this.config.accountUpdateInterval)

    this.updateIntervals.set(accountId, interval)
  }

  /**
   * 停止账户监控
   */
  private stopAccountMonitoring(accountId: string): void {
    const interval = this.updateIntervals.get(accountId)
    if (interval) {
      clearInterval(interval)
      this.updateIntervals.delete(accountId)
    }

    const healthCheck = this.connectionHealthChecks.get(accountId)
    if (healthCheck) {
      clearInterval(healthCheck)
      this.connectionHealthChecks.delete(accountId)
    }
  }

  /**
   * 更新账户状态
   */
  private async updateAccountState(accountId: string): Promise<void> {
    const account = this.accounts.get(accountId)
    if (!account) return

    try {
      // 模拟状态更新（实际实现需要调用交易所API）
      const simulatedMetrics = {
        currentUtilization: 0.65 + (Math.random() - 0.5) * 0.1,
        currentDelta: (Math.random() - 0.5) * 0.002,
        netPosition: (Math.random() - 0.5) * 0.1,
        totalBalance: 1000 + Math.random() * 100,
        availableBalance: 800 + Math.random() * 100,
        unrealizedPnl: (Math.random() - 0.5) * 50,
        leverage: 1 + Math.random() * 2,
        lastUpdate: new Date(),
      }

      account.updateMetrics(simulatedMetrics)
      this.lastAccountUpdates.set(accountId, new Date())

      // 检查违规情况
      this.checkAccountViolations(account)
    } catch (error) {
      logger.error(`更新账户 ${accountId} 状态失败:`, error)
    }
  }

  /**
   * 检查账户违规
   */
  private checkAccountViolations(account: ExchangeAccount): void {
    const config = account.getConfig()
    const metrics = account.getMetrics()

    // 检查Delta违规
    if (account.needsEmergencyHedge()) {
      this.emit('account-delta-violation', {
        accountId: config.accountId,
        delta: metrics.currentDelta,
        threshold: account.getDeltaParams().emergencyThreshold,
      })
    }

    // 检查利用率违规
    if (account.needsRebalance()) {
      this.emit('account-utilization-violation', {
        accountId: config.accountId,
        utilization: metrics.currentUtilization,
        targetMin: config.utilizationTargetMin,
        targetMax: config.utilizationTargetMax,
      })
    }

    // 检查紧急状态
    if (config.status === 'emergency') {
      this.emit('account-emergency', {
        accountId: config.accountId,
        reason: '账户处于紧急状态',
      })
    }
  }

  /**
   * 启动健康检查
   */
  private startHealthChecks(): void {
    for (const accountId of this.accounts.keys()) {
      const interval = setInterval(() => {
        this.performAccountHealthCheck(accountId)
      }, this.config.healthCheckInterval)

      this.connectionHealthChecks.set(accountId, interval)
    }
  }

  /**
   * 执行账户健康检查
   */
  private performAccountHealthCheck(accountId: string): void {
    const lastUpdate = this.lastAccountUpdates.get(accountId)
    if (!lastUpdate) return

    const timeSinceUpdate = Date.now() - lastUpdate.getTime()

    if (timeSinceUpdate > this.config.accountUpdateInterval * 3) {
      logger.warn(`⚠️ 账户 ${accountId} 健康检查失败，上次更新: ${Math.round(timeSinceUpdate / 1000)}秒前`)
    }
  }

  /**
   * 启动性能监控
   */
  private startPerformanceMonitoring(): void {
    setInterval(() => {
      this.generatePerformanceReport()
    }, this.config.performanceReportInterval)
  }

  /**
   * 生成性能报告
   */
  private generatePerformanceReport(): void {
    const summary = this.getSystemSummary()

    logger.info('📊 UnifiedAccountManager 性能报告', {
      accounts: summary.totalAccounts,
      active: summary.activeAccounts,
      needingHedge: summary.accountsNeedingHedge,
      globalDelta: summary.globalDelta.toFixed(6),
      globalUtilization: (summary.globalUtilization * 100).toFixed(1) + '%',
      hedgingGroups: summary.hedgingGroups,
    })
  }

  /**
   * 执行初始状态同步
   */
  private async performInitialStateSynchronization(): Promise<void> {
    logger.info('🔄 执行初始状态同步')

    for (const accountId of this.accounts.keys()) {
      try {
        await this.updateAccountState(accountId)
      } catch (error) {
        logger.error(`初始同步账户 ${accountId} 失败:`, error)
      }
    }
  }

  /**
   * 停止所有定时器
   */
  private stopAllTimers(): void {
    // 停止账户更新定时器
    for (const interval of this.updateIntervals.values()) {
      clearInterval(interval)
    }
    this.updateIntervals.clear()

    // 停止健康检查定时器
    for (const interval of this.connectionHealthChecks.values()) {
      clearInterval(interval)
    }
    this.connectionHealthChecks.clear()
  }

  /**
   * 执行优雅关闭
   */
  private async performGracefulShutdown(): Promise<void> {
    logger.info('🔄 执行优雅关闭')

    // 可以在这里执行最后的状态保存等操作
  }

  /**
   * 清理资源
   */
  private cleanup(): void {
    this.accounts.clear()
    this.accountConfigs.clear()
    this.hedgingGroups.clear()
    this.performanceMetrics.clear()
    this.lastAccountUpdates.clear()
    this.removeAllListeners()
  }

  /**
   * 从对冲组移除账户（占位实现）
   */
  private async removeAccountFromHedgingGroup(groupId: string, accountId: string): Promise<void> {
    const group = this.hedgingGroups.get(groupId)
    if (group) {
      group.accounts = group.accounts.filter(id => id !== accountId)
      logger.info(`✅ 从对冲组 ${groupId} 移除账户 ${accountId}`)
    }
  }
}

export default UnifiedAccountManager
