import { TradingService, ServiceStatus } from './types.js'
import { CacheManager } from './cache/CacheManager.js'
import { AccountManager } from './account/AccountManager.js'
import { RiskManager } from './risk/RiskManager.js'
import { StopLossService } from './stopLoss/StopLossService.js'
import { HedgingCoordinator } from './hedging/HedgingCoordinator.js'
import { TradingEngineV2 } from './trading/TradingEngineV2.js'
import { DashboardService } from './dashboard/DashboardService.js'
import { OrderCleanupService } from './cleanup/OrderCleanupService.js'
import { PacificaOrderbookManager } from './orderbook/PacificaOrderbookManager.js'
import { SamePlatformHedgingManager } from '../core/hedging/SamePlatformHedgingManager.js'
import { PacificaProxyClient } from '../exchanges/pacifica/PacificaProxyClient.js'
import { globalPriceManager } from './price/PriceManager.js'
import { AdvancedHedgingManager } from './hedging/AdvancedHedgingManager.js'
import { AccountManagerBridge } from '../services/AccountManagerBridge.js'
import { HedgingCoordinatorBridge } from '../services/HedgingCoordinatorBridge.js'
import { MarketDataFailoverBridge } from '../services/MarketDataFailoverBridge.js'
import { StrategyModuleBridge } from '../services/StrategyModuleBridge.js'
import { StructuredLoggingService } from '../services/StructuredLoggingService.js'
import { ControlPlaneService } from '../services/ControlPlaneService.js'
import { ExchangeAccountManager } from '../models/ExchangeAccount.js'
import { RiskEnvelopeManager } from '../models/RiskEnvelope.js'
import { MarketDataFeedManager } from '../models/MarketDataFeed.js'
import { StrategyModuleManager } from '../models/StrategyModule.js'
import { MonitoringEventManager } from '../models/MonitoringEvent.js'
import { HedgeExecutionManager } from '../models/HedgeExecution.js'
import { SynthPriceSnapshotManager } from '../models/SynthPriceSnapshot.js'
import { logger } from '../utils/logger.js'

/**
 * 系统协调器 - 统一管理所有模块的生命周期和依赖关系
 */
export class SystemOrchestrator {
  private services: Map<string, TradingService> = new Map()
  private isRunning = false
  private initializationOrder: string[] = [
    'CacheManager',
    'PacificaOrderbookManager',
    'AccountManager',
    'RiskManager',
    'StopLossService',
    'OrderCleanupService',
    'HedgingCoordinator',
    'AdvancedHedgingManager',
    'TradingEngine',
    'DashboardService',
  ]

  // 服务实例
  private cacheManager!: CacheManager
  private pacificaOrderbookManager!: PacificaOrderbookManager
  private accountManager!: AccountManager
  private riskManager!: RiskManager
  private stopLossService!: StopLossService
  private orderCleanupService!: OrderCleanupService
  private hedgingCoordinator!: HedgingCoordinator
  private advancedHedgingManager!: AdvancedHedgingManager
  private tradingEngine!: TradingEngineV2
  private dashboardService!: DashboardService

  // 新架构服务实例
  private exchangeAccountManager!: ExchangeAccountManager
  private riskEnvelopeManager!: RiskEnvelopeManager
  private marketDataFeedManager!: MarketDataFeedManager
  private strategyModuleManager!: StrategyModuleManager
  private monitoringEventManager!: MonitoringEventManager
  private hedgeExecutionManager!: HedgeExecutionManager
  private controlPlaneService!: ControlPlaneService
  private accountManagerBridge!: AccountManagerBridge
  private hedgingCoordinatorBridge!: HedgingCoordinatorBridge
  private marketDataFailoverBridge!: MarketDataFailoverBridge
  private strategyModuleBridge!: StrategyModuleBridge
  private structuredLoggingService!: StructuredLoggingService

  constructor() {
    logger.info('SystemOrchestrator 创建')
  }

