/**
 * 🎯 Delta中性交易引擎 v2.0 - 企业级Delta中性交易执行系统
 *
 * 基于tasks规范重构的交易引擎，专注于：
 * - Delta中性策略执行
 * - 智能对冲交易协调
 * - 利用率目标维护（50%-80%）
 * - 多平台订单路由和执行
 * - 实时风险控制和止损
 * - 交易性能监控和报告
 */

import { TradingService, ServiceStatus } from '../types'
import UnifiedAccountManager from '../../models/UnifiedAccountManager'
import { RiskEnvelopeManager, ViolationEvent } from '../../models/RiskEnvelope'
import {
  DeltaNeutralController,
  DeltaNeutralPlan,
  DeltaNeutralExecutionResult,
} from '../../controllers/DeltaNeutralController'
import { ExchangeAccount } from '../../models/ExchangeAccount'
import { CacheManager } from '../cache/CacheManager'
import { logger } from '../shared/utils/logger'

/**
 * Delta中性交易信号
 */
export interface DeltaNeutralSignal {
  signalId: string
  accountId: string
  signalType: 'delta-rebalance' | 'utilization-adjust' | 'emergency-hedge' | 'profit-taking'
  priority: 'low' | 'medium' | 'high' | 'critical'

  // 交易参数
  symbol: string
  side: 'buy' | 'sell'
  quantity: number
  expectedDeltaImpact: number
  expectedUtilizationImpact: number

  // 执行策略
  executionStrategy: 'market' | 'limit' | 'maker-taker-mixed'
  maxSlippage: number
  timeoutMs: number

  // 元数据
  createdAt: Date
  validUntil: Date
  riskScore: number

  // 依赖和约束
  dependsOn?: string[] // 依赖的其他信号
  conflictsWith?: string[] // 冲突的信号
  maxRetries: number
}

/**
 * 交易执行结果
 */
export interface DeltaNeutralTradeResult {
  signalId: string
  success: boolean
  accountId: string

  // 执行详情
  orderId?: string
  executedQuantity: number
  executedPrice: number
  executionTime: number
  fees: number

  // Delta影响
  deltaBefore: number
  deltaAfter: number
  actualDeltaImpact: number

  // 利用率影响
  utilizationBefore: number
  utilizationAfter: number
  actualUtilizationImpact: number

  // 风险和违规
  riskViolations: ViolationEvent[]
  riskScore: number

  // 性能指标
  slippage: number
  latency: number

  // 错误信息
  errors: string[]
  warnings: string[]

  timestamp: Date
}

/**
 * 交易引擎配置
 */
export interface DeltaNeutralTradingConfig {
  // 执行控制
  maxConcurrentTrades: number // 最大并发交易数
  maxTradesPerSecond: number // 每秒最大交易数
  signalProcessingInterval: number // 信号处理间隔

  // Delta中性参数
  deltaThresholdForTrading: number // 交易触发Delta阈值
  utilizationRebalanceThreshold: number // 利用率再平衡阈值
  emergencyHedgeThreshold: number // 紧急对冲阈值

  // 风险控制
  maxSlippageAllowed: number // 最大允许滑点
  maxOrderSize: number // 最大订单大小
  riskScoreThreshold: number // 风险分数阈值

  // 性能优化
  enableSmartRouting: boolean // 启用智能路由
  enableLatencyOptimization: boolean // 启用延迟优化
  batchOrderExecution: boolean // 启用批量订单执行
}

/**
 * 引擎性能指标
 */
export interface TradingEngineMetrics {
  // 基本统计
  totalSignals: number
  processedSignals: number
  successfulTrades: number
  failedTrades: number

  // Delta中性指标
  avgDeltaReductionPerTrade: number
  deltaControlEfficiency: number // Delta控制效率
  utilizationMaintainanceRate: number // 利用率维护率

  // 性能指标
  avgExecutionTime: number
  avgSlippage: number
  avgLatency: number
  throughputPerSecond: number

  // 风险指标
  totalRiskViolations: number
  emergencyTradesExecuted: number
  riskAdjustedReturn: number

  // 时间范围
  periodStart: Date
  periodEnd: Date
  lastUpdate: Date
}

/**
 * Delta中性交易引擎
 */
export class DeltaNeutralTradingEngine implements TradingService {
  private status: 'stopped' | 'initializing' | 'running' | 'stopping' | 'error' = 'stopped'
  private lastStatusChange = Date.now()

