/**
 * 策略模块桥接服务
 * 连接现有 TradingEngineV2 与新的 StrategyModuleService
 * 实现 T032 任务：集成 StrategyModuleService 与现有 TradingEngineV2
 */
import { TradingEngineV2 } from '../modules/trading/TradingEngineV2.js'
import { StrategyModuleService } from './StrategyModuleService.js'
import { StrategyModuleManager, StrategyModule } from '../models/StrategyModule.js'
import { ExchangeAccountManager } from '../models/ExchangeAccount.js'
import { MonitoringEventManager } from '../models/MonitoringEvent.js'
import { TradingSignal } from '../modules/types.js'
import { logger } from '../utils/logger.js'

export interface StrategyModuleBridgeConfig {
  enableModuleRegistration: boolean // 是否启用模块注册
  moduleExecutionTimeout: number // 模块执行超时时间
  maxConcurrentModules: number // 最大并发模块数
  enableDryRunMode: boolean // 启用干运行模式
  sandboxIsolation: boolean // 沙箱隔离
  moduleValidation: boolean // 模块验证
}

export interface StrategyBridgeStats {
  registeredModules: number
  activeModules: number
  totalExecutions: number
  successfulExecutions: number
  failedExecutions: number
  sandboxTests: number
  lastExecutionTime: number
  bridgeMode: boolean
}

export class StrategyModuleBridge {
  private isRunning = false
  private executionStats = {
    totalExecutions: 0,
    successfulExecutions: 0,
    failedExecutions: 0,
    lastExecutionTime: 0,
    lastError: null as string | null
  }

  private registeredModules = new Map<string, StrategyModule>()
  private activeModules = new Set<string>()

  constructor(
    private tradingEngineV2: TradingEngineV2,
    private strategyModuleService: StrategyModuleService,
    private strategyModuleManager: StrategyModuleManager,
    private exchangeAccountManager: ExchangeAccountManager,
    private monitoringManager: MonitoringEventManager,
    private config: StrategyModuleBridgeConfig = {
      enableModuleRegistration: true,
      moduleExecutionTimeout: 30000, // 30秒超时
      maxConcurrentModules: 5,
      enableDryRunMode: true,
      sandboxIsolation: true,
      moduleValidation: true
    }
  ) {}

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

    logger.info('启动 StrategyModuleBridge 服务')
    
