import { TradingSignal } from '../types.js'
import { AccountManager } from '../account/AccountManager.js'
import { RiskManager } from '../risk/RiskManager.js'
import { StopLossService } from '../stopLoss/StopLossService.js'
import { SamePlatformHedgingManager } from '../../core/hedging/SamePlatformHedgingManager.js'
import { PacificaOrderbookManager } from '../orderbook/PacificaOrderbookManager.js'
import { logger } from '../../utils/logger.js'
import { globalPriceManager } from '../price/PriceManager.js'

/**
 * 交易执行器 - 从TradingEngine中分离出来的交易执行逻辑
 */
export class TradeExecutor {
  private riskLimits = {
    maxPositionSize: 0.01,
    maxTotalExposure: 0.05,
    maxAccountBalance: 10000,
    minAccountBalance: 100,
    maxDailyTrades: 200,
    maxSlippage: 0.05,
    emergencyStopLoss: 0.1,
    enabled: true,
  }

  constructor(
    private accountManager: AccountManager,
    private riskManager: RiskManager,
    private stopLossService: StopLossService,
    private hedgeManager: SamePlatformHedgingManager | null = null,
    private pacificaOrderbookManager?: PacificaOrderbookManager,
  ) {}

  /**
   * 处理交易信号
   */
  async handleTradingSignal(signal: TradingSignal): Promise<void> {
    try {
      logger.info(`处理交易信号`, {
        action: signal.action,
        symbol: signal.symbol,
        side: signal.side,
        amount: signal.amount,
        targetAccount: signal.targetAccount,
      })

      // 根据信号动作选择不同的执行方法
      switch (signal.action) {
        case 'buy':
        case 'sell':
          await this.executeTradeSignal(signal)
          break
        case 'hedge':
          await this.executeHedgeSignal(signal)
          break
        case 'volume_boost':
          await this.executeVolumeBoost(signal)
          break
        case 'balance_accounts':
          await this.executeBalanceSignal(signal)
          break
        case 'close_position':
          await this.executeCloseSignal(signal)
          break
        default:
          logger.warn(`未知的信号动作: ${signal.action}`)
      }
    } catch (error) {
      logger.error('处理交易信号失败', {
        signal,
        error: error instanceof Error ? error.message : error,
      })
    }
  }

  /**
   * 执行普通交易信号
   */
  private async executeTradeSignal(signal: TradingSignal): Promise<void> {
    try {
      // 风险检查
      if (!this.riskLimits.enabled) {
        logger.warn('风险控制已禁用，跳过交易')
        return
      }

      // 获取账户客户端
      const accountId = signal.targetAccount || 'pacifica-1' // 默认使用第一个账户
      const client = this.accountManager.getClient(accountId)
      if (!client) {
        logger.error(`找不到账户客户端: ${accountId}`)
        return
      }

      // 检查账户余额
      if (!this.checkAccountBalance()) {
        logger.warn('账户余额不足，跳过交易')
        return
      }

      // 计算交易金额
      const amount = await this.calculateTradingAmount()
      if (parseFloat(amount) <= 0) {
        logger.warn('计算的交易金额无效')
        return
      }

      // 执行交易
      const currentPrice = this.getCurrentPriceSync(signal.symbol)
      if (!currentPrice || currentPrice <= 0) {
        logger.error(`无法获取 ${signal.symbol} 的当前价格`)
        return
      }

      // 检查最小订单金额 (10 USDT)
      const minOrderAmountUsd = 10
      const orderValue = parseFloat(amount) * currentPrice

      if (orderValue < minOrderAmountUsd) {
        logger.warn(`订单金额过小: ${orderValue.toFixed(2)} USD < ${minOrderAmountUsd} USD`)
        return
      }

      logger.info(`执行交易: ${signal.side} ${amount} ${signal.symbol} @$${currentPrice.toFixed(2)}`)

      // 这里会调用实际的交易接口
      // 由于是演示模式，暂时记录日志
      logger.info(`[模拟交易] ${signal.side} ${amount} ${signal.symbol} - 成功`)

    } catch (error) {
      logger.error('执行交易信号失败', { signal, error })
    }
  }

  /**
   * 执行对冲信号
   */
  private async executeHedgeSignal(signal: TradingSignal): Promise<void> {
    try {
      if (!this.hedgeManager) {
        logger.warn('对冲管理器未初始化')
        return
      }

      logger.info(`执行对冲信号: ${signal.side} ${signal.amount} ${signal.symbol}`)

      // 这里会调用对冲管理器的方法
      // 暂时记录日志
      logger.info(`[模拟对冲] ${signal.side} ${signal.amount} ${signal.symbol} - 成功`)

    } catch (error) {
      logger.error('执行对冲信号失败', { signal, error })
    }
  }

  /**
   * 执行批量交易信号
   */
  private async executeVolumeBoost(signal: TradingSignal): Promise<void> {
    try {
      const client = this.accountManager.getClient(signal.targetAccount || 'pacifica-1')
      if (!client) {
        logger.error(`找不到账户客户端: ${signal.targetAccount || 'pacifica-1'}`)
        return
      }

      logger.info(`执行批量交易: ${signal.side} ${signal.amount} ${signal.symbol}`)

      // 批量交易通常使用较小的金额
      const amount = parseFloat(signal.amount)
      const currentPrice = this.getCurrentPriceSync(signal.symbol)

      if (!currentPrice || currentPrice <= 0) {
        logger.error(`无法获取 ${signal.symbol} 的当前价格`)
        return
      }

      // 检查最小订单金额
      const orderValue = amount * currentPrice
      if (orderValue < 10) {
        logger.warn(`批量交易订单金额过小: ${orderValue.toFixed(2)} USD`)
        return
      }

      logger.info(`[模拟批量交易] ${signal.side} ${signal.amount} ${signal.symbol} - 成功`)

    } catch (error) {
      logger.error('执行批量交易失败', { signal, error })
    }
  }