  // 运行状态
  private signalQueue: DeltaNeutralSignal[] = []
  private activeTrades: Map<string, DeltaNeutralTradeResult> = new Map()
  private processingInterval?: NodeJS.Timeout
  private metricsReportInterval?: NodeJS.Timeout

  // 配置和指标
  private config: DeltaNeutralTradingConfig
  private metrics: TradingEngineMetrics

  constructor(
    private accountManager: UnifiedAccountManager,
    private riskEnvelopeManager: RiskEnvelopeManager,
    private deltaNeutralController: DeltaNeutralController,
    private cacheManager: CacheManager,
    config?: Partial<DeltaNeutralTradingConfig>,
  ) {
    // 初始化配置
    this.config = {
      maxConcurrentTrades: 10,
      maxTradesPerSecond: 5,
      signalProcessingInterval: 2000,
      deltaThresholdForTrading: 0.0005,
      utilizationRebalanceThreshold: 0.05,
      emergencyHedgeThreshold: 0.001,
      maxSlippageAllowed: 0.001,
      maxOrderSize: 0.1,
      riskScoreThreshold: 80,
      enableSmartRouting: true,
      enableLatencyOptimization: true,
      batchOrderExecution: true,
      ...config,
    }

    // 初始化指标
    this.metrics = {
      totalSignals: 0,
      processedSignals: 0,
      successfulTrades: 0,
      failedTrades: 0,
      avgDeltaReductionPerTrade: 0,
      deltaControlEfficiency: 1,
      utilizationMaintainanceRate: 1,
      avgExecutionTime: 0,
      avgSlippage: 0,
      avgLatency: 0,
      throughputPerSecond: 0,
      totalRiskViolations: 0,
      emergencyTradesExecuted: 0,
      riskAdjustedReturn: 0,
      periodStart: new Date(),
      periodEnd: new Date(),
      lastUpdate: new Date(),
    }

    this.setupEventHandlers()
  }

  /**
   * 初始化交易引擎
   */
  async initialize(): Promise<void> {
    logger.info('🎯 DeltaNeutralTradingEngine v2.0 初始化开始')
    this.status = 'initializing'
    this.lastStatusChange = Date.now()

    try {
      // 1. 验证依赖服务
      await this.validateDependencies()

      // 2. 初始化交易路由
      await this.initializeTradingRoutes()

      // 3. 设置信号监听
      this.setupSignalListeners()

      // 4. 初始化性能监控
      this.initializePerformanceMonitoring()

      this.status = 'running'
      this.lastStatusChange = Date.now()

      logger.info('✅ DeltaNeutralTradingEngine v2.0 初始化完成')
      logger.info(`🎯 Delta交易阈值: ±${this.config.deltaThresholdForTrading} BTC`)
      logger.info(`📊 利用率再平衡阈值: ${this.config.utilizationRebalanceThreshold}`)
      logger.info(`⚡ 最大并发交易数: ${this.config.maxConcurrentTrades}`)
    } catch (error) {
      this.status = 'error'
      this.lastStatusChange = Date.now()
      logger.error('❌ DeltaNeutralTradingEngine 初始化失败:', error)
      throw error
    }
  }

  /**
   * 启动交易引擎
   */
  async start(): Promise<void> {
    if (this.status !== 'running') {
      throw new Error('DeltaNeutralTradingEngine 必须先完成初始化')
    }

    logger.info('🚀 DeltaNeutralTradingEngine v2.0 启动中')

    try {
      // 1. 启动信号处理循环
      this.startSignalProcessing()

      // 2. 启动性能监控
      this.startPerformanceReporting()

      // 3. 执行启动后Delta检查
      await this.performInitialDeltaCheck()

      logger.info('✅ DeltaNeutralTradingEngine v2.0 启动完成')
      logger.info(`🔄 信号处理间隔: ${this.config.signalProcessingInterval}ms`)
      logger.info('🎯 Delta中性交易系统已激活')
    } catch (error) {
      this.status = 'error'
      this.lastStatusChange = Date.now()
      logger.error('❌ DeltaNeutralTradingEngine 启动失败:', error)
      throw error
    }
  }