    try {
      // 1. 初始化策略模块
      await this.initializeStrategyModules()
      
      // 2. 注册现有策略
      await this.registerLegacyStrategies()
      
      // 3. 设置模块执行监控
      this.setupModuleExecutionMonitoring()
      
      this.isRunning = true
      logger.info('StrategyModuleBridge 启动成功')
      
    } catch (error: any) {
      logger.error(`StrategyModuleBridge 启动失败: ${error.message}`)
      throw error
    }
  }

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

    logger.info('停止 StrategyModuleBridge 服务')
    
    // 停止所有活动模块
    for (const moduleId of this.activeModules) {
      await this.stopModule(moduleId)
    }
    
    this.isRunning = false
    logger.info('StrategyModuleBridge 已停止')
  }

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

  /**
   * 初始化策略模块
   */
  private async initializeStrategyModules(): Promise<void> {
    logger.info('初始化策略模块')

    try {
      // 1. 创建基础策略模块
      await this.createBaseStrategyModules()

      // 2. 设置模块验证
      if (this.config.moduleValidation) {
        await this.setupModuleValidation()
      }

      // 3. 初始化沙箱环境
      if (this.config.sandboxIsolation) {
        await this.initializeSandboxEnvironment()
      }

      logger.info('策略模块初始化完成')
    } catch (error: any) {
      logger.error(`策略模块初始化失败: ${error.message}`)
      throw error
    }
  }

  /**
   * 创建基础策略模块
   */
  private async createBaseStrategyModules(): Promise<void> {
    logger.info('创建基础策略模块')

    // 1. 创建 Delta 中性策略模块
    const deltaNeutralModule: StrategyModule = {
      moduleId: 'delta-neutral-strategy',
      name: 'Delta Neutral Strategy',
      version: '1.0.0',
      type: 'hedging',
      status: 'active',
      config: {
        deltaThreshold: 0.0005,
        rebalanceInterval: 30000,
        maxPositionSize: 0.01,
        enableAutoRebalance: true
      },
      metadata: {
        author: 'System',
        description: 'Delta neutral hedging strategy for risk management',
        tags: ['hedging', 'risk-management', 'delta-neutral']
      },
      createdAt: new Date(),
      updatedAt: new Date()
    }

    this.strategyModuleManager.addModule(deltaNeutralModule)
    this.registeredModules.set(deltaNeutralModule.moduleId, deltaNeutralModule)

    // 2. 创建资金利用率管理策略模块
    const utilizationModule: StrategyModule = {
      moduleId: 'utilization-management-strategy',
      name: 'Capital Utilization Management',
      version: '1.0.0',
      type: 'allocation',
      status: 'active',
      config: {
        targetUtilizationMin: 0.5,
        targetUtilizationMax: 0.8,
        rebalanceThreshold: 0.1,
        enableAutoRebalance: true
      },
      metadata: {
        author: 'System',
        description: 'Capital utilization management strategy',
        tags: ['allocation', 'utilization', 'rebalancing']
      },
      createdAt: new Date(),
      updatedAt: new Date()
    }

    this.strategyModuleManager.addModule(utilizationModule)
    this.registeredModules.set(utilizationModule.moduleId, utilizationModule)

    // 3. 创建市场数据失效回退策略模块
    const failoverModule: StrategyModule = {
      moduleId: 'market-data-failover-strategy',
      name: 'Market Data Failover Strategy',
      version: '1.0.0',
      type: 'failover',
      status: 'active',
      config: {
        failoverTimeout: 10000,
        maxFailoverAttempts: 3,
        enableSyntheticPricing: true,
        syntheticPriceAccuracy: 0.001
      },
      metadata: {
        author: 'System',
        description: 'Market data failover and synthetic pricing strategy',
        tags: ['failover', 'market-data', 'synthetic-pricing']
      },
      createdAt: new Date(),
      updatedAt: new Date()
    }

    this.strategyModuleManager.addModule(failoverModule)
    this.registeredModules.set(failoverModule.moduleId, failoverModule)

    logger.info(`创建了 ${this.registeredModules.size} 个基础策略模块`)
  }

  /**
   * 设置模块验证
   */
  private async setupModuleValidation(): Promise<void> {
    logger.info('设置策略模块验证')

    // 验证所有注册的模块
    for (const [moduleId, module] of this.registeredModules) {
      try {
        const validation = await this.strategyModuleService.validateModule(module)
        
        if (validation.isValid) {
          logger.debug(`模块验证通过: ${moduleId}`)
        } else {
          logger.warn(`模块验证失败: ${moduleId}`, validation.errors)
          // 禁用无效模块
          module.status = 'disabled'
        }
      } catch (error: any) {
        logger.error(`模块验证异常: ${moduleId}`, { error: error.message })
        module.status = 'disabled'
      }
    }

    logger.info('策略模块验证完成')
  }

  /**
   * 初始化沙箱环境
   */
  private async initializeSandboxEnvironment(): Promise<void> {
    logger.info('初始化沙箱环境')

    // 为每个模块创建沙箱测试环境
    for (const [moduleId, module] of this.registeredModules) {
      try {
        const sandboxResult = await this.strategyModuleService.runSandboxTest(module)
        
        if (sandboxResult.success) {
          logger.debug(`沙箱测试通过: ${moduleId}`)
        } else {
          logger.warn(`沙箱测试失败: ${moduleId}`, sandboxResult.errors)
        }
      } catch (error: any) {
        logger.error(`沙箱测试异常: ${moduleId}`, { error: error.message })
      }
    }

    logger.info('沙箱环境初始化完成')
  }

  /**
   * 注册现有策略
   */
  private async registerLegacyStrategies(): Promise<void> {
    logger.info('注册现有交易策略')

    try {
      // 1. 注册现有的信号生成策略
      const signalGenerationModule: StrategyModule = {
        moduleId: 'legacy-signal-generation',
        name: 'Legacy Signal Generation',
        version: '1.0.0',
        type: 'signal',
        status: 'active',
        config: {
          signalInterval: 15000,
          confidenceThreshold: 0.7,
          enableVolumeBoost: true,
          volumeBoostInterval: 8000
        },
        metadata: {
          author: 'Legacy',
          description: 'Legacy signal generation strategy from TradingEngineV2',
          tags: ['legacy', 'signal-generation', 'volume-boost']
        },
        createdAt: new Date(),
        updatedAt: new Date()
      }

      this.strategyModuleManager.addModule(signalGenerationModule)
      this.registeredModules.set(signalGenerationModule.moduleId, signalGenerationModule)

      // 2. 注册现有的定价策略
      const pricingModule: StrategyModule = {
        moduleId: 'legacy-optimized-pricing',
        name: 'Legacy Optimized Pricing',
        version: '1.0.0',
        type: 'pricing',
        status: 'active',
        config: {
          targetFillProbability: 0.8,
          aggressiveness: 0.7,
          minProfitMargin: 0.001,
          enableOrderbookIntegration: true
        },
        metadata: {
          author: 'Legacy',
          description: 'Legacy optimized limit order pricing strategy',
          tags: ['legacy', 'pricing', 'orderbook']
        },
        createdAt: new Date(),
        updatedAt: new Date()
      }

      this.strategyModuleManager.addModule(pricingModule)
      this.registeredModules.set(pricingModule.moduleId, pricingModule)

      logger.info('现有策略注册完成')
    } catch (error: any) {
      logger.error(`现有策略注册失败: ${error.message}`)
      throw error
    }
  }

  /**
   * 设置模块执行监控
   */
  private setupModuleExecutionMonitoring(): void {
    logger.info('设置策略模块执行监控')

    // 创建策略模块桥接启动事件
    this.monitoringManager.addEvent({
      eventId: `strategy-bridge-start-${Date.now()}`,
      type: 'strategy-bridge-start',
      payload: {
        config: this.config,
        registeredModules: this.registeredModules.size,
        bridgeMode: true
      },
      severity: 'INFO',
      createdAt: new Date()
    })

    logger.info('策略模块执行监控设置完成')
  }

  /**
   * 执行策略模块
   */
  async executeModule(moduleId: string, context?: any): Promise<{
    success: boolean
    result?: any
    error?: string
  }> {
    try {
      const module = this.registeredModules.get(moduleId)
      if (!module) {
        return {
          success: false,
          error: `模块未找到: ${moduleId}`
        }
      }

      if (module.status !== 'active') {
        return {
          success: false,
          error: `模块未激活: ${moduleId}`
        }
      }

      if (this.activeModules.size >= this.config.maxConcurrentModules) {
        return {
          success: false,
          error: '达到最大并发模块数限制'
        }
      }

      this.activeModules.add(moduleId)
      this.executionStats.totalExecutions++

      logger.info(`执行策略模块: ${moduleId}`)

      let result: any
      
      if (this.config.enableDryRunMode) {
        // 干运行模式
        result = await this.executeModuleDryRun(module, context)
      } else {
        // 实际执行模式
        result = await this.executeModuleReal(module, context)
      }

      this.executionStats.successfulExecutions++
      this.executionStats.lastExecutionTime = Date.now()
      this.executionStats.lastError = null

      this.activeModules.delete(moduleId)

      return {
        success: true,
        result
      }

    } catch (error: any) {
      this.activeModules.delete(moduleId)
      this.executionStats.failedExecutions++
      this.executionStats.lastError = error.message
      
      logger.error(`策略模块执行失败: ${moduleId}`, { error: error.message })
      
      return {
        success: false,
        error: error.message
      }
    }
  }

  /**
   * 执行模块干运行
   */
  private async executeModuleDryRun(module: StrategyModule, context?: any): Promise<any> {
    logger.info(`执行模块干运行: ${module.moduleId}`)

    // 模拟模块执行
    const mockResult = {
      moduleId: module.moduleId,
      executionMode: 'dry-run',
      simulatedTrades: Math.floor(Math.random() * 3),
      simulatedVolume: Math.random() * 1000,
      executionTime: Date.now(),
      success: true
    }

    // 记录干运行结果
    this.monitoringManager.addEvent({
      eventId: `module-dry-run-${Date.now()}`,
      type: 'module-dry-run',
      payload: {
        moduleId: module.moduleId,
        result: mockResult
      },
      severity: 'INFO',
      createdAt: new Date()
    })

    return mockResult
  }

  /**
   * 执行模块实际运行
   */
  private async executeModuleReal(module: StrategyModule, context?: any): Promise<any> {
    logger.info(`执行模块实际运行: ${module.moduleId}`)

    // 根据模块类型执行相应的策略
    switch (module.type) {
      case 'hedging':
        return await this.executeHedgingModule(module, context)
      case 'allocation':
        return await this.executeAllocationModule(module, context)
      case 'failover':
        return await this.executeFailoverModule(module, context)
      case 'signal':
        return await this.executeSignalModule(module, context)
      case 'pricing':
        return await this.executePricingModule(module, context)
      default:
        throw new Error(`未知的模块类型: ${module.type}`)
    }
  }

  /**
   * 执行对冲模块
   */
  private async executeHedgingModule(module: StrategyModule, context?: any): Promise<any> {
    // 这里可以调用现有的对冲逻辑
    return {
      moduleId: module.moduleId,
      type: 'hedging',
      executed: true,
      timestamp: Date.now()
    }
  }

  /**
   * 执行分配模块
   */
  private async executeAllocationModule(module: StrategyModule, context?: any): Promise<any> {
    // 这里可以调用现有的资金分配逻辑
    return {
      moduleId: module.moduleId,
      type: 'allocation',
      executed: true,
      timestamp: Date.now()
    }
  }

  /**
   * 执行失效回退模块
   */
  private async executeFailoverModule(module: StrategyModule, context?: any): Promise<any> {
    // 这里可以调用现有的失效回退逻辑
    return {
      moduleId: module.moduleId,
      type: 'failover',
      executed: true,
      timestamp: Date.now()
    }
  }

  /**
   * 执行信号模块
   */
  private async executeSignalModule(module: StrategyModule, context?: any): Promise<any> {
    // 这里可以调用现有的信号生成逻辑
    return {
      moduleId: module.moduleId,
      type: 'signal',
      executed: true,
      timestamp: Date.now()
    }
  }

  /**
   * 执行定价模块
   */
  private async executePricingModule(module: StrategyModule, context?: any): Promise<any> {
    // 这里可以调用现有的定价逻辑
    return {
      moduleId: module.moduleId,
      type: 'pricing',
      executed: true,
      timestamp: Date.now()
    }
  }

  /**
   * 启动模块
   */
  async startModule(moduleId: string): Promise<{
    success: boolean
    message: string
  }> {
    try {
      const module = this.registeredModules.get(moduleId)
      if (!module) {
        return {
          success: false,
          message: `模块未找到: ${moduleId}`
        }
      }

      module.status = 'active'
      this.strategyModuleManager.updateModule(module)
      
      logger.info(`启动策略模块: ${moduleId}`)
      
      return {
        success: true,
        message: `模块启动成功: ${moduleId}`
      }
    } catch (error: any) {
      return {
        success: false,
        message: `模块启动失败: ${error.message}`
      }
    }
  }

  /**
   * 停止模块
   */
  async stopModule(moduleId: string): Promise<{
    success: boolean
    message: string
  }> {
    try {
      const module = this.registeredModules.get(moduleId)
      if (!module) {
        return {
          success: false,
          message: `模块未找到: ${moduleId}`
        }
      }

      module.status = 'stopped'
      this.strategyModuleManager.updateModule(module)
      
      // 从活动模块中移除
      this.activeModules.delete(moduleId)
      
      logger.info(`停止策略模块: ${moduleId}`)
      
      return {
        success: true,
        message: `模块停止成功: ${moduleId}`
      }
    } catch (error: any) {
      return {
        success: false,
        message: `模块停止失败: ${error.message}`
      }
    }
  }

  /**
   * 获取桥接统计信息
   */
  getBridgeStats(): StrategyBridgeStats {
    return {
      registeredModules: this.registeredModules.size,
      activeModules: Array.from(this.registeredModules.values()).filter(m => m.status === 'active').length,
      totalExecutions: this.executionStats.totalExecutions,
      successfulExecutions: this.executionStats.successfulExecutions,
      failedExecutions: this.executionStats.failedExecutions,
      sandboxTests: 0, // 可以从 StrategyModuleService 获取
      lastExecutionTime: this.executionStats.lastExecutionTime,
      bridgeMode: true
    }
  }

  /**
   * 获取注册的模块列表
   */
  getRegisteredModules(): StrategyModule[] {
    return Array.from(this.registeredModules.values())
  }

  /**
   * 获取活动模块列表
   */
  getActiveModules(): StrategyModule[] {
    return Array.from(this.registeredModules.values()).filter(m => m.status === 'active')
  }

  /**
   * 更新配置
   */
  updateConfig(newConfig: Partial<StrategyModuleBridgeConfig>): void {
    this.config = { ...this.config, ...newConfig }
    logger.info('策略模块桥接配置已更新', newConfig)
  }

  /**
   * 获取现有交易引擎
   */
  getTradingEngineV2(): TradingEngineV2 {
    return this.tradingEngineV2
  }

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