import WebSocket from 'ws'
import { EventEmitter } from 'events'
import { logger } from '../../utils/logger.js'
import { Config } from '../../config/simpleEnv.js'
import { globalPriceManager } from '../price/PriceManager.js'
import { TradingService, ServiceStatus } from '../types.js'
import { AccountManager } from '../account/AccountManager.js'
import { OrderCreatePayload } from '../../exchanges/pacifica/OrdersAdapter.js'

export interface AccountPosition {
  account: string
  symbol: string
  size: number // 正数=多头，负数=空头
  averageEntryPrice: number
  unrealizedPnl: number
  marginUsed: number
  timestamp: number
}

export interface AccountBalance {
  account: string
  totalBalance: number
  availableBalance: number
  marginUsed: number
  utilizationRate: number // marginUsed / totalBalance
  timestamp: number
}

export interface HedgingRisk {
  netExposure: number // 净敞口 (position1 + position2)
  exposureRatio: number // 敞口比例
  utilizationImbalance: number // 使用率不平衡
  priceSpread: number // 平均入场价差
  riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL'
}

/**
 * 高级对冲管理器
 *
 * 核心功能：
 * 1. 实时监控账户仓位和余额
 * 2. 优先保证净值中性（敞口控制）
 * 3. 平衡两账户的使用率
 * 4. 防范单边行情风险
 */
export class AdvancedHedgingManager extends EventEmitter implements TradingService {
  private wsConnections: Map<string, WebSocket> = new Map()
  private accountPositions: Map<string, AccountPosition> = new Map()
  private accountBalances: Map<string, AccountBalance> = new Map()
  private wsUrl: string
  private accounts: string[]
  private symbol: string
  private isActive = false
  private accountManager: AccountManager | null = null

  // WebSocket连接管理
  private reconnectAttempts: Map<string, number> = new Map()
  private maxReconnectAttempts = 10
  private pingIntervals: Map<string, NodeJS.Timeout> = new Map()
  private connectingAccounts: Set<string> = new Set()
  private lastConnectAttempt: Map<string, number> = new Map()

  // 风险控制参数
  private riskLimits = {
    maxNetExposure: 0.01, // 最大净敞口 (BTC)
    maxUtilizationImbalance: 0.2, // 最大使用率不平衡 (20%)
    maxPriceSpread: 0.02, // 最大价差比例 (2%)
    targetUtilizationRange: [0.7, 0.8], // 目标使用率范围
    emergencyThreshold: 0.95, // 紧急平仓阈值
  }

  constructor(accounts: string[], symbol: string = 'BTC', wsUrl?: string) {
    super()
    this.accounts = accounts
    this.symbol = symbol
    this.wsUrl = wsUrl || Config.pacifica.wsUrl || 'wss://ws.pacifica.fi/ws'

    // 定期风险评估
    setInterval(() => this.performRiskAssessment(), 5000) // 5秒评估一次

    // 定期对冲调整
    setInterval(() => this.executeHedgingAdjustment(), 10000) // 10秒调整一次
  }

  /**
   * 初始化对冲管理器
   */
  async initialize(): Promise<void> {
    logger.info('初始化高级对冲管理器', { accounts: this.accounts, symbol: this.symbol })
    // 初始化阶段只是准备，不建立连接
  }

  /**
   * 设置账户管理器 (用于实际交易)
   */
  setAccountManager(accountManager: AccountManager): void {
    this.accountManager = accountManager
    logger.info('✅ 对冲管理器已连接AccountManager，可执行实际交易')
  }

  /**
   * 启动对冲管理器
   */
  async start(): Promise<void> {
    logger.info('启动高级对冲管理器', { accounts: this.accounts, symbol: this.symbol })

    try {
      // 为每个账户建立WebSocket连接
      for (const account of this.accounts) {
        await this.connectAccountWebSocket(account)
      }

      this.isActive = true
      logger.info('✅ 对冲管理器启动成功')
      this.emit('started')
    } catch (error) {
      logger.error('对冲管理器启动失败', { error })
      throw error
    }
  }

