/**
 * 控制平面主服务
 * 整合所有核心服务，提供统一的控制平面接口
 */
import { AccountSyncService } from './AccountSyncService.js'
import { HedgeExecutionService } from './HedgeExecutionService.js'
import { MarketDataFailoverService } from './MarketDataFailoverService.js'
import { StrategyModuleService } from './StrategyModuleService.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 { AccountManager } from '../modules/account/AccountManager.js'
import { TradingService, ServiceStatus } from '../modules/types.js'
import { logger } from '../utils/logger.js'

export class ControlPlaneService implements TradingService {
  private accountSyncService: AccountSyncService
  private hedgeExecutionService: HedgeExecutionService
  private marketDataFailoverService: MarketDataFailoverService
  private strategyModuleService: StrategyModuleService
  
  private status: 'stopped' | 'initializing' | 'initialized' | 'starting' | 'running' | 'stopping' | 'error' = 'stopped'
  private lastStatusChange = Date.now()
  private healthCheckInterval?: NodeJS.Timeout

  constructor(
    private accountManager: AccountManager,
    private exchangeAccountManager: ExchangeAccountManager,
    private riskManager: RiskEnvelopeManager,
    private marketDataFeedManager: MarketDataFeedManager,
    private strategyModuleManager: StrategyModuleManager,
    private monitoringManager: MonitoringEventManager
  ) {
    // 初始化子服务
    this.accountSyncService = new AccountSyncService(
      exchangeAccountManager,
      monitoringManager,
      riskManager,
      accountManager
    )

    this.hedgeExecutionService = new HedgeExecutionService(
      new (require('../models/HedgeExecution.js').HedgeExecutionManager)(),
      accountManager,
      riskManager,
      this.createMockOrderExecutor()
    )

    this.marketDataFailoverService = new MarketDataFailoverService(
      marketDataFeedManager,
      new (require('../models/SynthPriceSnapshot.js').SynthPriceSnapshotManager)(),
      monitoringManager
    )

    this.strategyModuleService = new StrategyModuleService(
      strategyModuleManager,
      new (require('../models/AccountAllocation.js').AccountAllocationManager)(),
      new (require('../models/OrderIntent.js').OrderIntentManager)(),
      this.createMockOrderExecutor()
    )
  }

  async initialize(): Promise<void> {
    this.updateStatus('initializing')
    logger.info('控制平面服务初始化开始')

    try {
      // 初始化子服务
      await this.initializeSubServices()
      
      // 注册价格数据提供者
      this.registerPriceProviders()
      
      // 注册交易所适配器
      this.registerExchangeAdapters()

      this.updateStatus('initialized')
      logger.info('控制平面服务初始化完成')
    } catch (error: any) {
      this.updateStatus('error')
      logger.error(`控制平面服务初始化失败: ${error.message}`)
      throw error
    }
  }

  async start(): Promise<void> {
    this.updateStatus('starting')
    logger.info('控制平面服务启动开始')

    try {
      // 启动健康检查
      this.startHealthCheck()
      
      // 启动市场数据监控
      this.startMarketDataMonitoring()

      this.updateStatus('running' as any)
      logger.info('控制平面服务启动完成')
    } catch (error: any) {
      this.updateStatus('error')
      logger.error(`控制平面服务启动失败: ${error.message}`)
      throw error
    }
  }

  async stop(): Promise<void> {
    this.updateStatus('stopping')
    logger.info('控制平面服务停止开始')

    try {
      // 停止健康检查
      if (this.healthCheckInterval) {
        clearInterval(this.healthCheckInterval)
        this.healthCheckInterval = undefined
      }

      this.updateStatus('stopped')
      logger.info('控制平面服务停止完成')
    } catch (error: any) {
      this.updateStatus('error')
      logger.error(`控制平面服务停止失败: ${error.message}`)
      throw error
    }
  }

  getStatus(): ServiceStatus {
    return {
      name: 'ControlPlaneService',
      status: this.status,
      lastUpdate: this.lastStatusChange,
      details: {
        subServices: {
          accountSync: 'running',
          hedgeExecution: 'running',
          marketDataFailover: 'running',
          strategyModule: 'running'
        },
        healthMetrics: this.getHealthMetrics()
      }
    }
  }

  /**
   * 账户同步接口
   */
  async syncAccounts(accountIds?: string[]): Promise<any> {
    if (accountIds && accountIds.length > 0) {
      // 同步指定账户
      const request = {
        requestId: `sync-${Date.now()}`,
        accounts: accountIds.map(id => ({
          accountId: id,
          exchange: this.exchangeAccountManager.getAccount(id)?.exchange || 'unknown',
          nonce: Date.now()
        }))
      }
      return this.accountSyncService.syncAccounts(request)
    } else {
      // 同步所有账户
      return this.accountSyncService.syncAllAccounts()
    }
  }

  /**
   * 对冲执行接口
   */
  async executeHedge(request: {
    primaryAccountId: string
    hedgeAccountId: string
    deltaBefore: number
    targetDelta: number
    triggerReason: 'utilization' | 'delta' | 'failover' | 'manual'
  }): Promise<any> {
    const hedgeRequest = {
      executionId: `hedge-${Date.now()}`,
      ...request
    }
    return this.hedgeExecutionService.executeHedge(hedgeRequest)
  }

  /**
   * 策略模块管理接口
   */
  async createStrategyModule(config: {
    name: string
    type: string
    configSchema: Record<string, any>
  }): Promise<any> {
    return this.strategyModuleService.createModule(config)
  }