  /**
   * 停止交易引擎
   */
  async stop(): Promise<void> {
    logger.info('🛑 DeltaNeutralTradingEngine v2.0 停止中')
    this.status = 'stopping'
    this.lastStatusChange = Date.now()

    try {
      // 1. 停止信号处理
      this.stopSignalProcessing()

      // 2. 等待活跃交易完成
      await this.waitForActiveTradesCompletion()

      // 3. 生成最终性能报告
      await this.generateFinalPerformanceReport()

      // 4. 清理资源
      this.cleanup()

      this.status = 'stopped'
      this.lastStatusChange = Date.now()

      logger.info('✅ DeltaNeutralTradingEngine v2.0 已安全停止')
      logger.info(`📊 处理信号总数: ${this.metrics.processedSignals}`)
      logger.info(`✅ 成功交易: ${this.metrics.successfulTrades}`)
      logger.info(`❌ 失败交易: ${this.metrics.failedTrades}`)
    } catch (error) {
      this.status = 'error'
      this.lastStatusChange = Date.now()
      logger.error('❌ DeltaNeutralTradingEngine 停止失败:', error)
      throw error
    }
  }

  /**
   * 提交Delta中性交易信号
   */
  async submitSignal(signal: DeltaNeutralSignal): Promise<void> {
    logger.info(`📬 收到Delta中性交易信号: ${signal.signalId}`, {
      type: signal.signalType,
      priority: signal.priority,
      account: signal.accountId,
      deltaImpact: signal.expectedDeltaImpact,
    })

    try {
      // 1. 验证信号
      this.validateSignal(signal)

      // 2. 检查冲突
      this.checkSignalConflicts(signal)

      // 3. 添加到队列
      this.addToSignalQueue(signal)

      this.metrics.totalSignals++

      logger.info(`✅ 信号 ${signal.signalId} 已加入处理队列`)
    } catch (error) {
      logger.error(`❌ 信号 ${signal.signalId} 提交失败:`, error)
      throw error
    }
  }

  /**
   * 生成Delta再平衡信号
   */
  async generateDeltaRebalanceSignals(): Promise<DeltaNeutralSignal[]> {
    const signals: DeltaNeutralSignal[] = []
    const accounts = this.accountManager.getAccountsNeedingHedge()

    for (const account of accounts) {
      if (account.needsEmergencyHedge() || account.needsRebalance()) {
        const signal = await this.createRebalanceSignal(account)
        signals.push(signal)
      }
    }

    logger.info(`🎯 生成了 ${signals.length} 个Delta再平衡信号`)
    return signals
  }

  /**
   * 获取引擎指标
   */
  getMetrics(): TradingEngineMetrics {
    return { ...this.metrics }
  }

  /**
   * 获取活跃交易
   */
  getActiveTrades(): DeltaNeutralTradeResult[] {
    return Array.from(this.activeTrades.values())
  }

  /**
   * 获取信号队列状态
   */
  getSignalQueueStatus() {
    return {
      queueLength: this.signalQueue.length,
      priorityBreakdown: {
        critical: this.signalQueue.filter(s => s.priority === 'critical').length,
        high: this.signalQueue.filter(s => s.priority === 'high').length,
        medium: this.signalQueue.filter(s => s.priority === 'medium').length,
        low: this.signalQueue.filter(s => s.priority === 'low').length,
      },
      oldestSignal: this.signalQueue.length > 0 ? this.signalQueue[0].createdAt : null,
    }
  }

  /**
   * 获取服务状态
   */
  getStatus(): ServiceStatus {
    return {
      name: 'DeltaNeutralTradingEngine',
      status: this.status === 'running' ? 'running' : this.status === 'error' ? 'error' : 'stopped',
      lastUpdate: this.lastStatusChange,
      details: {
        signalQueueLength: this.signalQueue.length,
        activeTrades: this.activeTrades.size,
        totalSignals: this.metrics.totalSignals,
        successRate: this.calculateSuccessRate(),
        avgExecutionTime: this.metrics.avgExecutionTime,
      },
    }
  }

  getLastStatusChange(): number {
    return this.lastStatusChange
  }

  // ========== 私有方法 ==========

  /**
   * 设置事件处理器
   */
  private setupEventHandlers(): void {
    // 监听账户Delta违规事件
    this.accountManager.on('account-delta-violation', data => {
      this.handleDeltaViolation(data)
    })

    // 监听账户利用率违规事件
    this.accountManager.on('account-utilization-violation', data => {
      this.handleUtilizationViolation(data)
    })

    // 监听紧急状态事件
    this.accountManager.on('account-emergency', data => {
      this.handleAccountEmergency(data)
    })
  }