  /**
   * 为账户建立WebSocket连接
   */
  private async connectAccountWebSocket(account: string): Promise<void> {
    // 防止重复连接
    if (
      this.connectingAccounts.has(account) ||
      (this.wsConnections.has(account) && this.wsConnections.get(account)?.readyState === WebSocket.OPEN)
    ) {
      return
    }

    // 检查重连频率限制 (最少间隔1秒)
    const lastAttempt = this.lastConnectAttempt.get(account) || 0
    const now = Date.now()
    if (now - lastAttempt < 1000) {
      logger.debug(`账户${account}重连过于频繁，跳过此次连接`)
      return
    }

    this.connectingAccounts.add(account)
    this.lastConnectAttempt.set(account, now)

    const attempts = this.reconnectAttempts.get(account) || 0
    if (attempts >= this.maxReconnectAttempts) {
      logger.error(`账户${account}已达到最大重连次数(${this.maxReconnectAttempts})，停止重连`)
      this.connectingAccounts.delete(account)
      return
    }

    try {
      logger.info(`连接账户${account}的WebSocket (尝试 ${attempts + 1}/${this.maxReconnectAttempts})`)
      const ws = new WebSocket(this.wsUrl)

      ws.on('open', () => {
        logger.info(`✅ 账户${account}的WebSocket已连接`)

        // 重置重连计数
        this.reconnectAttempts.set(account, 0)
        this.connectingAccounts.delete(account)

        // 订阅账户仓位数据
        ws.send(
          JSON.stringify({
            method: 'subscribe',
            params: {
              source: 'account_positions',
              account: account,
            },
          }),
        )

        // 订阅账户余额数据
        ws.send(
          JSON.stringify({
            method: 'subscribe',
            params: {
              source: 'account_balance',
              account: account,
            },
          }),
        )

        logger.info(`📊 已订阅账户${account}的仓位和余额数据`)

        // 启动心跳
        this.startPing(account, ws)
      })

      ws.on('message', (data: Buffer) => {
        try {
          const message = JSON.parse(data.toString())

          // 处理pong响应
          if (message.type === 'pong') {
            logger.debug(`收到账户${account}的pong响应`)
            return
          }

          this.handleAccountMessage(account, message)
        } catch (error) {
          logger.warn('解析账户WebSocket消息失败', { account, error })
        }
      })

      ws.on('error', error => {
        logger.error(`账户${account}的WebSocket错误`, { error })
        this.connectingAccounts.delete(account)
        this.stopPing(account)
      })

      ws.on('close', (code, reason) => {
        logger.warn(`账户${account}的WebSocket连接关闭，尝试重连...`, {
          code,
          reason: reason.toString(),
          attempts: attempts + 1,
        })

        this.connectingAccounts.delete(account)
        this.stopPing(account)

        // 增加重连次数
        this.reconnectAttempts.set(account, attempts + 1)

        // 使用指数退避重连
        const backoffDelay = Math.min(1000 * Math.pow(2, attempts), 30000) // 最大30秒
        const jitter = Math.random() * 1000 // 添加抖动避免同时重连

        setTimeout(() => {
          if (this.isActive) {
            // 只在服务激活时重连
            this.connectAccountWebSocket(account)
          }
        }, backoffDelay + jitter)
      })

      this.wsConnections.set(account, ws)
    } catch (error) {
      logger.error(`创建账户${account}的WebSocket连接失败`, { error })
      this.connectingAccounts.delete(account)

      // 重连
      const attempts = this.reconnectAttempts.get(account) || 0
      this.reconnectAttempts.set(account, attempts + 1)

      const backoffDelay = Math.min(1000 * Math.pow(2, attempts), 30000)
      setTimeout(() => {
        if (this.isActive) {
          this.connectAccountWebSocket(account)
        }
      }, backoffDelay)
    }
  }