  /**
   * 获取系统状态
   */
  getSystemStatus(): {
    controlPlane: ServiceStatus
    accounts: any
    risk: any
    marketData: any
    strategies: any
  } {
    return {
      controlPlane: this.getStatus(),
      accounts: {
        total: this.exchangeAccountManager.getAllAccounts().length,
        active: this.exchangeAccountManager.getAllAccounts().filter(a => a.status === 'active').length
      },
      risk: this.riskManager.getRiskStats(),
      marketData: this.marketDataFailoverService.getFailoverStats(),
      strategies: this.strategyModuleService.getAllModulesStatus()
    }
  }

  /**
   * 获取健康指标
   */
  getHealthMetrics(): {
    systemHealth: 'healthy' | 'degraded' | 'critical'
    activeAlerts: number
    criticalAlerts: number
    lastSyncTime: Date | null
    uptime: number
  } {
    const alerts = this.monitoringManager.getAllEvents()
    const activeAlerts = alerts.filter(a => !a.payload?.resolved).length
    const criticalAlerts = alerts.filter(a => a.severity === 'CRITICAL' && !a.payload?.resolved).length
    
    let systemHealth: 'healthy' | 'degraded' | 'critical' = 'healthy'
    if (criticalAlerts > 0) {
      systemHealth = 'critical'
    } else if (activeAlerts > 3) {
      systemHealth = 'degraded'
    }

    return {
      systemHealth,
      activeAlerts,
      criticalAlerts,
      lastSyncTime: new Date(),
      uptime: Date.now() - this.lastStatusChange
    }
  }

  /**
   * 获取账户同步服务
   */
  getAccountSyncService(): AccountSyncService {
    return this.accountSyncService
  }

  /**
   * 获取对冲执行服务
   */
  getHedgeExecutionService(): HedgeExecutionService {
    return this.hedgeExecutionService
  }

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

  /**
   * 获取策略模块服务
   */
  getStrategyModuleService(): StrategyModuleService {
    return this.strategyModuleService
  }

  /**
   * 初始化子服务
   */
  private async initializeSubServices(): Promise<void> {
    // 子服务初始化逻辑
    logger.debug('初始化控制平面子服务')
  }

  /**
   * 注册价格数据提供者
   */
  private registerPriceProviders(): void {
    // 注册现有的价格管理器作为提供者
    this.marketDataFailoverService.registerPriceProvider('global', {
      getPrice: async (symbol: string) => {
        const price = globalPriceManager.getPrice(symbol)
        return {
          price: price || 0,
          timestamp: Date.now(),
          source: 'global'
        }
      }
    })

    logger.debug('价格数据提供者注册完成')
  }

  /**
   * 注册交易所适配器
   */
  private registerExchangeAdapters(): void {
    // 注册现有的账户管理器作为适配器
    this.accountSyncService.registerAdapter('pacifica', {
      getAccountInfo: async (accountId: string) => {
        const state = this.accountManager.getAccountState(accountId)
        return {
          balances: [{
            asset: 'BTC',
            available: state?.availableBalance?.toString() || '0',
            total: state?.lastBalance?.toString() || '0',
            locked: (state?.marginUsed || 0).toString()
          }],
          positions: [{
            symbol: 'BTC',
            side: state?.netPosition && state.netPosition > 0 ? 'long' : 'short',
            size: Math.abs(state?.netPosition || 0).toString(),
            entryPrice: state?.entryPrice?.toString() || '0',
            markPrice: state?.currentPrice?.toString() || '0',
            unrealizedPnl: state?.unrealizedPnl?.toString() || '0'
          }]
        }
      }
    })

    logger.debug('交易所适配器注册完成')
  }

  /**
   * 启动健康检查
   */
  private startHealthCheck(): void {
    this.healthCheckInterval = setInterval(() => {
      this.performHealthCheck()
    }, 30000) // 每30秒检查一次

    logger.debug('健康检查启动')
  }

  /**
   * 执行健康检查
   */
  private performHealthCheck(): void {
    try {
      // 检查市场数据健康状态
      this.marketDataFailoverService.monitorFeedHealth()
      
      // 检查风险状态
      const accounts = this.exchangeAccountManager.getAllAccounts()
      for (const account of accounts) {
        const envelope = this.riskManager.getEnvelopeByAccount(account.accountId)
        if (envelope) {
          this.riskManager.checkRiskStatus(envelope.envelopeId)
        }
      }

      logger.debug('健康检查完成')
    } catch (error: any) {
      logger.warn(`健康检查失败: ${error.message}`)
    }
  }

  /**
   * 启动市场数据监控
   */
  private startMarketDataMonitoring(): void {
    // 启动市场数据失效监控
    logger.debug('市场数据监控启动')
  }

  /**
   * 创建模拟订单执行器
   */
  private createMockOrderExecutor(): any {
    return {
      executeOrder: async (signal: any) => {
        // 模拟订单执行
        return {
          success: true,
          orderId: `mock-${Date.now()}`,
          filledSize: signal.amount,
          avgPrice: '50000',
          fees: '0.001'
        }
      }
    }
  }

  /**
   * 更新状态
   */
  private updateStatus(newStatus: typeof this.status): void {
    if (this.status !== newStatus) {
      logger.info(`控制平面服务状态从 '${this.status}' 切换到 '${newStatus}'`, {
        oldStatus: this.status,
        newStatus: newStatus,
        duration: Date.now() - this.lastStatusChange
      })
      this.status = newStatus
      this.lastStatusChange = Date.now()
    }
  }
}

// 导出全局价格管理器引用
import { globalPriceManager } from '../modules/price/PriceManager.js'
