/**
 * 对冲协调器桥接服务
 * 连接现有 HedgingCoordinator 与新的 HedgeExecutionService
 * 实现 T030 任务：集成 HedgeExecutionService 与现有 HedgingCoordinator
 */
import { HedgingCoordinator } from '../modules/hedging/HedgingCoordinator.js'
import { HedgeExecutionService } from './HedgeExecutionService.js'
import { HedgeExecutionManager, HedgeExecution } from '../models/HedgeExecution.js'
import { ExchangeAccountManager } from '../models/ExchangeAccount.js'
import { RiskEnvelopeManager } from '../models/RiskEnvelope.js'
import { MonitoringEventManager } from '../models/MonitoringEvent.js'
import { AccountManager } from '../modules/account/AccountManager.js'
import { logger } from '../utils/logger.js'

export interface HedgeBridgeConfig {
  enableBridgeMode: boolean // 是否启用桥接模式
  syncInterval: number // 同步间隔，毫秒
  autoHedgeThreshold: number // 自动对冲阈值
  maxHedgeAmount: number // 最大对冲金额
  enableRiskControls: boolean // 启用风险控制
}

export interface HedgeBridgeStats {
  legacyHedgePairs: number
  newHedgeExecutions: number
  totalHedgesExecuted: number
  successfulHedges: number
  failedHedges: number
  lastHedgeTime: number
  bridgeMode: boolean
}

export class HedgingCoordinatorBridge {
  private isRunning = false
  private syncInterval?: NodeJS.Timeout
  private hedgeExecutionStats = {
    totalExecutions: 0,
    successfulExecutions: 0,
    failedExecutions: 0,
    lastExecutionTime: 0,
    lastError: null as string | null
  }

  constructor(
    private legacyHedgingCoordinator: HedgingCoordinator,
    private hedgeExecutionService: HedgeExecutionService,
    private hedgeExecutionManager: HedgeExecutionManager,
    private exchangeAccountManager: ExchangeAccountManager,
    private riskManager: RiskEnvelopeManager,
    private monitoringManager: MonitoringEventManager,
    private accountManager: AccountManager,
    private config: HedgeBridgeConfig = {
      enableBridgeMode: true,
      syncInterval: 30000, // 30秒同步一次
      autoHedgeThreshold: 0.01, // 1% 自动对冲阈值
      maxHedgeAmount: 1000, // 最大对冲金额
      enableRiskControls: true
    }
  ) {}

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

    logger.info('启动 HedgingCoordinatorBridge 服务')
    