  /**
   * 执行余额检查信号
   */
  private async executeBalanceSignal(signal: TradingSignal): Promise<void> {
    try {
      logger.info(`执行余额检查: ${signal.reason}`)

      // 余额信号通常用于警告或暂停交易
      if (signal.reason?.includes('余额不足')) {
        logger.warn(`账户 ${signal.targetAccount || 'pacifica-1'} 余额不足，暂停交易`)
      }

    } catch (error) {
      logger.error('执行余额信号失败', { signal, error })
    }
  }

  /**
   * 执行平仓信号
   */
  private async executeCloseSignal(signal: TradingSignal): Promise<void> {
    try {
      const client = this.accountManager.getClient(signal.targetAccount || 'pacifica-1')
      if (!client) {
        logger.error(`找不到账户客户端: ${signal.targetAccount || 'pacifica-1'}`)
        return
      }

      logger.info(`执行平仓: ${signal.side} ${signal.amount} ${signal.symbol}`)

      // 平仓操作
      logger.info(`[模拟平仓] ${signal.side} ${signal.amount} ${signal.symbol} - 成功`)

    } catch (error) {
      logger.error('执行平仓信号失败', { signal, error })
    }
  }

  /**
   * 执行利用率控制信号
   */
  private async executeUtilizationControlSignal(signal: TradingSignal): Promise<void> {
    try {
      logger.info(`执行利用率控制: ${signal.reason}`)

      // 利用率控制通常涉及调整仓位大小或暂停交易
      if (signal.reason?.includes('利用率过高')) {
        logger.warn('账户利用率过高，调整交易策略')
      }

    } catch (error) {
      logger.error('执行利用率控制信号失败', { signal, error })
    }
  }

  /**
   * 检查账户余额
   */
  private checkAccountBalance(): boolean {
    try {
      const accounts = this.accountManager.getAccounts()

      for (const account of accounts) {
        // 简化余额检查 - 假设有足够余额
        // TODO: 实现更详细的余额检查
        logger.debug(`检查账户 ${account.id} 余额`)
        return true
      }

      return true
    } catch (error) {
      logger.error('检查账户余额失败', { error })
      return false
    }
  }

  /**
   * 计算交易金额
   */
  private async calculateTradingAmount(): Promise<string> {
    try {
      // 简化的交易金额计算
      const baseAmount = 0.0005 // 基础金额 0.0005 BTC

      // 根据风险设置调整
      const adjustedAmount = Math.min(baseAmount, this.riskLimits.maxPositionSize)

      return adjustedAmount.toString()
    } catch (error) {
      logger.error('计算交易金额失败', { error })
      return '0'
    }
  }

  /**
   * 同步获取当前价格 - 优先使用WebSocket orderbook数据
   */
  private getCurrentPriceSync(symbol: string): number | null {
    try {
      // 1. 优先尝试从WebSocket orderbook获取实时价格
      if (this.pacificaOrderbookManager) {
        const normalizedSymbol = this.normalizeSymbol(symbol)
        const bestPrices = this.pacificaOrderbookManager.getBestPrices(normalizedSymbol)
        
        if (bestPrices) {
          logger.debug('✅ 使用WebSocket orderbook价格数据', {
            symbol: normalizedSymbol,
            bestBid: bestPrices.bestBid,
            bestAsk: bestPrices.bestAsk,
            midPrice: bestPrices.midPrice,
            spread: `${(bestPrices.spread / bestPrices.bestBid * 100).toFixed(3)}%`
          })
          
          // 返回中间价格作为当前价格
          return bestPrices.midPrice
        } else {
          logger.debug('⚠️ WebSocket orderbook数据不可用，fallback到HTTP API', {
            symbol: normalizedSymbol
          })
        }
      }

      // 2. Fallback: 从价格管理器获取缓存的价格
      const normalizedSymbol = symbol.replace('-', '')
      const price = globalPriceManager.getPrice(normalizedSymbol)

      if (price && price > 0) {
        logger.debug('📊 使用HTTP API缓存价格数据', {
          symbol: normalizedSymbol,
          price: price
        })
        return price
      }

      // 3. 最后的fallback: 返回模拟价格
      if (symbol.includes('BTC')) {
        const mockPrice = 108000 + Math.random() * 2000 // 模拟BTC价格 108k-110k
        logger.debug('🎭 使用模拟价格数据', {
          symbol,
          mockPrice
        })
        return mockPrice
      }

      return null
    } catch (error) {
      logger.error('获取当前价格失败', { symbol, error })
      return null
    }
  }

  /**
   * 标准化交易对符号（Pacifica使用基础符号如BTC）
   */
  private normalizeSymbol(symbol: string): string {
    // 将BTCUSDT, BTC-USD等转换为BTC
    if (symbol.includes('BTC')) return 'BTC'
    if (symbol.includes('ETH')) return 'ETH'
    if (symbol.includes('SOL')) return 'SOL'
    return symbol
  }
}