  /**
   * 验证依赖服务
   */
  private async validateDependencies(): Promise<void> {
    if (!this.accountManager) {
      throw new Error('AccountManager 依赖未提供')
    }

    if (!this.deltaNeutralController) {
      throw new Error('DeltaNeutralController 依赖未提供')
    }

    if (!this.riskEnvelopeManager) {
      throw new Error('RiskEnvelopeManager 依赖未提供')
    }

    logger.info('✅ 依赖服务验证通过')
  }

  /**
   * 初始化交易路由
   */
  private async initializeTradingRoutes(): Promise<void> {
    // 这里可以初始化交易所连接和路由配置
    logger.info('🛣️ 交易路由初始化完成')
  }

  /**
   * 设置信号监听
   */
  private setupSignalListeners(): void {
    // 可以监听外部信号源
    logger.info('📡 信号监听设置完成')
  }

  /**
   * 初始化性能监控
   */
  private initializePerformanceMonitoring(): void {
    this.metrics.periodStart = new Date()
    logger.info('📊 性能监控初始化完成')
  }

  /**
   * 启动信号处理
   */
  private startSignalProcessing(): void {
    this.processingInterval = setInterval(async () => {
      try {
        await this.processSignalQueue()
      } catch (error) {
        logger.error('❌ 信号处理循环失败:', error)
      }
    }, this.config.signalProcessingInterval)

    logger.info(`🔄 信号处理循环已启动 (${this.config.signalProcessingInterval}ms)`)
  }

  /**
   * 停止信号处理
   */
  private stopSignalProcessing(): void {
    if (this.processingInterval) {
      clearInterval(this.processingInterval)
      this.processingInterval = undefined
      logger.info('⏹️ 信号处理循环已停止')
    }
  }

  /**
   * 启动性能报告
   */
  private startPerformanceReporting(): void {
    this.metricsReportInterval = setInterval(() => {
      this.updateMetrics()
      this.logPerformanceReport()
    }, 60000) // 1分钟报告间隔

    logger.info('📊 性能报告已启动 (60秒间隔)')
  }

  /**
   * 处理信号队列
   */
  private async processSignalQueue(): Promise<void> {
    if (this.signalQueue.length === 0) return

    // 按优先级排序
    this.signalQueue.sort((a, b) => {
      const priorityOrder = { critical: 4, high: 3, medium: 2, low: 1 }
      return priorityOrder[b.priority] - priorityOrder[a.priority]
    })

    // 处理最高优先级信号
    const signal = this.signalQueue.shift()
    if (signal) {
      await this.processSignal(signal)
    }
  }

  /**
   * 处理单个信号
   */
  private async processSignal(signal: DeltaNeutralSignal): Promise<void> {
    logger.info(`🔄 处理信号: ${signal.signalId} (${signal.signalType})`)

    try {
      // 1. 检查是否已过期
      if (new Date() > signal.validUntil) {
        logger.warn(`⏰ 信号 ${signal.signalId} 已过期`)
        return
      }

      // 2. 检查并发限制
      if (this.activeTrades.size >= this.config.maxConcurrentTrades) {
        this.signalQueue.unshift(signal) // 放回队列
        return
      }

      // 3. 执行交易
      const result = await this.executeSignal(signal)

      // 4. 记录结果
      this.activeTrades.set(signal.signalId, result)
      this.metrics.processedSignals++

      if (result.success) {
        this.metrics.successfulTrades++
      } else {
        this.metrics.failedTrades++
      }

      // 5. 清理完成的交易
      setTimeout(() => {
        this.activeTrades.delete(signal.signalId)
      }, 30000) // 30秒后清理
    } catch (error) {
      logger.error(`❌ 处理信号 ${signal.signalId} 失败:`, error)
      this.metrics.failedTrades++
    }
  }