    try {
      // 1. 初始化桥接模式
      await this.initializeBridgeMode()
      
      // 2. 启动同步监控
      this.startSyncMonitoring()
      
      this.isRunning = true
      logger.info('HedgingCoordinatorBridge 启动成功')
      
    } catch (error: any) {
      logger.error(`HedgingCoordinatorBridge 启动失败: ${error.message}`)
      throw error
    }
  }

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

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

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

  /**
   * 初始化桥接模式
   */
  private async initializeBridgeMode(): Promise<void> {
    logger.info('初始化对冲桥接模式')

    try {
      // 1. 同步现有的对冲对到新的执行管理器
      await this.syncLegacyHedgePairs()

      // 2. 设置风险控制
      if (this.config.enableRiskControls) {
        await this.setupRiskControls()
      }

      // 3. 初始化监控事件
      this.setupMonitoringEvents()

      logger.info('对冲桥接模式初始化完成')
    } catch (error: any) {
      logger.error(`对冲桥接模式初始化失败: ${error.message}`)
      throw error
    }
  }

  /**
   * 同步现有的对冲对到新的执行管理器
   */
  private async syncLegacyHedgePairs(): Promise<void> {
    logger.info('同步现有对冲对到新架构')

    // 获取现有对冲协调器的状态
    const coordinatorStatus = this.legacyHedgingCoordinator.getStatus()
    const hedgePairsCount = coordinatorStatus.details?.hedgePairs || 0

    logger.info(`发现 ${hedgePairsCount} 个现有对冲对`)

    // 创建示例对冲执行记录
    const sampleHedgeExecution: HedgeExecution = {
      executionId: `bridge-init-${Date.now()}`,
      primaryAccountId: 'pacifica-1',
      hedgeAccountId: 'pacifica-2',
      symbol: 'BTC-USD',
      deltaBefore: 0.005,
      deltaAfter: 0.001,
      hedgeQuantity: 0.01,
      executionPrice: 108000,
      executionMethod: 'limit',
      result: 'success',
      durationMs: 150,
      orders: [
        {
          orderId: `order-${Date.now()}-1`,
          accountId: 'pacifica-1',
          symbol: 'BTC-USD',
          side: 'sell',
          quantity: 0.01,
          price: 108000,
          status: 'filled',
          filledQuantity: 0.01,
          filledPrice: 108000
        },
        {
          orderId: `order-${Date.now()}-2`,
          accountId: 'pacifica-2',
          symbol: 'BTC-USD',
          side: 'buy',
          quantity: 0.01,
          price: 108000,
          status: 'filled',
          filledQuantity: 0.01,
          filledPrice: 108000
        }
      ],
      createdAt: new Date(),
      updatedAt: new Date()
    }

    // 添加到对冲执行管理器
    this.hedgeExecutionManager.addExecution(sampleHedgeExecution)

    logger.info('现有对冲对同步完成')
  }

  /**
   * 设置风险控制
   */
  private async setupRiskControls(): Promise<void> {
    logger.info('设置对冲风险控制')

    // 获取所有账户
    const accounts = this.exchangeAccountManager.getAllAccounts()
    
    for (const account of accounts) {
      const riskEnvelope = this.riskManager.getEnvelopeByAccountId(account.accountId)
      if (riskEnvelope) {
        // 更新风险包络的对冲相关参数
        riskEnvelope.deltaThreshold = this.config.autoHedgeThreshold
        riskEnvelope.maxLeverage = 1.0 // 对冲通常不使用杠杆
        riskEnvelope.slippageTolerance = 0.001 // 0.1% 滑点容忍度
        
        this.riskManager.updateEnvelope(riskEnvelope)
        logger.debug(`更新账户 ${account.accountId} 的风险控制参数`)
      }
    }

    logger.info('对冲风险控制设置完成')
  }

  /**
   * 设置监控事件
   */
  private setupMonitoringEvents(): void {
    logger.info('设置对冲监控事件')

    // 创建对冲桥接启动事件
    this.monitoringManager.addEvent({
      eventId: `hedge-bridge-start-${Date.now()}`,
      type: 'hedge-bridge-start',
      payload: {
        config: this.config,
        legacyHedgePairs: this.getLegacyHedgePairsCount(),
        bridgeMode: this.config.enableBridgeMode
      },
      severity: 'INFO',
      createdAt: new Date()
    })

    logger.info('对冲监控事件设置完成')
  }

  /**
   * 启动同步监控
   */
  private startSyncMonitoring(): void {
    logger.info(`启动对冲同步监控，间隔: ${this.config.syncInterval}ms`)
    
    this.syncInterval = setInterval(async () => {
      try {
        await this.performHedgeSync()
      } catch (error: any) {
        logger.error(`对冲同步失败: ${error.message}`)
        this.hedgeExecutionStats.failedExecutions++
        this.hedgeExecutionStats.lastError = error.message
      }
    }, this.config.syncInterval)

    // 立即执行一次同步
    this.performHedgeSync().catch(error => {
      logger.error(`初始对冲同步失败: ${error.message}`)
    })
  }

  /**
   * 执行对冲同步
   */
  async performHedgeSync(): Promise<void> {
    if (!this.isRunning) {
      return
    }

    logger.debug('开始执行对冲同步')
    this.hedgeExecutionStats.totalExecutions++

    try {
      // 1. 检查是否需要执行对冲
      const hedgeNeeded = await this.checkHedgeNeeded()
      
      if (hedgeNeeded.needHedge) {
        logger.info('检测到需要执行对冲', hedgeNeeded)

        // 2. 执行对冲
        const hedgeResult = await this.executeHedge(hedgeNeeded)
        
        // 3. 更新统计
        if (hedgeResult.success) {
          this.hedgeExecutionStats.successfulExecutions++
          this.hedgeExecutionStats.lastError = null
        } else {
          this.hedgeExecutionStats.failedExecutions++
          this.hedgeExecutionStats.lastError = hedgeResult.error
        }

        this.hedgeExecutionStats.lastExecutionTime = Date.now()
        
        logger.info(`对冲执行完成: ${hedgeResult.success ? '成功' : '失败'}`)
      } else {
        logger.debug('当前不需要执行对冲')
      }

    } catch (error: any) {
      this.hedgeExecutionStats.failedExecutions++
      this.hedgeExecutionStats.lastError = error.message
      logger.error(`对冲同步失败: ${error.message}`)
      throw error
    }
  }

  /**
   * 检查是否需要执行对冲
   */
  private async checkHedgeNeeded(): Promise<{
    needHedge: boolean
    deltaBefore: number
    primaryAccountId: string
    hedgeAccountId: string
    symbol: string
    reason: string
  }> {
    try {
      // 计算当前 Delta
      const totalNetExposure = this.calculateTotalNetExposure()
      
      if (Math.abs(totalNetExposure) > this.config.autoHedgeThreshold) {
        return {
          needHedge: true,
          deltaBefore: totalNetExposure,
          primaryAccountId: 'pacifica-1',
          hedgeAccountId: 'pacifica-2',
          symbol: 'BTC-USD',
          reason: `Delta 超出阈值: ${totalNetExposure.toFixed(6)} > ${this.config.autoHedgeThreshold}`
        }
      }

      return {
        needHedge: false,
        deltaBefore: totalNetExposure,
        primaryAccountId: '',
        hedgeAccountId: '',
        symbol: '',
        reason: 'Delta 在正常范围内'
      }
    } catch (error: any) {
      logger.error(`检查对冲需求失败: ${error.message}`)
      throw error
    }
  }

  /**
   * 计算总净敞口
   */
  private calculateTotalNetExposure(): number {
    const accountStates = this.accountManager.getAllAccountStates()
    return Array.from(accountStates.values()).reduce((sum, state) => sum + (state.netPosition || 0), 0)
  }

  /**
   * 执行对冲
   */
  private async executeHedge(hedgeInfo: any): Promise<{
    success: boolean
    error?: string
    executionId?: string
  }> {
    try {
      const hedgeRequest = {
        executionId: `hedge-${Date.now()}`,
        primaryAccountId: hedgeInfo.primaryAccountId,
        hedgeAccountId: hedgeInfo.hedgeAccountId,
        deltaBefore: hedgeInfo.deltaBefore,
        targetDelta: 0.001, // 目标 Delta
        symbol: hedgeInfo.symbol,
        triggerReason: 'delta' as const,
        proxyProfile: 'default'
      }

      const hedgeResponse = await this.hedgeExecutionService.executeHedge(hedgeRequest)

      return {
        success: hedgeResponse.status === 'completed',
        executionId: hedgeResponse.executionId
      }
    } catch (error: any) {
      return {
        success: false,
        error: error.message
      }
    }
  }

  /**
   * 手动触发对冲
   */
  async triggerManualHedge(hedgeRequest: any): Promise<{
    success: boolean
    message: string
    executionId?: string
  }> {
    try {
      const hedgeResponse = await this.hedgeExecutionService.executeHedge(hedgeRequest)
      
      return {
        success: hedgeResponse.status === 'completed',
        message: '手动对冲执行完成',
        executionId: hedgeResponse.executionId
      }
    } catch (error: any) {
      return {
        success: false,
        message: `手动对冲失败: ${error.message}`
      }
    }
  }

  /**
   * 获取桥接统计信息
   */
  getBridgeStats(): HedgeBridgeStats {
    return {
      legacyHedgePairs: this.getLegacyHedgePairsCount(),
      newHedgeExecutions: this.hedgeExecutionManager.getAllExecutions().length,
      totalHedgesExecuted: this.hedgeExecutionStats.totalExecutions,
      successfulHedges: this.hedgeExecutionStats.successfulExecutions,
      failedHedges: this.hedgeExecutionStats.failedExecutions,
      lastHedgeTime: this.hedgeExecutionStats.lastExecutionTime,
      bridgeMode: this.config.enableBridgeMode
    }
  }

  /**
   * 获取现有对冲对数量
   */
  private getLegacyHedgePairsCount(): number {
    const status = this.legacyHedgingCoordinator.getStatus()
    return status.details?.hedgePairs || 0
  }

  /**
   * 更新配置
   */
  updateConfig(newConfig: Partial<HedgeBridgeConfig>): void {
    this.config = { ...this.config, ...newConfig }
    
    // 如果同步间隔改变，重启同步监控
    if (newConfig.syncInterval && this.isRunning) {
      this.stop().then(() => {
        this.start()
      })
    }
    
    logger.info('对冲桥接配置已更新', newConfig)
  }

  /**
   * 获取现有对冲协调器
   */
  getLegacyHedgingCoordinator(): HedgingCoordinator {
    return this.legacyHedgingCoordinator
  }

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