  /**
   * 启动WebSocket心跳
   */
  private startPing(account: string, ws: WebSocket): void {
    // 清除之前的心跳
    this.stopPing(account)

    // 每30秒发送一次ping
    const pingInterval = setInterval(() => {
      if (ws.readyState === WebSocket.OPEN) {
        try {
          ws.send(JSON.stringify({ type: 'ping', timestamp: Date.now() }))
          logger.debug(`发送ping到账户${account}`)
        } catch (error) {
          logger.warn(`发送ping失败: ${account}`, { error })
          this.stopPing(account)
        }
      } else {
        logger.warn(`WebSocket连接已关闭，停止ping: ${account}`)
        this.stopPing(account)
      }
    }, 30000)

    this.pingIntervals.set(account, pingInterval)
  }

  /**
   * 停止WebSocket心跳
   */
  private stopPing(account: string): void {
    const pingInterval = this.pingIntervals.get(account)
    if (pingInterval) {
      clearInterval(pingInterval)
      this.pingIntervals.delete(account)
    }
  }

  /**
   * 处理账户WebSocket消息
   */
  private handleAccountMessage(account: string, message: any): void {
    try {
      if (message.channel === 'account_positions' && message.data) {
        this.updateAccountPosition(account, message.data)
      } else if (message.channel === 'account_balance' && message.data) {
        this.updateAccountBalance(account, message.data)
      }
    } catch (error) {
      logger.warn('处理账户消息失败', { account, error })
    }
  }

  /**
   * 更新账户仓位数据
   */
  private updateAccountPosition(account: string, positionData: any): void {
    const position: AccountPosition = {
      account,
      symbol: positionData.symbol || this.symbol,
      size: parseFloat(positionData.size || positionData.position || '0'),
      averageEntryPrice: parseFloat(positionData.averageEntryPrice || positionData.avgPrice || '0'),
      unrealizedPnl: parseFloat(positionData.unrealizedPnl || positionData.pnl || '0'),
      marginUsed: parseFloat(positionData.marginUsed || positionData.margin || '0'),
      timestamp: Date.now(),
    }

    this.accountPositions.set(account, position)
    logger.debug(`📈 仓位更新: ${account} = ${position.size} BTC @ $${position.averageEntryPrice}`)

    this.emit('positionUpdate', { account, position })
  }

  /**
   * 更新账户余额数据
   */
  private updateAccountBalance(account: string, balanceData: any): void {
    const totalBalance = parseFloat(balanceData.totalBalance || balanceData.total || '0')
    const marginUsed = parseFloat(balanceData.marginUsed || balanceData.used || '0')

    const balance: AccountBalance = {
      account,
      totalBalance,
      availableBalance: parseFloat(balanceData.availableBalance || balanceData.available || '0'),
      marginUsed,
      utilizationRate: totalBalance > 0 ? marginUsed / totalBalance : 0,
      timestamp: Date.now(),
    }

    this.accountBalances.set(account, balance)
    logger.debug(`💰 余额更新: ${account} = ${(balance.utilizationRate * 100).toFixed(1)}% 使用率`)

    this.emit('balanceUpdate', { account, balance })
  }

