/**
 * 市场数据失效回退桥接服务
 * 连接现有 PacificaOrderbookManager 与新的 MarketDataFailoverService
 * 实现 T031 任务：集成 MarketDataFailoverService 与现有 PacificaOrderbookManager
 */
import { PacificaOrderbookManager } from '../modules/orderbook/PacificaOrderbookManager.js'
import { MarketDataFailoverService } from './MarketDataFailoverService.js'
import { MarketDataFeedManager, MarketDataFeed } from '../models/MarketDataFeed.js'
import { SynthPriceSnapshotManager } from '../models/SynthPriceSnapshot.js'
import { MonitoringEventManager } from '../models/MonitoringEvent.js'
import { logger } from '../utils/logger.js'

export interface MarketDataFailoverBridgeConfig {
  enableFailover: boolean // 是否启用失效回退
  failoverTimeoutMs: number // 失效回退超时时间
  maxFailoverAttempts: number // 最大失效回退尝试次数
  synthPriceAccuracy: number // 合成价格精度
  enableHealthCheck: boolean // 启用健康检查
  healthCheckInterval: number // 健康检查间隔
}

export interface MarketDataBridgeStats {
  primaryFeeds: number
  backupFeeds: number
  synthPriceSnapshots: number
  failoverEvents: number
  lastFailoverTime: number
  currentDataSource: 'primary' | 'backup' | 'synthetic'
  dataQuality: 'excellent' | 'good' | 'degraded' | 'poor'
  bridgeMode: boolean
}

export class MarketDataFailoverBridge {
  private isRunning = false
  private healthCheckInterval?: NodeJS.Timeout
  private currentDataSource: 'primary' | 'backup' | 'synthetic' = 'primary'
  private failoverStats = {
    totalFailovers: 0,
    successfulFailovers: 0,
    failedFailovers: 0,
    lastFailoverTime: 0,
    lastError: null as string | null
  }

  constructor(
    private pacificaOrderbookManager: PacificaOrderbookManager,
    private marketDataFailoverService: MarketDataFailoverService,
    private marketDataFeedManager: MarketDataFeedManager,
    private synthPriceSnapshotManager: SynthPriceSnapshotManager,
    private monitoringManager: MonitoringEventManager,
    private config: MarketDataFailoverBridgeConfig = {
      enableFailover: true,
      failoverTimeoutMs: 10000, // 10秒失效回退
      maxFailoverAttempts: 3,
      synthPriceAccuracy: 0.001, // 0.1% 精度
      enableHealthCheck: true,
      healthCheckInterval: 5000 // 5秒健康检查
    }
  ) {}

  /**
   * 启动桥接服务
   */
  async start(): Promise<void> {
    if (this.isRunning) {
      logger.warn('MarketDataFailoverBridge 已在运行')
      return
    }

    logger.info('启动 MarketDataFailoverBridge 服务')
    
    try {
      // 1. 初始化市场数据源
      await this.initializeMarketDataFeeds()
      
      // 2. 启动健康检查
      if (this.config.enableHealthCheck) {
        this.startHealthCheck()
      }
      
      // 3. 设置失效回退监控
      this.setupFailoverMonitoring()
      
      this.isRunning = true
      logger.info('MarketDataFailoverBridge 启动成功')
      
    } catch (error: any) {
      logger.error(`MarketDataFailoverBridge 启动失败: ${error.message}`)
      throw error
    }
  }

  /**
   * 停止桥接服务
   */
  async stop(): Promise<void> {
    if (!this.isRunning) {
      return
    }

    logger.info('停止 MarketDataFailoverBridge 服务')
    
    if (this.healthCheckInterval) {
      clearInterval(this.healthCheckInterval)
      this.healthCheckInterval = undefined
    }
    
    this.isRunning = false
    logger.info('MarketDataFailoverBridge 已停止')
  }