  /**
   * 初始化所有服务
   */
  async initialize(config?: {
    accounts?: any[]
    enableTrading?: boolean
    enableDashboard?: boolean
    displayConfig?: any
    enableControlPlane?: boolean
  }): Promise<void> {
    logger.info('开始初始化系统服务...')

    try {
      // 创建服务实例
      await this.createServices()

      // 配置账户和客户端
      if (config?.accounts) {
        await this.setupAccountsAndClients(config.accounts)
      }

      // 按顺序初始化服务
      for (const serviceName of this.initializationOrder) {
        const service = this.services.get(serviceName)
        if (service) {
          logger.info(`初始化服务: ${serviceName}`)
          await service.initialize()
        }
      }

      // 设置服务间的依赖关系
      await this.setupServiceDependencies()

      // 配置显示选项
      if (config?.displayConfig) {
        this.dashboardService.setDisplayConfig(config.displayConfig)
      }

      // 初始化控制平面模式
      if (config?.enableControlPlane) {
        await this.initializeControlPlane()
      }

      logger.info('系统服务初始化完成')
    } catch (error: any) {
      logger.error('系统初始化失败', { error: error.message })
      throw error
    }
  }

  /**
   * 启动所有服务
   */
  async start(): Promise<void> {
    if (this.isRunning) {
      logger.warn('系统已在运行中')
      return
    }

    logger.info('启动系统服务...')

    // 全局价格管理器已自动启动
    logger.info('✅ 全局价格管理器已初始化', globalPriceManager.getStatus())

    try {
      // 按顺序启动服务
      for (const serviceName of this.initializationOrder) {
        const service = this.services.get(serviceName)
        if (service) {
          logger.info(`启动服务: ${serviceName}`)
          await service.start()
        }
      }

      this.isRunning = true
      logger.info('✅ 系统启动成功')

      // 显示启动消息
      console.log('🚀 Pacifica 交易系统已启动')
      console.log('📊 仪表板正在运行...')
      console.log('🔄 交易引擎已激活')
      console.log('🛡️ 风险管理系统运行中')
      console.log()
    } catch (error: any) {
      logger.error('系统启动失败', { error: error.message })
      throw error
    }
  }

  /**
   * 停止所有服务
   */
  async stop(): Promise<void> {
    if (!this.isRunning) {
      logger.warn('系统未在运行')
      return
    }

    logger.info('停止系统服务...')

    try {
      // 按逆序停止服务
      const stopOrder = [...this.initializationOrder].reverse()

      for (const serviceName of stopOrder) {
        const service = this.services.get(serviceName)
        if (service) {
          logger.info(`停止服务: ${serviceName}`)
          await service.stop()
        }
      }

      this.isRunning = false
      logger.info('系统已安全停止')
    } catch (error: any) {
      logger.error('系统停止时出错', { error: error.message })
    }
  }

  /**
   * 优雅关闭
   */
  async gracefulShutdown(): Promise<void> {
    logger.info('开始优雅关闭系统...')

    try {
      // 首先停止交易引擎
      if (this.tradingEngine) {
        await this.tradingEngine.stop()
      }

      // 停止对冲协调器
      if (this.hedgingCoordinator) {
        await this.hedgingCoordinator.emergencyStopAllHedging()
      }

      // 停止其他服务
      await this.stop()

      logger.info('✅ 系统已优雅关闭')
    } catch (error: any) {
      logger.error('优雅关闭时出错', { error: error.message })
    }
  }

