import { logger } from '../../utils/logger.js'
import { PacificaProxyClient } from '../../exchanges/pacifica/PacificaProxyClient.js'
import { PacificaOrderbookManager } from '../orderbook/PacificaOrderbookManager.js'

/**
 * 订单簿数据接口
 */
interface OrderBookData {
  bids: Array<{ price: number; amount: number }>
  asks: Array<{ price: number; amount: number }>
  timestamp: number
}

/**
 * 限价单定价结果接口
 */
interface LimitOrderPricing {
  buyPrice: number
  sellPrice: number
  spread: number
  midPrice: number
  confidence: number  // 成交概率信心度 (0-1)
  expectedFillTime: number  // 预期成交时间 (秒)
  reasoning: string
}

/**
 * 定价策略配置
 */
interface PricingConfig {
  // 基础配置
  targetFillProbability: number    // 目标成交概率 (0.7 = 70%)
  maxSpreadTolerance: number       // 最大价差容忍度 (0.005 = 0.5%)
  minProfitMargin: number          // 最小盈利margin (0.001 = 0.1%)

  // 智能定价参数
  aggressiveness: number           // 定价激进度 (0-1, 越高越接近盘口)
  liquidityWeight: number          // 流动性权重 (0-1, 考虑订单簿深度)
  volatilityAdjustment: number     // 波动率调整系数 (0-1)

  // 风险控制
  maxPriceDeviation: number        // 最大价格偏离度 (0.02 = 2%)
  orderBookDepthRequirement: number // 最小订单簿深度要求
}

/**
 * 优化的限价单定价策略
 *
 * 核心改进：
 * 1. 基于真实订单簿数据计算最优价格
 * 2. 智能平衡成交概率和盈利margin
 * 3. 考虑市场流动性和波动性
 * 4. 动态调整定价策略
 */
export class OptimizedLimitOrderPricingStrategy {
  private config: PricingConfig
  private lastOrderBook: OrderBookData | null = null
  private priceHistory: number[] = []
  private recentSpreads: number[] = []
  private pacificaOrderbookManager: PacificaOrderbookManager | null = null

  constructor(config: Partial<PricingConfig> = {}, pacificaOrderbookManager?: PacificaOrderbookManager) {
    this.config = {
      // 默认配置 - 平衡成交率和盈利
      targetFillProbability: 0.75,      // 75% 目标成交率
      maxSpreadTolerance: 0.003,        // 0.3% 最大价差
      minProfitMargin: 0.0008,          // 0.08% 最小盈利

      // 智能定价 - 中等激进度
      aggressiveness: 0.6,              // 60% 激进度
      liquidityWeight: 0.4,             // 40% 流动性权重
      volatilityAdjustment: 0.3,        // 30% 波动率调整

      // 风险控制
      maxPriceDeviation: 0.015,         // 1.5% 最大偏离
      orderBookDepthRequirement: 0.01,  // 0.01 BTC 最小深度

      ...config
    }

    this.pacificaOrderbookManager = pacificaOrderbookManager || null
    logger.info('🎯 优化限价单定价策略初始化', {
      config: this.config,
      hasPacificaOrderbookManager: !!this.pacificaOrderbookManager
    })
  }

  /**
   * 计算优化的限价单价格
   */
  async calculateOptimizedPricing(
    client: PacificaProxyClient,
    symbol: string = 'BTC',
    orderAmount: number = 0.0001
  ): Promise<LimitOrderPricing | null> {
    try {
      logger.debug('开始计算优化限价单价格', { symbol, orderAmount })

      // 1. 获取最新订单簿数据
      const orderBook = await this.fetchOrderBookData(client, symbol)
      if (!orderBook) {
        logger.warn('无法获取订单簿数据，跳过定价计算')
        return null
      }

      // 2. 分析市场状况
      const marketAnalysis = this.analyzeMarketConditions(orderBook)
      if (!marketAnalysis.suitable) {
        logger.debug('市场条件不适合限价单交易', marketAnalysis)
        return null
      }

      // 3. 计算智能价格
      const pricing = this.calculateIntelligentPricing(orderBook, orderAmount, marketAnalysis)

      // 4. 验证价格合理性
      const validatedPricing = this.validatePricing(pricing, orderBook)

      logger.info('✅ 优化限价单价格计算完成', {
        buyPrice: validatedPricing.buyPrice.toFixed(2),
        sellPrice: validatedPricing.sellPrice.toFixed(2),
        spread: `${(validatedPricing.spread * 100).toFixed(3)}%`,
        confidence: `${(validatedPricing.confidence * 100).toFixed(1)}%`,
        expectedFillTime: `${validatedPricing.expectedFillTime}s`,
        reasoning: validatedPricing.reasoning
      })

      return validatedPricing

    } catch (error: any) {
      logger.error('计算优化限价单价格失败', { error: error.message })
      return null
    }
  }