  /**
   * 执行风险评估 (问题1: 敞口暴露控制)
   */
  private performRiskAssessment(): HedgingRisk {
    if (this.accounts.length < 2) {
      return { netExposure: 0, exposureRatio: 0, utilizationImbalance: 0, priceSpread: 0, riskLevel: 'LOW' }
    }

    const [account1, account2] = this.accounts
    const pos1 = this.accountPositions.get(account1)
    const pos2 = this.accountPositions.get(account2)
    const bal1 = this.accountBalances.get(account1)
    const bal2 = this.accountBalances.get(account2)

    if (!pos1 || !pos2 || !bal1 || !bal2) {
      return { netExposure: 0, exposureRatio: 0, utilizationImbalance: 0, priceSpread: 0, riskLevel: 'LOW' }
    }

    // 计算净敞口 (最重要的风险指标)
    const netExposure = Math.abs(pos1.size + pos2.size)
    const totalExposure = Math.abs(pos1.size) + Math.abs(pos2.size)
    const exposureRatio = totalExposure > 0 ? netExposure / totalExposure : 0

    // 计算使用率不平衡
    const utilizationImbalance = Math.abs(bal1.utilizationRate - bal2.utilizationRate)

    // 计算价差风险
    const currentPrice = globalPriceManager.getPrice(this.symbol)
    const avgPrice = (pos1.averageEntryPrice + pos2.averageEntryPrice) / 2
    const priceSpread = avgPrice > 0 ? Math.abs(currentPrice - avgPrice) / avgPrice : 0

    // 风险等级评估
    let riskLevel: HedgingRisk['riskLevel'] = 'LOW'

    if (
      netExposure > this.riskLimits.maxNetExposure * 0.8 ||
      utilizationImbalance > this.riskLimits.maxUtilizationImbalance * 0.8 ||
      Math.max(bal1.utilizationRate, bal2.utilizationRate) > this.riskLimits.emergencyThreshold
    ) {
      riskLevel = 'CRITICAL'
    } else if (
      netExposure > this.riskLimits.maxNetExposure * 0.6 ||
      utilizationImbalance > this.riskLimits.maxUtilizationImbalance * 0.6
    ) {
      riskLevel = 'HIGH'
    } else if (
      netExposure > this.riskLimits.maxNetExposure * 0.3 ||
      utilizationImbalance > this.riskLimits.maxUtilizationImbalance * 0.3
    ) {
      riskLevel = 'MEDIUM'
    }

    const risk: HedgingRisk = {
      netExposure,
      exposureRatio,
      utilizationImbalance,
      priceSpread,
      riskLevel,
    }

    // 记录风险状态
    if (riskLevel !== 'LOW') {
      logger.warn(`⚠️ 对冲风险评估: ${riskLevel}`, {
        netExposure: netExposure.toFixed(6),
        exposureRatio: (exposureRatio * 100).toFixed(1) + '%',
        utilizationImbalance: (utilizationImbalance * 100).toFixed(1) + '%',
        priceSpread: (priceSpread * 100).toFixed(2) + '%',
      })
    }

    this.emit('riskAssessment', risk)
    return risk
  }

  /**
   * 执行对冲调整 (统一处理三个问题)
   */
  private async executeHedgingAdjustment(): Promise<void> {
    if (!this.isActive || this.accounts.length < 2) return

    const risk = this.performRiskAssessment()
    const [account1, account2] = this.accounts
    const pos1 = this.accountPositions.get(account1)
    const pos2 = this.accountPositions.get(account2)
    const bal1 = this.accountBalances.get(account1)
    const bal2 = this.accountBalances.get(account2)

    if (!pos1 || !pos2 || !bal1 || !bal2) return

    try {
      // 优先级1: 敞口控制 (最高优先级)
      if (risk.riskLevel === 'CRITICAL' || risk.netExposure > this.riskLimits.maxNetExposure) {
        await this.executeExposureControl(pos1, pos2, risk)
        return // 敞口问题解决后再处理其他问题
      }

      // 优先级2: 使用率平衡
      if (risk.utilizationImbalance > this.riskLimits.maxUtilizationImbalance) {
        await this.executeUtilizationBalancing(bal1, bal2, pos1, pos2)
        return
      }

      // 优先级3: 单边行情风险控制
      if (risk.priceSpread > this.riskLimits.maxPriceSpread) {
        await this.executePriceSpreadControl(pos1, pos2, risk)
        return
      }

      // 如果没有紧急风险，执行常规维护
      await this.executeRoutineMaintenance(bal1, bal2, pos1, pos2)
    } catch (error) {
      logger.error('对冲调整执行失败', { error })
    }
  }

