import { EventEmitter } from 'events'
import { logger } from '../../utils/logger.js'

/**
 * 实时成功率监控器
 * 用于追踪和显示双向盈利挂单的成功率统计
 */
export class SuccessRateMonitor extends EventEmitter {
  private isRunning = false
  private displayInterval: NodeJS.Timeout | null = null

  constructor(private strategy: any) {
    super()
    this.setupEventListeners()
  }

  /**
   * 启动监控显示
   */
  start(): void {
    if (this.isRunning) return

    this.isRunning = true
    logger.info('📊 启动成功率监控器')

    // 每10秒更新一次显示
    this.displayInterval = setInterval(() => {
      this.displayStats()
    }, 10000)

    // 立即显示一次
    this.displayStats()
  }

  /**
   * 停止监控
   */
  stop(): void {
    if (!this.isRunning) return

    this.isRunning = false

    if (this.displayInterval) {
      clearInterval(this.displayInterval)
      this.displayInterval = null
    }

    logger.info('成功率监控器已停止')
  }

  /**
   * 设置事件监听器
   */
  private setupEventListeners(): void {
    // 监听订单放置事件
    this.strategy.on('orderPlaced', (order: any) => {
      console.log(`📋 挂单: ${order.side.toUpperCase()} ${order.amount} BTC @$${order.price.toFixed(2)} (预期盈利: $${order.expectedProfit.toFixed(2)})`)
    })

    // 监听订单完成事件
    this.strategy.on('orderCompleted', (data: any) => {
      const statusEmoji = {
        filled: '✅',
        cancelled: '❌',
        timeout: '⏰'
      }[data.status] || '❓'

      const profitText = data.profit > 0 ? `+$${data.profit.toFixed(2)}` : data.profit < 0 ? `-$${Math.abs(data.profit).toFixed(2)}` : '$0.00'
      const timeText = data.fillTime > 0 ? `${(data.fillTime / 1000).toFixed(1)}s` : 'N/A'

      console.log(`${statusEmoji} 订单${data.status}: ${data.orderId.substring(0, 8)}... | 盈利: ${profitText} | 用时: ${timeText}`)
    })

    // 监听统计更新事件
    this.strategy.on('statsUpdated', (stats: any) => {
      // 可以在这里添加实时警报逻辑
      if (stats.successRate < 0.6) {
        console.log('⚠️ 警告: 成功率低于60%')
      }
    })
  }

  /**
   * 显示详细统计信息
   */
  private displayStats(): void {
    const report = this.strategy.getDetailedReport()
    const stats = report.stats
    const performance = report.performance

    console.clear()
    console.log('╔══════════════════════════════════════════════════════════════════════════════╗')
    console.log('║                        📊 双向盈利挂单策略监控面板                            ║')
    console.log('╚══════════════════════════════════════════════════════════════════════════════╝')
    console.log()

    // 基础统计
    console.log('📈 基础统计')
    console.log('────────────────────────────────────────────────────────────────────────────────')
    console.log(`🎯 总订单数: ${stats.totalOrders}`)
    console.log(`✅ 成交订单: ${stats.filledOrders} (${(stats.successRate * 100).toFixed(1)}%)`)
    console.log(`❌ 取消订单: ${stats.cancelledOrders}`)
    console.log(`⏰ 超时订单: ${stats.timeoutOrders}`)
    console.log(`🔄 活跃订单: ${report.activeOrders.length}`)
    console.log()

    // 盈利统计
    console.log('💰 盈利统计')
    console.log('────────────────────────────────────────────────────────────────────────────────')
    console.log(`💵 总盈利: $${stats.totalProfit.toFixed(2)}`)
    console.log(`📊 盈利率: ${(stats.profitRate * 100).toFixed(1)}%`)
    console.log(`⏱️ 平均成交时间: ${(stats.averageFillTime / 1000).toFixed(1)}秒`)
    console.log(`🕐 小时盈利: $${performance.hourlyProfit.toFixed(2)}`)
    console.log(`📅 日盈利: $${performance.dailyProfit.toFixed(2)}`)
    console.log(`📈 ROI: ${performance.roi.toFixed(2)}%`)
    console.log()

    // 活跃订单详情
    if (report.activeOrders.length > 0) {
      console.log('🔄 活跃订单详情')
      console.log('────────────────────────────────────────────────────────────────────────────────')
      report.activeOrders.forEach((order, index) => {
        const elapsed = Math.floor((Date.now() - order.timestamp) / 1000)
        const remaining = Math.max(0, report.config.orderTimeout - elapsed)
        console.log(`${index + 1}. ${order.side.toUpperCase()} ${order.amount} BTC @$${order.price.toFixed(2)} | 剩余: ${remaining}s | 预期: +$${order.expectedProfit.toFixed(2)}`)
      })
      console.log()
    }

    // 策略配置
    console.log('⚙️ 策略配置')
    console.log('────────────────────────────────────────────────────────────────────────────────')
    console.log(`💹 盈利Margin: ${(report.config.profitMargin * 100).toFixed(2)}%`)
    console.log(`⏰ 订单超时: ${report.config.orderTimeout}秒`)
    console.log(`📊 最大活跃订单: ${report.config.maxActiveOrders}`)
    console.log(`💰 单笔金额: ${report.config.orderAmount} BTC`)
    console.log(`📏 价差阈值: ${(report.config.spreadThreshold * 100).toFixed(2)}%`)
    console.log(`📈 波动率限制: ${(report.config.volatilityLimit * 100).toFixed(1)}%`)
    console.log()

    // 性能指标
    const efficiency = stats.totalOrders > 0 ? (stats.filledOrders / stats.totalOrders) * 100 : 0
    const profitability = stats.filledOrders > 0 ? (stats.totalProfit / stats.filledOrders) : 0

    console.log('🎯 性能指标')
    console.log('────────────────────────────────────────────────────────────────────────────────')
    console.log(`📊 执行效率: ${efficiency.toFixed(1)}%`)
    console.log(`💰 单笔平均盈利: $${profitability.toFixed(2)}`)
    console.log(`⚡ 策略状态: ${this.getStrategyStatus(stats)}`)
    console.log()

    // 实时提示
    console.log('💡 实时提示')
    console.log('────────────────────────────────────────────────────────────────────────────────')
    this.displayRealTimeHints(stats, report.config)

    console.log('─'.repeat(80))
    console.log(`🕒 最后更新: ${new Date().toLocaleTimeString()}`)
  }