  /**
   * 获取订单簿数据
   */
  private async fetchOrderBookData(client: PacificaProxyClient, symbol: string): Promise<OrderBookData | null> {
    try {
      // 1. 优先尝试从Pacifica WebSocket orderbook管理器获取实时数据
      if (this.pacificaOrderbookManager) {
        const cachedOrderbook = this.pacificaOrderbookManager.getOrderbook(symbol)
        if (cachedOrderbook && cachedOrderbook.isValid) {
          const orderBook: OrderBookData = {
            bids: cachedOrderbook.bids.map(entry => ({
              price: entry.price,
              amount: entry.size
            })),
            asks: cachedOrderbook.asks.map(entry => ({
              price: entry.price,
              amount: entry.size
            })),
            timestamp: cachedOrderbook.timestamp
          }

          this.lastOrderBook = orderBook
          this.updatePriceHistory(orderBook)

          logger.debug('✅ 使用Pacifica WebSocket orderbook数据', {
            symbol,
            bidCount: orderBook.bids.length,
            askCount: orderBook.asks.length,
            bestBid: orderBook.bids[0]?.price.toFixed(2),
            bestAsk: orderBook.asks[0]?.price.toFixed(2),
            dataAge: Date.now() - cachedOrderbook.lastRefresh
          })

          return orderBook
        } else {
          logger.debug('⚠️ Pacifica WebSocket orderbook无效或不存在，fallback到HTTP API', {
            symbol,
            hasCache: !!cachedOrderbook,
            isValid: cachedOrderbook?.isValid
          })
        }
      }

      // 2. Fallback: 使用HTTP API获取订单簿数据
      logger.debug('🔄 使用HTTP API获取orderbook数据 (WebSocket缓存不可用)', { symbol })
      const depthResponse = await client.getOrderBook(symbol, 20)

      if (!depthResponse) {
        logger.warn('获取订单簿数据为空')
        return null
      }

      let orderBook: OrderBookData | null = null

      // 处理不同的订单簿数据格式
      if (depthResponse.bids && depthResponse.asks) {
        // 标准订单簿格式
        orderBook = {
          bids: depthResponse.bids.map((bid: any) => ({
            price: parseFloat(bid.price || bid[0]),
            amount: parseFloat(bid.amount || bid[1])
          })).filter(bid => bid.price > 0 && bid.amount > 0),

          asks: depthResponse.asks.map((ask: any) => ({
            price: parseFloat(ask.price || ask[0]),
            amount: parseFloat(ask.amount || ask[1])
          })).filter(ask => ask.price > 0 && ask.amount > 0),

          timestamp: Date.now()
        }
      } else if (depthResponse.price) {
        // 从价格数据构造模拟订单簿
        const currentPrice = parseFloat(depthResponse.price)
        const spread = currentPrice * 0.001 // 0.1% 模拟价差

        orderBook = {
          bids: [
            { price: currentPrice - spread/2, amount: 0.1 },
            { price: currentPrice - spread, amount: 0.2 },
            { price: currentPrice - spread*1.5, amount: 0.3 }
          ],
          asks: [
            { price: currentPrice + spread/2, amount: 0.1 },
            { price: currentPrice + spread, amount: 0.2 },
            { price: currentPrice + spread*1.5, amount: 0.3 }
          ],
          timestamp: Date.now()
        }

        logger.debug('从价格数据构造模拟订单簿', {
          currentPrice,
          spread: (spread/currentPrice * 100).toFixed(3) + '%'
        })
      } else {
        logger.warn('订单簿数据格式无效', { responseKeys: Object.keys(depthResponse) })
        return null
      }

      // 排序确保价格顺序正确
      orderBook.bids.sort((a, b) => b.price - a.price) // 买单：价格从高到低
      orderBook.asks.sort((a, b) => a.price - b.price) // 卖单：价格从低到高

      this.lastOrderBook = orderBook
      this.updatePriceHistory(orderBook)

      logger.debug('📊 HTTP API orderbook数据获取成功', {
        bidCount: orderBook.bids.length,
        askCount: orderBook.asks.length,
        bestBid: orderBook.bids[0]?.price.toFixed(2),
        bestAsk: orderBook.asks[0]?.price.toFixed(2)
      })

      return orderBook

    } catch (error: any) {
      logger.error('获取订单簿数据失败', { error: error.message })
      return null
    }
  }