  /**
   * 敞口控制 (问题1: 最高优先级)
   */
  private async executeExposureControl(pos1: AccountPosition, pos2: AccountPosition, risk: HedgingRisk): Promise<void> {
    logger.warn(`🚨 [敞口控制] 净敞口${risk.netExposure.toFixed(6)} BTC 超限，执行紧急对冲`)

    const netPosition = pos1.size + pos2.size

    if (Math.abs(netPosition) < 0.00001) {
      logger.info('净敞口已接近中性，无需调整')
      return
    }

    // 计算需要调整的数量 (让净敞口接近0)
    const adjustmentSize = Math.abs(netPosition) * 0.8 // 调整80%

    // 确定调整方向：净多头需要卖出，净空头需要买入
    const adjustmentSide = netPosition > 0 ? 'ask' : 'bid'

    // 选择调整账户：选择仓位较大的账户进行调整
    const adjustAccount = Math.abs(pos1.size) > Math.abs(pos2.size) ? pos1.account : pos2.account

    logger.info(`📊 [敞口调整] ${adjustAccount}: ${adjustmentSide} ${adjustmentSize.toFixed(6)} BTC`)

    // 执行调整订单
    await this.executeHedgeOrder({
      account: adjustAccount,
      symbol: this.symbol,
      size: adjustmentSize,
      side: adjustmentSide,
      type: 'market',
      reason: '敞口控制',
    })
  }

  /**
   * 使用率平衡 (问题2)
   */
  private async executeUtilizationBalancing(
    bal1: AccountBalance,
    bal2: AccountBalance,
    pos1: AccountPosition,
    pos2: AccountPosition,
  ): Promise<void> {
    const utilizationDiff = bal1.utilizationRate - bal2.utilizationRate
    const avgUtilization = (bal1.utilizationRate + bal2.utilizationRate) / 2

    logger.info(
      `⚖️ [使用率平衡] ${bal1.account}: ${(bal1.utilizationRate * 100).toFixed(1)}%, ${bal2.account}: ${(
        bal2.utilizationRate * 100
      ).toFixed(1)}%`,
    )

    // 如果平均使用率在目标范围内，通过仓位调整平衡使用率
    if (
      avgUtilization >= this.riskLimits.targetUtilizationRange[0] &&
      avgUtilization <= this.riskLimits.targetUtilizationRange[1]
    ) {
      // 高使用率账户减仓，低使用率账户加仓
      const highUtilAccount = bal1.utilizationRate > bal2.utilizationRate ? bal1.account : bal2.account
      const lowUtilAccount = bal1.utilizationRate < bal2.utilizationRate ? bal1.account : bal2.account

      const adjustmentRatio = Math.abs(utilizationDiff) * 0.3 // 调整30%的差异
      const currentPrice = globalPriceManager.getPrice(this.symbol)

      if (currentPrice > 0) {
        const adjustmentUsd = Math.min(bal1.totalBalance, bal2.totalBalance) * adjustmentRatio * 0.5
        const adjustmentBtc = adjustmentUsd / currentPrice

        logger.info(`📈 [使用率调整] 高使用率账户减仓, 低使用率账户加仓: ${adjustmentBtc.toFixed(6)} BTC`)

        // 同步执行: 高使用率账户减仓 + 低使用率账户加仓
        await Promise.all([
          this.executeHedgeOrder({
            account: highUtilAccount,
            symbol: this.symbol,
            size: adjustmentBtc,
            side: 'ask', // 减仓
            type: 'market',
            reason: '使用率平衡-减仓',
          }),
          this.executeHedgeOrder({
            account: lowUtilAccount,
            symbol: this.symbol,
            size: adjustmentBtc,
            side: 'bid', // 加仓
            type: 'market',
            reason: '使用率平衡-加仓',
          }),
        ])
      }
    }
    // 如果平均使用率超出目标范围，同步调整
    else if (avgUtilization > this.riskLimits.targetUtilizationRange[1]) {
      // 平均使用率过高，双账户同步减仓
      await this.executeSynchronizedReduction(bal1, bal2, pos1, pos2)
    } else if (avgUtilization < this.riskLimits.targetUtilizationRange[0]) {
      // 平均使用率过低，双账户同步加仓
      await this.executeSynchronizedIncrease(bal1, bal2, pos1, pos2)
    }
  }