  /**
   * 获取桥接状态
   */
  getStatus(): {
    isRunning: boolean
    config: MarketDataFailoverBridgeConfig
    stats: MarketDataBridgeStats
  } {
    return {
      isRunning: this.isRunning,
      config: { ...this.config },
      stats: this.getBridgeStats()
    }
  }

  /**
   * 初始化市场数据源
   */
  private async initializeMarketDataFeeds(): Promise<void> {
    logger.info('初始化市场数据源')

    try {
      // 1. 创建主要数据源（Pacifica WebSocket）
      const primaryFeed: MarketDataFeed = {
        feedId: 'pacifica-ws-primary',
        exchange: 'pacifica',
        symbol: 'BTC',
        type: 'websocket',
        wsEndpoint: process.env.PACIFICA_WS_URL || 'wss://ws.pacifica.fi/ws',
        httpEndpoint: process.env.PACIFICA_HTTP_URL || 'https://api.pacifica.fi/api/v1',
        status: 'active',
        priority: 1,
        latency: 50, // 预估延迟
        reliability: 0.95, // 可靠性
        lastUpdate: new Date(),
        createdAt: new Date(),
        updatedAt: new Date()
      }

      this.marketDataFeedManager.addFeed(primaryFeed)

      // 2. 创建备用数据源（HTTP API）
      const backupFeed: MarketDataFeed = {
        feedId: 'pacifica-http-backup',
        exchange: 'pacifica',
        symbol: 'BTC',
        type: 'http',
        wsEndpoint: '',
        httpEndpoint: process.env.PACIFICA_HTTP_URL || 'https://api.pacifica.fi/api/v1',
        status: 'standby',
        priority: 2,
        latency: 200, // HTTP 延迟更高
        reliability: 0.90,
        lastUpdate: new Date(),
        createdAt: new Date(),
        updatedAt: new Date()
      }

      this.marketDataFeedManager.addFeed(backupFeed)

      // 3. 初始化合成价格快照
      await this.initializeSynthPriceSnapshots()

      logger.info('市场数据源初始化完成')
    } catch (error: any) {
      logger.error(`市场数据源初始化失败: ${error.message}`)
      throw error
    }
  }

  /**
   * 初始化合成价格快照
   */
  private async initializeSynthPriceSnapshots(): Promise<void> {
    logger.info('初始化合成价格快照')

    const symbols = ['BTC', 'ETH', 'SOL']
    
    for (const symbol of symbols) {
      const synthSnapshot = {
        snapshotId: `synth-${symbol.toLowerCase()}-${Date.now()}`,
        symbol,
        source: 'synthetic',
        price: this.generateSyntheticPrice(symbol),
        confidence: 0.8, // 合成价格置信度
        factors: {
          historicalAverage: this.getHistoricalAverage(symbol),
          volatility: this.getVolatility(symbol),
          marketTrend: this.getMarketTrend(symbol)
        },
        createdAt: new Date(),
        updatedAt: new Date()
      }

      this.synthPriceSnapshotManager.addSnapshot(synthSnapshot)
      logger.debug(`创建合成价格快照: ${symbol}`)
    }

    logger.info('合成价格快照初始化完成')
  }

  /**
   * 启动健康检查
   */
  private startHealthCheck(): void {
    logger.info(`启动市场数据健康检查，间隔: ${this.config.healthCheckInterval}ms`)
    
    this.healthCheckInterval = setInterval(async () => {
      try {
        await this.performHealthCheck()
      } catch (error: any) {
        logger.error(`健康检查失败: ${error.message}`)
      }
    }, this.config.healthCheckInterval)

    // 立即执行一次健康检查
    this.performHealthCheck().catch(error => {
      logger.error(`初始健康检查失败: ${error.message}`)
    })
  }