  /**
   * 分析市场条件
   */
  private analyzeMarketConditions(orderBook: OrderBookData): {
    suitable: boolean
    spread: number
    liquidity: number
    volatility: number
    reasoning: string
  } {
    const bestBid = orderBook.bids[0]?.price || 0
    const bestAsk = orderBook.asks[0]?.price || 0

    if (bestBid <= 0 || bestAsk <= 0 || bestAsk <= bestBid) {
      return {
        suitable: false,
        spread: 0,
        liquidity: 0,
        volatility: 0,
        reasoning: '无效的买卖价格'
      }
    }

    // 计算价差
    const spread = (bestAsk - bestBid) / bestBid

    // 计算流动性 (前5档总深度)
    const bidLiquidity = orderBook.bids.slice(0, 5).reduce((sum, bid) => sum + bid.amount, 0)
    const askLiquidity = orderBook.asks.slice(0, 5).reduce((sum, ask) => sum + ask.amount, 0)
    const totalLiquidity = Math.min(bidLiquidity, askLiquidity)

    // 计算波动性 (基于最近价格历史)
    const volatility = this.calculateVolatility()

    // 更新价差历史
    this.recentSpreads.push(spread)
    if (this.recentSpreads.length > 20) {
      this.recentSpreads = this.recentSpreads.slice(-20)
    }

    // 判断是否适合交易
    let suitable = true
    let reasoning = '市场条件良好'

    if (spread > this.config.maxSpreadTolerance) {
      suitable = false
      reasoning = `价差过大: ${(spread * 100).toFixed(3)}% > ${(this.config.maxSpreadTolerance * 100).toFixed(3)}%`
    } else if (totalLiquidity < this.config.orderBookDepthRequirement) {
      suitable = false
      reasoning = `流动性不足: ${totalLiquidity.toFixed(4)} BTC < ${this.config.orderBookDepthRequirement} BTC`
    } else if (volatility > 0.05) { // 5% 波动率阈值
      suitable = false
      reasoning = `波动性过高: ${(volatility * 100).toFixed(2)}%`
    }

    return {
      suitable,
      spread,
      liquidity: totalLiquidity,
      volatility,
      reasoning
    }
  }