  /**
   * 执行信号
   */
  private async executeSignal(signal: DeltaNeutralSignal): Promise<DeltaNeutralTradeResult> {
    const startTime = Date.now()
    const account = this.accountManager.getAccount(signal.accountId)

    if (!account) {
      throw new Error(`账户 ${signal.accountId} 未找到`)
    }

    const metricsBefore = account.getMetrics()

    // 模拟交易执行（实际实现需要调用交易所API）
    const executionTime = Math.random() * 1000 + 500 // 0.5-1.5秒
    await new Promise(resolve => setTimeout(resolve, executionTime))

    // 模拟Delta影响
    const actualDeltaImpact = signal.expectedDeltaImpact * (0.9 + Math.random() * 0.2)
    const deltaAfter = metricsBefore.currentDelta + actualDeltaImpact

    // 模拟利用率影响
    const actualUtilizationImpact = signal.expectedUtilizationImpact * (0.95 + Math.random() * 0.1)
    const utilizationAfter = metricsBefore.currentUtilization + actualUtilizationImpact

    // 更新账户指标
    account.updateMetrics({
      currentDelta: deltaAfter,
      currentUtilization: utilizationAfter,
      lastUpdate: new Date(),
    })

    const result: DeltaNeutralTradeResult = {
      signalId: signal.signalId,
      success: Math.random() > 0.05, // 95%成功率
      accountId: signal.accountId,

      orderId: `order-${Date.now()}`,
      executedQuantity: signal.quantity,
      executedPrice: 65000 + (Math.random() - 0.5) * 100,
      executionTime: Date.now() - startTime,
      fees: signal.quantity * 0.0002,

      deltaBefore: metricsBefore.currentDelta,
      deltaAfter,
      actualDeltaImpact,

      utilizationBefore: metricsBefore.currentUtilization,
      utilizationAfter,
      actualUtilizationImpact,

      riskViolations: [],
      riskScore: Math.random() * 100,

      slippage: Math.random() * 0.0005,
      latency: Math.random() * 100 + 50,

      errors: [],
      warnings: [],

      timestamp: new Date(),
    }

    logger.info(`✅ 信号 ${signal.signalId} 执行完成`, {
      success: result.success,
      deltaImpact: actualDeltaImpact.toFixed(6),
      utilizationImpact: (actualUtilizationImpact * 100).toFixed(2) + '%',
      executionTime: result.executionTime + 'ms',
    })

    return result
  }

  /**
   * 验证信号
   */
  private validateSignal(signal: DeltaNeutralSignal): void {
    if (!signal.signalId) {
      throw new Error('signalId 是必需的')
    }

    if (!signal.accountId) {
      throw new Error('accountId 是必需的')
    }

    if (signal.quantity <= 0) {
      throw new Error('quantity 必须大于0')
    }

    if (signal.riskScore > this.config.riskScoreThreshold) {
      throw new Error(`风险分数 ${signal.riskScore} 超过阈值 ${this.config.riskScoreThreshold}`)
    }
  }

  /**
   * 检查信号冲突
   */
  private checkSignalConflicts(signal: DeltaNeutralSignal): void {
    // 检查是否与队列中的信号冲突
    const conflictingSignals = this.signalQueue.filter(
      existing =>
        existing.accountId === signal.accountId &&
        existing.symbol === signal.symbol &&
        signal.conflictsWith?.includes(existing.signalId),
    )

    if (conflictingSignals.length > 0) {
      throw new Error(`信号与现有信号冲突: ${conflictingSignals.map(s => s.signalId).join(', ')}`)
    }
  }

  /**
   * 添加到信号队列
   */
  private addToSignalQueue(signal: DeltaNeutralSignal): void {
    this.signalQueue.push(signal)
  }

  /**
   * 创建再平衡信号
   */
  private async createRebalanceSignal(account: ExchangeAccount): Promise<DeltaNeutralSignal> {
    const config = account.getConfig()
    const metrics = account.getMetrics()
    const hedgeSize = account.calculateHedgeSize()

    const signal: DeltaNeutralSignal = {
      signalId: `rebalance-${Date.now()}-${config.accountId}`,
      accountId: config.accountId,
      signalType: account.needsEmergencyHedge() ? 'emergency-hedge' : 'delta-rebalance',
      priority: account.needsEmergencyHedge() ? 'critical' : 'medium',

      symbol: 'BTC-USD',
      side: metrics.currentDelta > 0 ? 'sell' : 'buy',
      quantity: hedgeSize,
      expectedDeltaImpact: -metrics.currentDelta, // 趋向于0
      expectedUtilizationImpact: account.calculateUtilizationAdjustment(),

      executionStrategy: account.needsEmergencyHedge() ? 'market' : 'maker-taker-mixed',
      maxSlippage: account.needsEmergencyHedge() ? 0.002 : 0.001,
      timeoutMs: account.needsEmergencyHedge() ? 5000 : 30000,

      createdAt: new Date(),
      validUntil: new Date(Date.now() + 60000), // 1分钟有效期
      riskScore: account.needsEmergencyHedge() ? 95 : 50,

      maxRetries: account.needsEmergencyHedge() ? 5 : 3,
    }

    return signal
  }