  /**
   * 创建所有服务实例
   */
  private async createServices(): Promise<void> {
    // 创建基础服务
    this.cacheManager = new CacheManager()

    // 创建Pacifica WebSocket订单簿管理器（优先启动，为其他服务提供实时数据）
    this.pacificaOrderbookManager = new PacificaOrderbookManager({
      wsUrl: process.env.PACIFICA_WS_URL || 'wss://ws.pacifica.fi/ws',
      symbols: ['BTC', 'SOL', 'ETH'],
      aggLevel: parseInt(process.env.ORDERBOOK_AGG_LEVEL || '1'),
      cacheExpiryMs: parseInt(process.env.ORDERBOOK_CACHE_EXPIRY || '60000'),
      minDepthLevels: parseInt(process.env.MIN_DEPTH_LEVELS || '5')
    })

    this.accountManager = new AccountManager(this.cacheManager)
    this.riskManager = new RiskManager(this.accountManager)
    this.stopLossService = new StopLossService(this.accountManager, this.cacheManager)

    // 创建订单清理服务（5分钟清理一次，10分钟的订单被认为是历史订单，最多保留10个订单）
    const cleanupInterval = parseInt(process.env.ORDER_CLEANUP_INTERVAL || '300000') // 5分钟
    const maxOrderAge = parseInt(process.env.MAX_ORDER_AGE || '600000') // 10分钟
    const maxOrderCount = parseInt(process.env.MAX_ORDER_COUNT || '10') // 最多10个订单
    this.orderCleanupService = new OrderCleanupService(this.accountManager, cleanupInterval, maxOrderAge, maxOrderCount)

    this.hedgingCoordinator = new HedgingCoordinator(this.accountManager, this.riskManager)

    // 创建高级对冲管理器（默认管理两个账户进行对冲）
    const hedgingAccounts = [
      process.env.PACIFICA_ACCOUNT_1 || 'account-1',
      process.env.PACIFICA_ACCOUNT_2 || 'account-2',
    ]
    this.advancedHedgingManager = new AdvancedHedgingManager(hedgingAccounts, 'BTC')

    // 创建交易引擎（需要对冲管理器和orderbook管理器）
    this.tradingEngine = new TradingEngineV2(
      this.accountManager,
      this.riskManager,
      this.stopLossService,
      null, // 将在 setupServiceDependencies 中设置
      this.pacificaOrderbookManager, // 传递orderbook管理器
    )

    // 创建仪表板服务
    this.dashboardService = new DashboardService(
      this.accountManager,
      this.riskManager,
      this.stopLossService,
      this.hedgingCoordinator,
      this.tradingEngine,
      this.cacheManager,
    )

    // 注册服务
    this.services.set('CacheManager', this.cacheManager)
    this.services.set('PacificaOrderbookManager', this.pacificaOrderbookManager)
    this.services.set('AccountManager', this.accountManager)
    this.services.set('RiskManager', this.riskManager)
    this.services.set('StopLossService', this.stopLossService)
    this.services.set('OrderCleanupService', this.orderCleanupService)
    this.services.set('HedgingCoordinator', this.hedgingCoordinator)
    this.services.set('AdvancedHedgingManager', this.advancedHedgingManager)
    this.services.set('TradingEngine', this.tradingEngine)
    this.services.set('DashboardService', this.dashboardService)

    logger.info('服务实例创建完成')
  }

  /**
   * 设置服务间的依赖关系
   */
  private async setupServiceDependencies(): Promise<void> {
    // 设置交易引擎的对冲管理器
    const hedgingManager = this.hedgingCoordinator.getHedgingManager()
    if (hedgingManager && this.tradingEngine) {
      // 需要修改 TradingEngine 来允许设置对冲管理器
      // 这里暂时使用类型断言
      ;(this.tradingEngine as any).hedgeManager = hedgingManager
    }

    // 设置高级对冲管理器的账户管理器
    if (this.advancedHedgingManager && this.accountManager) {
      this.advancedHedgingManager.setAccountManager(this.accountManager)
      logger.info('✅ AdvancedHedgingManager已连接AccountManager')
    }

    logger.info('服务依赖关系设置完成')
  }