  /**
   * 执行健康检查
   */
  async performHealthCheck(): Promise<void> {
    if (!this.isRunning) {
      return
    }

    logger.debug('执行市场数据健康检查')

    try {
      // 1. 检查主要数据源状态
      const primaryFeedStatus = this.pacificaOrderbookManager.getStatus()
      
      if (primaryFeedStatus.status !== 'running') {
        logger.warn('主要数据源状态异常，检查是否需要失效回退')
        await this.checkFailoverNeeded('primary_feed_unhealthy')
      }

      // 2. 检查数据质量
      const dataQuality = this.assessDataQuality()
      
      if (dataQuality === 'poor') {
        logger.warn('数据质量较差，触发失效回退')
        await this.triggerFailover('data_quality_poor')
      }

      // 3. 更新监控事件
      this.monitoringManager.addEvent({
        eventId: `health-check-${Date.now()}`,
        type: 'market-data-health-check',
        payload: {
          primaryFeedStatus: primaryFeedStatus.status,
          dataQuality,
          currentDataSource: this.currentDataSource,
          failoverStats: this.failoverStats
        },
        severity: dataQuality === 'poor' ? 'WARN' : 'INFO',
        createdAt: new Date()
      })

    } catch (error: any) {
      logger.error(`健康检查执行失败: ${error.message}`)
      throw error
    }
  }

  /**
   * 检查是否需要失效回退
   */
  private async checkFailoverNeeded(reason: string): Promise<void> {
    if (!this.config.enableFailover) {
      logger.info('失效回退已禁用')
      return
    }

    try {
      const failoverResult = await this.marketDataFailoverService.triggerFailover({
        triggerReason: reason,
        timeoutMs: this.config.failoverTimeoutMs,
        maxAttempts: this.config.maxFailoverAttempts
      })

      if (failoverResult.success) {
        this.currentDataSource = failoverResult.newDataSource as any
        this.failoverStats.successfulFailovers++
        this.failoverStats.lastFailoverTime = Date.now()
        logger.info(`失效回退成功，切换到: ${this.currentDataSource}`)
      } else {
        this.failoverStats.failedFailovers++
        this.failoverStats.lastError = failoverResult.error
        logger.error(`失效回退失败: ${failoverResult.error}`)
      }

      this.failoverStats.totalFailovers++
    } catch (error: any) {
      this.failoverStats.failedFailovers++
      this.failoverStats.lastError = error.message
      logger.error(`检查失效回退需求失败: ${error.message}`)
    }
  }

  /**
   * 触发失效回退
   */
  async triggerFailover(reason: string): Promise<{
    success: boolean
    message: string
    newDataSource?: string
  }> {
    try {
      const failoverResult = await this.marketDataFailoverService.triggerFailover({
        triggerReason: reason,
        timeoutMs: this.config.failoverTimeoutMs,
        maxAttempts: this.config.maxFailoverAttempts
      })

      if (failoverResult.success) {
        this.currentDataSource = failoverResult.newDataSource as any
        this.failoverStats.successfulFailovers++
        this.failoverStats.lastFailoverTime = Date.now()
        
        return {
          success: true,
          message: `失效回退成功，切换到: ${this.currentDataSource}`,
          newDataSource: this.currentDataSource
        }
      } else {
        this.failoverStats.failedFailovers++
        this.failoverStats.lastError = failoverResult.error
        
        return {
          success: false,
          message: `失效回退失败: ${failoverResult.error}`
        }
      }
    } catch (error: any) {
      this.failoverStats.failedFailovers++
      this.failoverStats.lastError = error.message
      
      return {
        success: false,
        message: `失效回退异常: ${error.message}`
      }
    }
  }

