import { TradingService, ServiceStatus } 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'
import { SignalGenerator } from './SignalGenerator.js'
import { TradeExecutor } from './TradeExecutor.js'
import { OptimizedLimitOrderPricingStrategy } from './OptimizedLimitOrderPricingStrategy.js'

/**
 * 重构后的交易引擎 V2 - 使用模块化设计
 */
export class TradingEngineV2 implements TradingService {
  private isRunning = false
  private tradingIntervals: NodeJS.Timeout[] = []
  private signalGenerator: SignalGenerator
  private tradeExecutor: TradeExecutor
  private optimizedPricingStrategy: OptimizedLimitOrderPricingStrategy

  private stats = {
    totalTrades: 0,
    successfulTrades: 0,
    failedTrades: 0,
    totalVolume: 0,
    lastTradeTime: 0,
    sessionStartTime: Date.now(),
  }

  constructor(
    private accountManager: AccountManager,
    private riskManager: RiskManager,
    private stopLossService: StopLossService,
    private hedgeManager: SamePlatformHedgingManager | null = null,
    private pacificaOrderbookManager?: PacificaOrderbookManager,
  ) {
    // 初始化模块化组件
    this.signalGenerator = new SignalGenerator(
      accountManager,
      riskManager,
      hedgeManager
    )

    this.tradeExecutor = new TradeExecutor(
      accountManager,
      riskManager,
      stopLossService,
      hedgeManager,
      pacificaOrderbookManager
    )

    // 初始化优化限价单定价策略（支持WebSocket orderbook）
    this.optimizedPricingStrategy = new OptimizedLimitOrderPricingStrategy(
      {
        targetFillProbability: 0.8,  // 80% 目标成交率
        aggressiveness: 0.7,         // 70% 激进度
        minProfitMargin: 0.001,      // 0.1% 最小盈利
      },
      pacificaOrderbookManager
    )

    logger.info('🎯 TradingEngine V2 初始化完成', {
      hasOrderbookManager: !!pacificaOrderbookManager,
      pricingStrategy: 'OptimizedLimitOrderPricingStrategy'
    })
  }

  async initialize(): Promise<void> {
    logger.info('TradingEngine V2 初始化')
  }

  async start(): Promise<void> {
    logger.info('TradingEngine V2 启动')
    this.isRunning = true

    // 启动时预热价格缓存
    this.preloadOrderbookPrices()

    // 启动交易循环
    this.startTradingLoop()
  }

  async stop(): Promise<void> {
    logger.info('TradingEngine V2 停止')
    this.isRunning = false

    // 清理所有定时器
    for (const interval of this.tradingIntervals) {
      clearInterval(interval)
    }
    this.tradingIntervals = []

    // 等待当前交易完成
    await new Promise(resolve => setTimeout(resolve, 1000))
  }

  getStatus(): ServiceStatus {
    return {
      name: 'TradingEngine V2',
      status: this.isRunning ? 'running' : 'stopped',
      lastUpdate: Date.now(),
      details: {
        totalTrades: this.stats.totalTrades,
        successRate: this.stats.totalTrades > 0
          ? (this.stats.successfulTrades / this.stats.totalTrades * 100).toFixed(2) + '%'
          : '0%',
        uptime: Date.now() - this.stats.sessionStartTime,
      },
    }
  }

  /**
   * 启动交易循环
   */
  private startTradingLoop(): void {
    // 主交易信号生成循环 - 每30秒
    const mainLoop = setInterval(async () => {
      if (!this.isRunning) return

      try {
        await this.generateAndHandleSignals()
      } catch (error) {
        logger.error('主交易循环出错', { error })
      }
    }, 30000)

    this.tradingIntervals.push(mainLoop)

    // 价格缓存更新循环 - 每10秒
    const priceLoop = setInterval(() => {
      if (!this.isRunning) return
      this.preloadOrderbookPrices()
    }, 10000)

    this.tradingIntervals.push(priceLoop)

    logger.info('交易循环已启动')
  }

  /**
   * 生成并处理交易信号
   */
  private async generateAndHandleSignals(): Promise<void> {
    try {
      // 使用信号生成器生成信号
      const signals = await this.signalGenerator.generateTradingSignals()

      if (signals.length === 0) {
        logger.debug('本轮未生成交易信号')
        return
      }

      logger.info(`生成了 ${signals.length} 个交易信号`)

      // 使用交易执行器处理每个信号
      for (const signal of signals) {
        try {
          await this.tradeExecutor.handleTradingSignal(signal)
          this.stats.successfulTrades++
        } catch (error) {
          logger.error('处理交易信号失败', { signal, error })
          this.stats.failedTrades++
        }

        this.stats.totalTrades++
        this.stats.lastTradeTime = Date.now()
      }

    } catch (error) {
      logger.error('生成和处理交易信号失败', { error })
    }
  }

  /**
   * 预加载订单簿价格
   */
  private preloadOrderbookPrices(): void {
    try {
      const symbols = ['BTCUSDT', 'ETHUSDT', 'BTC-USD']

      for (const symbol of symbols) {
        // 触发价格管理器获取价格
        globalPriceManager.getPrice(symbol)
      }

      logger.debug('价格缓存已更新')
    } catch (error) {
      logger.error('预加载价格失败', { error })
    }
  }

  /**
   * 获取统计信息
   */
  getStats() {
    return {
      ...this.stats,
      successRate: this.stats.totalTrades > 0
        ? (this.stats.successfulTrades / this.stats.totalTrades)
        : 0,
      uptime: Date.now() - this.stats.sessionStartTime,
    }
  }

  /**
   * 获取优化限价单定价策略实例
   */
  getOptimizedPricingStrategy(): OptimizedLimitOrderPricingStrategy {
    return this.optimizedPricingStrategy
  }

  /**
   * 获取Pacifica订单簿管理器
   */
  getPacificaOrderbookManager(): PacificaOrderbookManager | undefined {
    return this.pacificaOrderbookManager
  }
}