  /**
   * 设置账户和客户端
   */
  private async setupAccountsAndClients(accounts: any[]): Promise<void> {
    logger.info(`设置 ${accounts.length} 个账户...`)

    this.accountManager.setAccounts(accounts)

    // 创建客户端
    for (let i = 0; i < accounts.length; i++) {
      const account = accounts[i]
      const clientId = `pacifica-${i + 1}`

      try {
        const client = new PacificaProxyClient({
          privateKey: account.privateKey || process.env[`PACIFICA_PRIVATE_KEY_${i + 1}`] || '',
          account: account.account || process.env[`PACIFICA_ACCOUNT_${i + 1}`] || '',
        })

        // 禁用WebSocket，使用HTTP+代理模式获取数据
        client.setWebSocketEnabled(false)
        // await client.initializeWebSocket() // 已禁用WebSocket

        this.accountManager.addClient(clientId, client)
        logger.info(`客户端 ${clientId} 创建成功 (HTTP+代理模式)`)
      } catch (error: any) {
        logger.error(`创建客户端 ${clientId} 失败`, { error: error.message })
      }
    }

    logger.info('账户和客户端设置完成')
  }

  /**
   * 获取代理配置
   */
  private getProxyConfig(accountIndex: number): any {
    const proxyEnabled = process.env.PROXY_ENABLED === 'true'
    if (!proxyEnabled) return null

    return {
      protocol: process.env.PROXY_PROTOCOL || 'http',
      host: process.env.PROXY_HOST || '',
      port: parseInt(process.env.PROXY_PORT || '8080'),
      auth: {
        username: process.env.PROXY_USERNAME || '',
        password: process.env.PROXY_PASSWORD || '',
      },
    }
  }

  /**
   * 获取系统状态
   */
  getSystemStatus(): { [serviceName: string]: ServiceStatus } {
    const status: { [serviceName: string]: ServiceStatus } = {}

    for (const [serviceName, service] of this.services) {
      status[serviceName] = service.getStatus()
    }

    return status
  }

  /**
   * 获取特定服务
   */
  getService<T extends TradingService>(serviceName: string): T | undefined {
    return this.services.get(serviceName) as T
  }

  /**
   * 检查系统健康状态
   */
  isHealthy(): boolean {
    if (!this.isRunning) return false

    for (const [serviceName, service] of this.services) {
      const status = service.getStatus()
      if (status.status !== 'running') {
        logger.warn(`服务 ${serviceName} 状态异常: ${status.status}`)
        return false
      }
    }

    return true
  }

  /**
   * 重启特定服务
   */
  async restartService(serviceName: string): Promise<boolean> {
    const service = this.services.get(serviceName)
    if (!service) {
      logger.error(`服务 ${serviceName} 不存在`)
      return false
    }

    try {
      logger.info(`重启服务: ${serviceName}`)
      await service.stop()
      await service.start()
      logger.info(`服务 ${serviceName} 重启成功`)
      return true
    } catch (error: any) {
      logger.error(`服务 ${serviceName} 重启失败`, { error: error.message })
      return false
    }
  }

  /**
   * 强制刷新仪表板
   */
  async refreshDashboard(): Promise<void> {
    if (this.dashboardService) {
      await this.dashboardService.forceRefresh()
    }
  }