  /**
   * 计算智能定价
   */
  private calculateIntelligentPricing(
    orderBook: OrderBookData,
    orderAmount: number,
    marketAnalysis: any
  ): LimitOrderPricing {
    const bestBid = orderBook.bids[0].price
    const bestAsk = orderBook.asks[0].price
    const midPrice = (bestBid + bestAsk) / 2
    const currentSpread = marketAnalysis.spread

    // 🎯 智能定价算法

    // 1. 基础价格偏移 (基于激进度)
    const baseOffset = currentSpread * (1 - this.config.aggressiveness)

    // 2. 流动性调整 (流动性越好，价格越接近盘口)
    const liquidityFactor = Math.min(1, marketAnalysis.liquidity / this.config.orderBookDepthRequirement)
    const liquidityAdjustment = baseOffset * (1 - liquidityFactor * this.config.liquidityWeight)

    // 3. 波动率调整 (波动率高时，价格偏离更大)
    const volatilityFactor = Math.min(1, marketAnalysis.volatility / 0.02) // 2% 基准波动率
    const volatilityAdjustment = liquidityAdjustment * (1 + volatilityFactor * this.config.volatilityAdjustment)

    // 4. 计算最终价格
    const priceOffset = Math.max(volatilityAdjustment, currentSpread * 0.1) // 最小保持 10% 价差

    // 确保最小盈利margin
    const minOffset = this.config.minProfitMargin / 2
    const finalOffset = Math.max(priceOffset, minOffset)

    const buyPrice = midPrice - finalOffset * midPrice
    const sellPrice = midPrice + finalOffset * midPrice

    // 价格必须是tick size的倍数 (Pacifica 使用1的倍数)
    const optimizedBuyPrice = Math.floor(buyPrice)
    const optimizedSellPrice = Math.ceil(sellPrice)

    // 5. 计算成交概率和预期时间
    const confidence = this.calculateFillProbability(optimizedBuyPrice, optimizedSellPrice, orderBook)
    const expectedFillTime = this.estimateFillTime(confidence, currentSpread)

    // 6. 生成策略说明
    const reasoning = this.generatePricingReasoning(
      { optimizedBuyPrice, optimizedSellPrice, midPrice, finalOffset },
      { liquidityFactor, volatilityFactor, confidence }
    )

    return {
      buyPrice: optimizedBuyPrice,
      sellPrice: optimizedSellPrice,
      spread: (optimizedSellPrice - optimizedBuyPrice) / midPrice,
      midPrice,
      confidence,
      expectedFillTime,
      reasoning
    }
  }

  /**
   * 计算成交概率
   */
  private calculateFillProbability(buyPrice: number, sellPrice: number, orderBook: OrderBookData): number {
    const bestBid = orderBook.bids[0].price
    const bestAsk = orderBook.asks[0].price

    // 买单成交概率 (价格越接近bestAsk，概率越高)
    const buyDistanceToAsk = (bestAsk - buyPrice) / bestAsk
    const buyProbability = Math.max(0, Math.min(1, 1 - buyDistanceToAsk * 10))

    // 卖单成交概率 (价格越接近bestBid，概率越高)
    const sellDistanceToBid = (sellPrice - bestBid) / bestBid
    const sellProbability = Math.max(0, Math.min(1, 1 - sellDistanceToBid * 10))

    // 综合概率 (取平均值)
    return (buyProbability + sellProbability) / 2
  }

  /**
   * 估算成交时间
   */
  private estimateFillTime(confidence: number, spread: number): number {
    // 基于成交概率和价差估算成交时间
    const baseTime = 60 // 基础60秒
    const confidenceFactor = 1 / Math.max(0.1, confidence) // 概率越低，时间越长
    const spreadFactor = 1 + spread * 20 // 价差越大，时间越长

    return Math.round(baseTime * confidenceFactor * spreadFactor)
  }

  /**
   * 生成定价推理说明
   */
  private generatePricingReasoning(
    pricing: { optimizedBuyPrice: number, optimizedSellPrice: number, midPrice: number, finalOffset: number },
    factors: { liquidityFactor: number, volatilityFactor: number, confidence: number }
  ): string {
    const { optimizedBuyPrice, optimizedSellPrice, midPrice, finalOffset } = pricing
    const { liquidityFactor, volatilityFactor, confidence } = factors

    const offsetPercent = (finalOffset * 100).toFixed(3)
    const buyOffsetPercent = ((midPrice - optimizedBuyPrice) / midPrice * 100).toFixed(3)
    const sellOffsetPercent = ((optimizedSellPrice - midPrice) / midPrice * 100).toFixed(3)

    return `智能定价: 中位价$${midPrice.toFixed(2)}, 买单-${buyOffsetPercent}%@$${optimizedBuyPrice}, 卖单+${sellOffsetPercent}%@$${optimizedSellPrice}. ` +
           `流动性${(liquidityFactor * 100).toFixed(0)}%, 波动性${(volatilityFactor * 100).toFixed(0)}%, 成交概率${(confidence * 100).toFixed(0)}%`
  }