  /**
   * 处理Delta违规
   */
  private async handleDeltaViolation(data: any): Promise<void> {
    logger.warn(`🚨 处理Delta违规: ${data.accountId}`)

    const account = this.accountManager.getAccount(data.accountId)
    if (account) {
      const signal = await this.createRebalanceSignal(account)
      await this.submitSignal(signal)
    }
  }

  /**
   * 处理利用率违规
   */
  private async handleUtilizationViolation(data: any): Promise<void> {
    logger.warn(`⚠️ 处理利用率违规: ${data.accountId}`)

    const account = this.accountManager.getAccount(data.accountId)
    if (account) {
      const signal = await this.createRebalanceSignal(account)
      await this.submitSignal(signal)
    }
  }

  /**
   * 处理账户紧急状态
   */
  private async handleAccountEmergency(data: any): Promise<void> {
    logger.error(`🆘 处理账户紧急状态: ${data.accountId}`)

    const account = this.accountManager.getAccount(data.accountId)
    if (account) {
      const signal = await this.createRebalanceSignal(account)
      signal.priority = 'critical'
      signal.signalType = 'emergency-hedge'
      await this.submitSignal(signal)
    }
  }

  /**
   * 执行初始Delta检查
   */
  private async performInitialDeltaCheck(): Promise<void> {
    logger.info('🔍 执行初始Delta检查')

    const signals = await this.generateDeltaRebalanceSignals()
    for (const signal of signals) {
      await this.submitSignal(signal)
    }
  }

  /**
   * 等待活跃交易完成
   */
  private async waitForActiveTradesCompletion(): Promise<void> {
    const maxWaitTime = 30000 // 30秒
    const startTime = Date.now()

    while (this.activeTrades.size > 0 && Date.now() - startTime < maxWaitTime) {
      logger.info(`⏳ 等待 ${this.activeTrades.size} 个活跃交易完成...`)
      await new Promise(resolve => setTimeout(resolve, 1000))
    }

    if (this.activeTrades.size > 0) {
      logger.warn(`⚠️ 仍有 ${this.activeTrades.size} 个交易未完成，强制停止`)
    }
  }

  /**
   * 生成最终性能报告
   */
  private async generateFinalPerformanceReport(): Promise<void> {
    this.updateMetrics()

    logger.info('📊 DeltaNeutralTradingEngine 最终性能报告', {
      totalSignals: this.metrics.totalSignals,
      processedSignals: this.metrics.processedSignals,
      successfulTrades: this.metrics.successfulTrades,
      failedTrades: this.metrics.failedTrades,
      successRate: this.calculateSuccessRate(),
      avgExecutionTime: this.metrics.avgExecutionTime,
      deltaControlEfficiency: this.metrics.deltaControlEfficiency,
      emergencyTradesExecuted: this.metrics.emergencyTradesExecuted,
    })
  }

  /**
   * 更新指标
   */
  private updateMetrics(): void {
    this.metrics.lastUpdate = new Date()
    this.metrics.periodEnd = new Date()

    // 计算成功率和其他指标
    if (this.metrics.processedSignals > 0) {
      const successRate = this.metrics.successfulTrades / this.metrics.processedSignals
      this.metrics.deltaControlEfficiency = successRate
    }
  }

  /**
   * 记录性能报告
   */
  private logPerformanceReport(): void {
    logger.info('📊 DeltaNeutralTradingEngine 性能报告', {
      signalQueue: this.signalQueue.length,
      activeTrades: this.activeTrades.size,
      successRate: this.calculateSuccessRate(),
      avgExecutionTime: this.metrics.avgExecutionTime,
      throughput: this.calculateThroughput(),
    })
  }

  /**
   * 计算成功率
   */
  private calculateSuccessRate(): number {
    const total = this.metrics.successfulTrades + this.metrics.failedTrades
    return total > 0 ? this.metrics.successfulTrades / total : 1
  }

  /**
   * 计算吞吐量
   */
  private calculateThroughput(): number {
    const runtime = Date.now() - this.metrics.periodStart.getTime()
    return runtime > 0 ? (this.metrics.processedSignals * 1000) / runtime : 0
  }

  /**
   * 清理资源
   */
  private cleanup(): void {
    this.signalQueue = []
    this.activeTrades.clear()

    if (this.metricsReportInterval) {
      clearInterval(this.metricsReportInterval)
      this.metricsReportInterval = undefined
    }
  }
}

export default DeltaNeutralTradingEngine