  /**
   * 价差风险控制 (问题3: 单边行情)
   */
  private async executePriceSpreadControl(
    pos1: AccountPosition,
    pos2: AccountPosition,
    risk: HedgingRisk,
  ): Promise<void> {
    const currentPrice = globalPriceManager.getPrice(this.symbol)
    const avgEntryPrice = (pos1.averageEntryPrice + pos2.averageEntryPrice) / 2

    logger.warn(
      `📊 [价差控制] 当前价格$${currentPrice}, 平均入场价$${avgEntryPrice}, 价差${(risk.priceSpread * 100).toFixed(
        2,
      )}%`,
    )

    // 如果价差过大，考虑部分平仓重新开仓
    if (risk.priceSpread > this.riskLimits.maxPriceSpread) {
      const rebalanceRatio = 0.2 // 重新平衡20%的仓位

      const rebalanceSize1 = Math.abs(pos1.size) * rebalanceRatio
      const rebalanceSize2 = Math.abs(pos2.size) * rebalanceRatio

      logger.info(
        `🔄 [价差重平衡] 部分平仓重开: ${pos1.account} ${rebalanceSize1.toFixed(6)} BTC, ${
          pos2.account
        } ${rebalanceSize2.toFixed(6)} BTC`,
      )

      // 同步平仓再开仓
      await Promise.all([
        this.executeRebalanceSequence(pos1.account, rebalanceSize1, pos1.size > 0 ? 'ask' : 'bid'),
        this.executeRebalanceSequence(pos2.account, rebalanceSize2, pos2.size > 0 ? 'ask' : 'bid'),
      ])
    }
  }

  /**
   * 双账户同步减仓
   */
  private async executeSynchronizedReduction(
    bal1: AccountBalance,
    bal2: AccountBalance,
    pos1: AccountPosition,
    pos2: AccountPosition,
  ): Promise<void> {
    const avgUtilization = (bal1.utilizationRate + bal2.utilizationRate) / 2
    const targetReduction = (avgUtilization - this.riskLimits.targetUtilizationRange[1]) * 0.5

    const currentPrice = globalPriceManager.getPrice(this.symbol)
    if (currentPrice <= 0) return

    const reductionUsd1 = bal1.totalBalance * targetReduction
    const reductionUsd2 = bal2.totalBalance * targetReduction
    const reductionBtc1 = Math.min(reductionUsd1 / currentPrice, Math.abs(pos1.size) * 0.3)
    const reductionBtc2 = Math.min(reductionUsd2 / currentPrice, Math.abs(pos2.size) * 0.3)

    logger.info(
      `📉 [同步减仓] ${bal1.account}: ${reductionBtc1.toFixed(6)} BTC, ${bal2.account}: ${reductionBtc2.toFixed(
        6,
      )} BTC`,
    )

    await Promise.all([
      this.executeHedgeOrder({
        account: bal1.account,
        symbol: this.symbol,
        size: reductionBtc1,
        side: pos1.size > 0 ? 'ask' : 'bid',
        type: 'market',
        reason: '同步减仓',
      }),
      this.executeHedgeOrder({
        account: bal2.account,
        symbol: this.symbol,
        size: reductionBtc2,
        side: pos2.size > 0 ? 'ask' : 'bid',
        type: 'market',
        reason: '同步减仓',
      }),
    ])
  }