  /**
   * 验证定价合理性
   */
  private validatePricing(pricing: LimitOrderPricing, orderBook: OrderBookData): LimitOrderPricing {
    const bestBid = orderBook.bids[0].price
    const bestAsk = orderBook.asks[0].price

    // 确保买价不高于最佳卖价，卖价不低于最佳买价
    const validatedBuyPrice = Math.min(pricing.buyPrice, bestAsk * 0.999) // 留0.1%缓冲
    const validatedSellPrice = Math.max(pricing.sellPrice, bestBid * 1.001) // 留0.1%缓冲

    // 确保价格不超过最大偏离度
    const maxDeviation = this.config.maxPriceDeviation
    const midPrice = pricing.midPrice

    const finalBuyPrice = Math.max(validatedBuyPrice, midPrice * (1 - maxDeviation))
    const finalSellPrice = Math.min(validatedSellPrice, midPrice * (1 + maxDeviation))

    // 重新计算相关指标
    const finalSpread = (finalSellPrice - finalBuyPrice) / midPrice
    const finalConfidence = this.calculateFillProbability(finalBuyPrice, finalSellPrice, orderBook)
    const finalExpectedTime = this.estimateFillTime(finalConfidence, finalSpread)

    return {
      ...pricing,
      buyPrice: finalBuyPrice,
      sellPrice: finalSellPrice,
      spread: finalSpread,
      confidence: finalConfidence,
      expectedFillTime: finalExpectedTime,
      reasoning: pricing.reasoning + ' (已验证边界)'
    }
  }

  /**
   * 更新价格历史
   */
  private updatePriceHistory(orderBook: OrderBookData): void {
    const midPrice = (orderBook.bids[0].price + orderBook.asks[0].price) / 2
    this.priceHistory.push(midPrice)

    // 保留最近50个价格点
    if (this.priceHistory.length > 50) {
      this.priceHistory = this.priceHistory.slice(-50)
    }
  }

  /**
   * 计算波动率
   */
  private calculateVolatility(): number {
    if (this.priceHistory.length < 10) {
      return 0.01 // 默认1%波动率
    }

    const prices = this.priceHistory.slice(-20) // 最近20个价格点
    const returns = []

    for (let i = 1; i < prices.length; i++) {
      const returnRate = (prices[i] - prices[i-1]) / prices[i-1]
      returns.push(returnRate)
    }

    // 计算标准差
    const mean = returns.reduce((sum, r) => sum + r, 0) / returns.length
    const variance = returns.reduce((sum, r) => sum + Math.pow(r - mean, 2), 0) / returns.length
    const stdDev = Math.sqrt(variance)

    return stdDev
  }

  /**
   * 动态调整策略配置
   */
  adjustConfig(newConfig: Partial<PricingConfig>): void {
    this.config = { ...this.config, ...newConfig }
    logger.info('🔧 限价单定价策略配置已调整', newConfig)
  }

  /**
   * 获取策略统计
   */
  getStats(): {
    config: PricingConfig
    recentSpreads: number[]
    averageSpread: number
    volatility: number
    lastOrderBook: OrderBookData | null
  } {
    const averageSpread = this.recentSpreads.length > 0 ?
      this.recentSpreads.reduce((sum, s) => sum + s, 0) / this.recentSpreads.length : 0

    return {
      config: this.config,
      recentSpreads: this.recentSpreads.slice(-10),
      averageSpread,
      volatility: this.calculateVolatility(),
      lastOrderBook: this.lastOrderBook
    }
  }

  /**
   * 获取当前最佳买卖价格 (用于快速查询)
   */
  getCurrentBestPrices(): { bestBid: number, bestAsk: number, midPrice: number, spread: number } | null {
    if (!this.lastOrderBook || this.lastOrderBook.bids.length === 0 || this.lastOrderBook.asks.length === 0) {
      return null
    }

    const bestBid = this.lastOrderBook.bids[0].price
    const bestAsk = this.lastOrderBook.asks[0].price
    const midPrice = (bestBid + bestAsk) / 2
    const spread = (bestAsk - bestBid) / midPrice

    return { bestBid, bestAsk, midPrice, spread }
  }
}