  /**
   * 初始化控制平面模式
   */
  private async initializeControlPlane(): Promise<void> {
    logger.info('初始化控制平面模式...')

    try {
      // 1. 创建新架构的管理器实例
      this.exchangeAccountManager = new ExchangeAccountManager()
      this.riskEnvelopeManager = new RiskEnvelopeManager()
      this.marketDataFeedManager = new MarketDataFeedManager()
      this.strategyModuleManager = new StrategyModuleManager()
      this.monitoringEventManager = new MonitoringEventManager()
      this.hedgeExecutionManager = new HedgeExecutionManager()

      // 2. 创建结构化日志服务
      this.structuredLoggingService = new StructuredLoggingService(this.monitoringEventManager)

      // 3. 创建控制平面服务
      this.controlPlaneService = new ControlPlaneService(
        this.accountManager,
        this.exchangeAccountManager,
        this.riskEnvelopeManager,
        this.marketDataFeedManager,
        this.strategyModuleManager,
        this.monitoringEventManager
      )

      // 4. 初始化控制平面服务
      await this.controlPlaneService.initialize()
      await this.controlPlaneService.start()

      // 5. 创建账户管理器桥接器
      this.accountManagerBridge = new AccountManagerBridge(
        this.accountManager,
        this.controlPlaneService.getAccountSyncService(),
        this.exchangeAccountManager,
        this.monitoringEventManager,
        this.riskEnvelopeManager
      )

      // 6. 创建对冲协调器桥接器
      this.hedgingCoordinatorBridge = new HedgingCoordinatorBridge(
        this.hedgingCoordinator,
        this.controlPlaneService.getHedgeExecutionService(),
        this.hedgeExecutionManager,
        this.exchangeAccountManager,
        this.riskEnvelopeManager,
        this.monitoringEventManager,
        this.accountManager
      )

      // 7. 创建市场数据失效回退桥接器
      this.marketDataFailoverBridge = new MarketDataFailoverBridge(
        this.pacificaOrderbookManager,
        this.controlPlaneService.getMarketDataFailoverService(),
        this.marketDataFeedManager,
        new SynthPriceSnapshotManager(),
        this.monitoringEventManager
      )

      // 8. 创建策略模块桥接器
      this.strategyModuleBridge = new StrategyModuleBridge(
        this.tradingEngine,
        this.controlPlaneService.getStrategyModuleService(),
        this.strategyModuleManager,
        this.exchangeAccountManager,
        this.monitoringEventManager
      )

      // 9. 启动桥接器
      await this.accountManagerBridge.start()
      await this.hedgingCoordinatorBridge.start()
      await this.marketDataFailoverBridge.start()
      await this.strategyModuleBridge.start()

      logger.info('控制平面模式初始化完成')
    } catch (error: any) {
      logger.error(`控制平面模式初始化失败: ${error.message}`)
      throw error
    }
  }

  /**
   * 获取控制平面服务
   */
  getControlPlaneService(): ControlPlaneService | undefined {
    return this.controlPlaneService
  }

  /**
   * 获取账户管理器桥接器
   */
  getAccountManagerBridge(): AccountManagerBridge | undefined {
    return this.accountManagerBridge
  }

  /**
   * 获取对冲协调器桥接器
   */
  getHedgingCoordinatorBridge(): HedgingCoordinatorBridge | undefined {
    return this.hedgingCoordinatorBridge
  }

  /**
   * 获取市场数据失效回退桥接器
   */
  getMarketDataFailoverBridge(): MarketDataFailoverBridge | undefined {
    return this.marketDataFailoverBridge
  }

  /**
   * 获取策略模块桥接器
   */
  getStrategyModuleBridge(): StrategyModuleBridge | undefined {
    return this.strategyModuleBridge
  }

  /**
   * 获取结构化日志服务
   */
  getStructuredLoggingService(): StructuredLoggingService | undefined {
    return this.structuredLoggingService
  }

  /**
   * 手动触发账户同步
   */
  async triggerAccountSync(): Promise<{
    success: boolean
    message: string
    stats?: any
  }> {
    if (!this.accountManagerBridge) {
      return {
        success: false,
        message: '账户管理器桥接器未初始化'
      }
    }

    try {
      const result = await this.accountManagerBridge.triggerManualSync()
      return {
        success: result.success,
        message: result.message,
        stats: result.syncStats
      }
    } catch (error: any) {
      return {
        success: false,
        message: `账户同步失败: ${error.message}`
      }
    }
  }

  /**
   * 获取桥接统计信息
   */
  getBridgeStats(): any {
    const accountStats = this.accountManagerBridge?.getBridgeStats()
    const hedgeStats = this.hedgingCoordinatorBridge?.getBridgeStats()
    const marketDataStats = this.marketDataFailoverBridge?.getBridgeStats()
    const strategyStats = this.strategyModuleBridge?.getBridgeStats()
    const loggingStats = this.structuredLoggingService?.getLogStats()
    
    return {
      accountBridge: accountStats,
      hedgeBridge: hedgeStats,
      marketDataBridge: marketDataStats,
      strategyBridge: strategyStats,
      loggingService: loggingStats
    }
  }