  /**
   * 双账户同步加仓
   */
  private async executeSynchronizedIncrease(
    bal1: AccountBalance,
    bal2: AccountBalance,
    pos1: AccountPosition,
    pos2: AccountPosition,
  ): Promise<void> {
    const avgUtilization = (bal1.utilizationRate + bal2.utilizationRate) / 2
    const targetIncrease = (this.riskLimits.targetUtilizationRange[0] - avgUtilization) * 0.5

    const currentPrice = globalPriceManager.getPrice(this.symbol)
    if (currentPrice <= 0) return

    const increaseUsd1 = bal1.availableBalance * targetIncrease
    const increaseUsd2 = bal2.availableBalance * targetIncrease
    const increaseBtc1 = increaseUsd1 / currentPrice
    const increaseBtc2 = increaseUsd2 / currentPrice

    logger.info(
      `📈 [同步加仓] ${bal1.account}: ${increaseBtc1.toFixed(6)} BTC, ${bal2.account}: ${increaseBtc2.toFixed(6)} BTC`,
    )

    // 保持对冲关系：一个做多，一个做空
    await Promise.all([
      this.executeHedgeOrder({
        account: bal1.account,
        symbol: this.symbol,
        size: increaseBtc1,
        side: 'bid', // 做多
        type: 'market',
        reason: '同步加仓',
      }),
      this.executeHedgeOrder({
        account: bal2.account,
        symbol: this.symbol,
        size: increaseBtc2,
        side: 'ask', // 做空
        type: 'market',
        reason: '同步加仓',
      }),
    ])
  }

  /**
   * 常规维护
   */
  private async executeRoutineMaintenance(
    bal1: AccountBalance,
    bal2: AccountBalance,
    pos1: AccountPosition,
    pos2: AccountPosition,
  ): Promise<void> {
    // 检查是否需要轻微调整
    const avgUtilization = (bal1.utilizationRate + bal2.utilizationRate) / 2

    if (avgUtilization < this.riskLimits.targetUtilizationRange[0] - 0.1) {
      logger.debug('📊 [常规维护] 使用率偏低，考虑轻微加仓')
      // 可以实现轻微的调整逻辑
    }
  }

  /**
   * 执行重平衡序列 (平仓再开仓)
   */
  private async executeRebalanceSequence(account: string, size: number, closeSide: 'bid' | 'ask'): Promise<void> {
    // 先平仓
    await this.executeHedgeOrder({
      account,
      symbol: this.symbol,
      size: size,
      side: closeSide,
      type: 'market',
      reason: '重平衡-平仓',
    })

    // 等待1秒再开仓 (避免价格冲击)
    await new Promise(resolve => setTimeout(resolve, 1000))

    // 反向开仓
    const openSide = closeSide === 'bid' ? 'ask' : 'bid'
    await this.executeHedgeOrder({
      account,
      symbol: this.symbol,
      size: size,
      side: openSide,
      type: 'market',
      reason: '重平衡-开仓',
    })
  }

  /**
   * 执行对冲订单 (集成实际交易客户端)
   */
  private async executeHedgeOrder(order: {
    account: string
    symbol: string
    size: number
    side: 'bid' | 'ask'
    type: 'market' | 'limit'
    reason: string
  }): Promise<void> {
    logger.info(
      `📋 [对冲订单] ${order.account}: ${order.side} ${order.size.toFixed(6)} ${order.symbol} (${order.reason})`,
    )

    if (!this.accountManager) {
      logger.warn('⚠️ AccountManager未设置，无法执行实际交易 (模拟模式)')
      this.emit('hedgeOrderExecuted', { ...order, simulated: true })
      return
    }

    try {
      // 根据账户ID获取对应的交易客户端
      const clientId = this.getClientIdForAccount(order.account)
      const client = this.accountManager.getClient(clientId)

      if (!client) {
        logger.error(`❌ 未找到账户${order.account}的交易客户端 (clientId: ${clientId})`)
        throw new Error(`No trading client found for account: ${order.account}`)
      }

      // 构建订单payload
      const payload: OrderCreatePayload = {
        account: order.account,
        symbol: order.symbol,
        amount: order.size.toFixed(6), // 确保精度
        side: order.side,
        reduceOnly: false,
        slippagePercent: '0.01', // 1% 滑点保护
        clientOrderId: `hedge-${Date.now()}-${Math.random().toString(36).substr(2, 6)}`,
      }

      // 执行市价单
      if (order.type === 'market') {
        const result = await client.createMarketOrder(payload)
        logger.info(`✅ [对冲订单成功] ${order.account}: ${order.side} ${order.size.toFixed(6)} ${order.symbol}`, {
          orderId: result.orderId || result.order_id,
          reason: order.reason,
        })

        this.emit('hedgeOrderExecuted', {
          ...order,
          orderId: result.orderId || result.order_id,
          result: result,
        })
      } else {
        logger.warn('⚠️ 限价单暂未实现，改为市价单执行')
        const result = await client.createMarketOrder(payload)
        this.emit('hedgeOrderExecuted', {
          ...order,
          orderId: result.orderId || result.order_id,
          result: result,
        })
      }
    } catch (error: any) {
      logger.error(`❌ [对冲订单失败] ${order.account}: ${order.side} ${order.size.toFixed(6)} ${order.symbol}`, {
        error: error.message,
        reason: order.reason,
      })

      this.emit('hedgeOrderError', { ...order, error: error.message })
      throw error
    }
  }