  /**
   * 评估数据质量
   */
  private assessDataQuality(): 'excellent' | 'good' | 'degraded' | 'poor' {
    try {
      // 获取订单簿统计数据
      const orderbookStats = this.pacificaOrderbookManager.getOrderbookStats()
      
      if (orderbookStats.length === 0) {
        return 'poor'
      }

      // 检查数据新鲜度
      const now = Date.now()
      const maxAge = 30000 // 30秒
      const staleData = orderbookStats.some(stat => (now - stat.lastUpdate) > maxAge)
      
      if (staleData) {
        return 'degraded'
      }

      // 检查价差合理性
      const highSpread = orderbookStats.some(stat => stat.spreadPercent > 0.01) // 1% 价差
      
      if (highSpread) {
        return 'degraded'
      }

      // 检查更新频率
      const lowFrequency = orderbookStats.some(stat => stat.updateFrequency < 0.5) // 每秒更新少于0.5次
      
      if (lowFrequency) {
        return 'good'
      }

      return 'excellent'
    } catch (error: any) {
      logger.error(`评估数据质量失败: ${error.message}`)
      return 'poor'
    }
  }

  /**
   * 设置失效回退监控
   */
  private setupFailoverMonitoring(): void {
    logger.info('设置失效回退监控')

    // 监听订单簿管理器的错误事件
    this.pacificaOrderbookManager.on('error', async (error) => {
      logger.warn('订单簿管理器错误，检查失效回退', { error: error.message })
      await this.checkFailoverNeeded('orderbook_manager_error')
    })

    // 创建失效回退启动事件
    this.monitoringManager.addEvent({
      eventId: `failover-bridge-start-${Date.now()}`,
      type: 'failover-bridge-start',
      payload: {
        config: this.config,
        primaryFeeds: 1,
        backupFeeds: 1,
        synthSnapshots: 3
      },
      severity: 'INFO',
      createdAt: new Date()
    })

    logger.info('失效回退监控设置完成')
  }

  /**
   * 生成合成价格
   */
  private generateSyntheticPrice(symbol: string): number {
    // 基于历史平均价格和随机波动生成合成价格
    const basePrice = this.getHistoricalAverage(symbol)
    const volatility = this.getVolatility(symbol)
    const randomFactor = (Math.random() - 0.5) * 2 * volatility
    
    return basePrice * (1 + randomFactor)
  }

  /**
   * 获取历史平均价格
   */
  private getHistoricalAverage(symbol: string): number {
    const averages: Record<string, number> = {
      'BTC': 108000,
      'ETH': 3200,
      'SOL': 180
    }
    return averages[symbol] || 1000
  }

  /**
   * 获取波动率
   */
  private getVolatility(symbol: string): number {
    const volatilities: Record<string, number> = {
      'BTC': 0.02,
      'ETH': 0.03,
      'SOL': 0.04
    }
    return volatilities[symbol] || 0.02
  }

  /**
   * 获取市场趋势
   */
  private getMarketTrend(symbol: string): 'bullish' | 'bearish' | 'neutral' {
    // 简化实现，返回随机趋势
    const trends = ['bullish', 'bearish', 'neutral'] as const
    return trends[Math.floor(Math.random() * trends.length)]
  }

  /**
   * 获取桥接统计信息
   */
  getBridgeStats(): MarketDataBridgeStats {
    return {
      primaryFeeds: 1,
      backupFeeds: 1,
      synthPriceSnapshots: this.synthPriceSnapshotManager.getAllSnapshots().length,
      failoverEvents: this.failoverStats.totalFailovers,
      lastFailoverTime: this.failoverStats.lastFailoverTime,
      currentDataSource: this.currentDataSource,
      dataQuality: this.assessDataQuality(),
      bridgeMode: true
    }
  }

  /**
   * 更新配置
   */
  updateConfig(newConfig: Partial<MarketDataFailoverBridgeConfig>): void {
    this.config = { ...this.config, ...newConfig }
    
    // 如果健康检查间隔改变，重启健康检查
    if (newConfig.healthCheckInterval && this.isRunning) {
      this.stop().then(() => {
        this.start()
      })
    }
    
    logger.info('市场数据失效回退桥接配置已更新', newConfig)
  }

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

  /**
   * 获取新的市场数据失效回退服务
   */
  getMarketDataFailoverService(): MarketDataFailoverService {
    return this.marketDataFailoverService
  }
}