  /**
   * 获取策略状态
   */
  private getStrategyStatus(stats: any): string {
    if (stats.successRate >= 0.8) return '🟢 优秀'
    if (stats.successRate >= 0.6) return '🟡 良好'
    if (stats.successRate >= 0.4) return '🟠 一般'
    return '🔴 需要优化'
  }

  /**
   * 显示实时提示
   */
  private displayRealTimeHints(stats: any, config: any): void {
    const hints: string[] = []

    // 成功率相关提示
    if (stats.successRate < 0.5) {
      hints.push('⚠️ 成功率偏低，考虑调整价格偏移或减少超时时间')
    } else if (stats.successRate > 0.9) {
      hints.push('💡 成功率很高，可以尝试增加盈利margin或减少价格偏移')
    }

    // 盈利率相关提示
    if (stats.profitRate < 0.7 && stats.totalProfit < 0) {
      hints.push('📉 盈利率偏低，建议增加最小盈利阈值')
    }

    // 活跃订单相关提示
    if (stats.totalOrders > 0 && (stats.filledOrders + stats.cancelledOrders + stats.timeoutOrders) / stats.totalOrders < 0.1) {
      hints.push('🔄 大量订单等待中，市场可能流动性不足')
    }

    // 超时相关提示
    if (stats.timeoutOrders / Math.max(stats.totalOrders, 1) > 0.3) {
      hints.push('⏰ 超时订单较多，考虑增加超时时间或调整价格策略')
    }

    // 显示提示或默认消息
    if (hints.length > 0) {
      hints.forEach(hint => console.log(hint))
    } else {
      console.log('✅ 策略运行正常，继续监控...')
    }
  }

  /**
   * 生成简化报告
   */
  generateSummaryReport(): string {
    const stats = this.strategy.getStats()
    const successRate = (stats.successRate * 100).toFixed(1)
    const profitRate = (stats.profitRate * 100).toFixed(1)

    return `📊 双向挂单统计: 总单${stats.totalOrders} | 成交率${successRate}% | 盈利率${profitRate}% | 总盈利$${stats.totalProfit.toFixed(2)} | 活跃单${stats.activeOrders}`
  }

  /**
   * 获取关键指标
   */
  getKeyMetrics(): {
    successRate: number
    profitRate: number
    totalProfit: number
    averageProfit: number
    activeOrders: number
    efficiency: number
  } {
    const stats = this.strategy.getStats()
    const totalCompleted = stats.filledOrders + stats.cancelledOrders + stats.timeoutOrders
    const efficiency = stats.totalOrders > 0 ? (totalCompleted / stats.totalOrders) : 0
    const averageProfit = stats.filledOrders > 0 ? (stats.totalProfit / stats.filledOrders) : 0

    return {
      successRate: stats.successRate,
      profitRate: stats.profitRate,
      totalProfit: stats.totalProfit,
      averageProfit,
      activeOrders: stats.activeOrders,
      efficiency
    }
  }

  /**
   * 导出历史数据
   */
  exportHistoryData(): {
    timestamp: number
    summary: string
    detailedStats: any
  } {
    return {
      timestamp: Date.now(),
      summary: this.generateSummaryReport(),
      detailedStats: this.strategy.getDetailedReport()
    }
  }
}