  /**
   * 根据账户ID获取对应的客户端ID
   */
  private getClientIdForAccount(account: string): string {
    // 账户ID到客户端ID的映射逻辑
    // 这里需要根据实际的命名规则调整
    if (account === this.accounts[0]) {
      return 'pacifica-1'
    } else if (account === this.accounts[1]) {
      return 'pacifica-2'
    }

    // 默认映射规则
    const accountIndex = this.accounts.indexOf(account)
    if (accountIndex >= 0) {
      return `pacifica-${accountIndex + 1}`
    }

    return 'pacifica-1' // 默认使用第一个客户端
  }

  /**
   * 获取服务状态 (TradingService 接口)
   */
  public getStatus(): ServiceStatus {
    const risk = this.performRiskAssessment()
    return {
      name: 'AdvancedHedgingManager',
      status: this.isActive ? 'running' : 'stopped',
      lastUpdate: Date.now(),
      details: {
        accounts: this.accounts,
        accountCount: this.accounts.length,
        wsConnections: this.wsConnections.size,
        positionCount: this.accountPositions.size,
        balanceCount: this.accountBalances.size,
        riskLevel: risk.riskLevel,
        netExposure: risk.netExposure,
      },
    }
  }

  /**
   * 获取详细状态 (扩展方法)
   */
  public getDetailedStatus(): {
    isActive: boolean
    accounts: string[]
    positions: Map<string, AccountPosition>
    balances: Map<string, AccountBalance>
    lastRisk: HedgingRisk
  } {
    return {
      isActive: this.isActive,
      accounts: this.accounts,
      positions: this.accountPositions,
      balances: this.accountBalances,
      lastRisk: this.performRiskAssessment(),
    }
  }

  /**
   * 停止对冲管理器并清理所有资源
   */
  public async stop(): Promise<void> {
    logger.info('停止高级对冲管理器...')
    this.isActive = false

    // 停止所有心跳
    for (const account of this.accounts) {
      this.stopPing(account)
    }

    // 关闭所有WebSocket连接
    for (const [account, ws] of this.wsConnections) {
      try {
        if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
          ws.close(1000, 'Service stopped')
        }
        logger.info(`关闭账户${account}的WebSocket连接`)
      } catch (error) {
        logger.warn(`关闭账户${account}的WebSocket时出错`, { error })
      }
    }

    // 清理所有状态
    this.wsConnections.clear()
    this.connectingAccounts.clear()
    this.reconnectAttempts.clear()
    this.lastConnectAttempt.clear()
    this.accountPositions.clear()
    this.accountBalances.clear()

    logger.info('对冲管理器已停止')
    this.emit('stopped')
  }
}

export default AdvancedHedgingManager