  /**
   * 手动触发对冲执行
   */
  async triggerManualHedge(hedgeRequest: any): Promise<{
    success: boolean
    message: string
    executionId?: string
  }> {
    if (!this.hedgingCoordinatorBridge) {
      return {
        success: false,
        message: '对冲协调器桥接器未初始化'
      }
    }

    try {
      const result = await this.hedgingCoordinatorBridge.triggerManualHedge(hedgeRequest)
      return result
    } catch (error: any) {
      return {
        success: false,
        message: `手动对冲失败: ${error.message}`
      }
    }
  }

  /**
   * 手动触发市场数据失效回退
   */
  async triggerMarketDataFailover(reason: string): Promise<{
    success: boolean
    message: string
    newDataSource?: string
  }> {
    if (!this.marketDataFailoverBridge) {
      return {
        success: false,
        message: '市场数据失效回退桥接器未初始化'
      }
    }

    try {
      const result = await this.marketDataFailoverBridge.triggerFailover(reason)
      return result
    } catch (error: any) {
      return {
        success: false,
        message: `市场数据失效回退失败: ${error.message}`
      }
    }
  }

  /**
   * 执行策略模块
   */
  async executeStrategyModule(moduleId: string, context?: any): Promise<{
    success: boolean
    result?: any
    error?: string
  }> {
    if (!this.strategyModuleBridge) {
      return {
        success: false,
        error: '策略模块桥接器未初始化'
      }
    }

    try {
      const result = await this.strategyModuleBridge.executeModule(moduleId, context)
      return result
    } catch (error: any) {
      return {
        success: false,
        error: `策略模块执行失败: ${error.message}`
      }
    }
  }

  /**
   * 启动策略模块
   */
  async startStrategyModule(moduleId: string): Promise<{
    success: boolean
    message: string
  }> {
    if (!this.strategyModuleBridge) {
      return {
        success: false,
        message: '策略模块桥接器未初始化'
      }
    }

    return await this.strategyModuleBridge.startModule(moduleId)
  }

  /**
   * 停止策略模块
   */
  async stopStrategyModule(moduleId: string): Promise<{
    success: boolean
    message: string
  }> {
    if (!this.strategyModuleBridge) {
      return {
        success: false,
        message: '策略模块桥接器未初始化'
      }
    }

    return await this.strategyModuleBridge.stopModule(moduleId)
  }

  /**
   * 获取统一系统状态
   */
  getUnifiedSystemStatus(): {
    legacy: Record<string, ServiceStatus>
    controlPlane?: ServiceStatus
    bridge?: any
  } {
    const legacyStatus: Record<string, ServiceStatus> = {}
    
    for (const [serviceName, service] of this.services) {
      legacyStatus[serviceName] = service.getStatus()
    }

    const result: any = {
      legacy: legacyStatus
    }

    if (this.controlPlaneService) {
      result.controlPlane = this.controlPlaneService.getStatus()
    }

    if (this.accountManagerBridge) {
      result.accountBridge = this.accountManagerBridge.getStatus()
    }

    if (this.hedgingCoordinatorBridge) {
      result.hedgeBridge = this.hedgingCoordinatorBridge.getStatus()
    }

    if (this.marketDataFailoverBridge) {
      result.marketDataBridge = this.marketDataFailoverBridge.getStatus()
    }

    if (this.strategyModuleBridge) {
      result.strategyBridge = this.strategyModuleBridge.getStatus()
    }

    return result
  }

  /**
   * 获取是否正在运行
   */
  getIsRunning(): boolean {
    return this.isRunning
  }

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

  /**
   * 设置紧急停止
   */
  async emergencyStop(): Promise<void> {
    logger.warn('🚨 紧急停止系统')

    try {
      // 立即停止交易
      if (this.tradingEngine) {
        await this.tradingEngine.stop()
      }

      // 停止所有对冲
      if (this.hedgingCoordinator) {
        await this.hedgingCoordinator.emergencyStopAllHedging()
      }

      // 停止系统
      await this.stop()

      console.log('🛑 系统已紧急停止')
    } catch (error: any) {
      logger.error('紧急停止时出错', { error: error.message })
    }
  }
}
