import { TradingService, ServiceStatus } from '../types.js'
import { AccountManager } from '../account/AccountManager.js'
import { RiskManager } from '../risk/RiskManager.js'
import { SamePlatformHedgingManager } from '../../core/hedging/SamePlatformHedgingManager.js'
import { logger } from '../../utils/logger.js'

/**
 * 对冲协调器 - 统一管理各种对冲策略
 */
export class HedgingCoordinator implements TradingService {
  private hedgingManager: SamePlatformHedgingManager | null = null
  private hedgeMonitoringInterval: NodeJS.Timeout | null = null
  private isActive = false

  private hedgingConfig = {
    rebalanceInterval: 30000, // 30秒检查一次再平衡
    maxExposureThreshold: 0.01, // 最大敞口阈值
    enableAutoHedging: true,
    hedgePairs: new Map<
      string,
      {
        primaryAccount: string
        hedgeAccount: string
        symbol: string
        rebalanceRatio: number
      }
    >(),
  }

  constructor(
    private accountManager: AccountManager,
    private riskManager: RiskManager,
  ) {}

  async initialize(): Promise<void> {
    logger.info('HedgingCoordinator初始化')
    this.initializeHedgingManager()
  }

  async start(): Promise<void> {
    logger.info('HedgingCoordinator启动')
    this.isActive = true
    this.startHedgeMonitoring()
  }

  async stop(): Promise<void> {
    logger.info('HedgingCoordinator停止')
    this.isActive = false
    if (this.hedgeMonitoringInterval) {
      clearInterval(this.hedgeMonitoringInterval)
      this.hedgeMonitoringInterval = null
    }
    if (this.hedgingManager) {
      await this.hedgingManager.stop()
    }
  }

  getStatus(): ServiceStatus {
    return {
      name: 'HedgingCoordinator',
      status: this.isActive ? 'running' : 'stopped',
      lastUpdate: Date.now(),
      details: {
        hedgePairs: this.hedgingConfig.hedgePairs.size,
        autoHedgingEnabled: this.hedgingConfig.enableAutoHedging,
        hedgingManager: this.hedgingManager ? 'initialized' : 'not_initialized',
      },
    }
  }

  /**
   * 初始化对冲管理器
   */
  private initializeHedgingManager(): void {
    try {
      this.hedgingManager = new SamePlatformHedgingManager('pacifica', {
        maxPositionSize: 0.01,
        maxTotalExposure: 0.05,
        emergencyStopLoss: 0.1,
        minAccountBalance: 10,
        enableRiskControls: true,
      })

      // 设置账户
      const clients = this.accountManager.getClients()
      for (const [clientId, client] of clients) {
        const account = this.getAccountFromClientId(clientId)
        if (account) {
          this.hedgingManager.addAccount(clientId, {
            account: account.accountId,
            privateKey: account.privateKey,
          })
        }
      }

      // 创建默认对冲对
      this.setupDefaultHedgePairs()

      logger.info('对冲管理器初始化完成')
    } catch (error: any) {
      logger.error('对冲管理器初始化失败', { error: error.message })
    }
  }

  /**
   * 设置默认对冲对
   */
  private setupDefaultHedgePairs(): void {
    if (!this.hedgingManager) return

    try {
      // 创建BTC对冲对
      this.hedgingManager.createHedgePair('btc-main-hedge', 'pacifica-1', 'pacifica-2', 'BTC-USD', 1.0)

      this.hedgingConfig.hedgePairs.set('btc-main-hedge', {
        primaryAccount: 'pacifica-1',
        hedgeAccount: 'pacifica-2',
        symbol: 'BTC-USD',
        rebalanceRatio: 1.0,
      })

      logger.info('默认对冲对创建完成')
    } catch (error: any) {
      logger.warn('创建默认对冲对失败', { error: error.message })
    }
  }

  /**
   * 启动对冲监控
   */
  private startHedgeMonitoring(): void {
    if (!this.hedgingConfig.enableAutoHedging) {
      logger.info('自动对冲已禁用')
      return
    }

    this.hedgeMonitoringInterval = setInterval(async () => {
      if (this.isActive) {
        await this.performAutomaticRebalancing()
      }
    }, this.hedgingConfig.rebalanceInterval)

    logger.info('对冲监控已启动')
  }

  /**
   * 执行自动再平衡
   */
  private async performAutomaticRebalancing(): Promise<void> {
    if (!this.hedgingManager) return

    try {
      // 检查净敞口
      const totalNetExposure = this.calculateTotalNetExposure()
      const exposureThreshold = this.riskManager.calculateDynamicExposureThreshold()

      if (Math.abs(totalNetExposure) > exposureThreshold) {
        logger.info('检测到敞口偏离，开始自动再平衡', {
          netExposure: totalNetExposure,
          threshold: exposureThreshold,
        })

        // 选择最优对冲对进行再平衡
        const hedgePairId = this.selectOptimalHedgePair(totalNetExposure)
        if (hedgePairId) {
          const adjustmentAmount = Math.min(Math.abs(totalNetExposure) * 0.8, 0.005)
          await this.hedgingManager.rebalanceHedgePair(hedgePairId, adjustmentAmount)
        }
      }

      // 定期风险检查
      const riskScore = await this.riskManager.calculateIntelligentRiskScore(this.getHedgingStats())
      if (riskScore.riskLevel === 'HIGH' || riskScore.riskLevel === 'CRITICAL') {
        logger.warn('检测到高风险状态，暂停自动对冲', { riskScore })
        this.hedgingConfig.enableAutoHedging = false
      }
    } catch (error: any) {
      logger.error('自动再平衡执行失败', { error: error.message })
    }
  }

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

  /**
   * 选择最优对冲对
   */
  private selectOptimalHedgePair(netExposure: number): string | null {
    const hedgePairs = Array.from(this.hedgingConfig.hedgePairs.entries())

    if (hedgePairs.length === 0) return null

    // 简单策略：选择第一个可用的对冲对
    const [pairId] = hedgePairs[0]
    return pairId
  }

  /**
   * 执行手动对冲
   */
  async executeManualHedge(options: {
    symbol: string
    amount: number
    primaryAccountId: string
    hedgeAccountId: string
  }): Promise<boolean> {
    if (!this.hedgingManager) {
      logger.error('对冲管理器未初始化')
      return false
    }

    try {
      const batchOrders = [
        {
          accountId: options.primaryAccountId,
          symbol: options.symbol,
          amount: options.amount,
          side: 'bid' as const,
          orderType: 'market' as const,
        },
        {
          accountId: options.hedgeAccountId,
          symbol: options.symbol,
          amount: options.amount,
          side: 'ask' as const,
          orderType: 'market' as const,
        },
      ]

      const results = await this.hedgingManager.executeBatchHedge(batchOrders)

      const successCount = results.filter(r => r.success).length
      const successRate = (successCount / results.length) * 100

      logger.info('手动对冲执行完成', {
        successRate: `${successRate.toFixed(1)}%`,
        successCount,
        totalOrders: results.length,
      })

      return successRate >= 50 // 至少50%成功率才认为成功
    } catch (error: any) {
      logger.error('手动对冲执行失败', { error: error.message })
      return false
    }
  }

  /**
   * 创建新的对冲对
   */
  createHedgePair(
    pairId: string,
    primaryAccount: string,
    hedgeAccount: string,
    symbol: string,
    ratio: number = 1.0,
  ): boolean {
    if (!this.hedgingManager) {
      logger.error('对冲管理器未初始化')
      return false
    }

    try {
      this.hedgingManager.createHedgePair(pairId, primaryAccount, hedgeAccount, symbol, ratio)

      this.hedgingConfig.hedgePairs.set(pairId, {
        primaryAccount,
        hedgeAccount,
        symbol,
        rebalanceRatio: ratio,
      })

      logger.info('对冲对创建成功', { pairId, primaryAccount, hedgeAccount, symbol, ratio })
      return true
    } catch (error: any) {
      logger.error('对冲对创建失败', { error: error.message, pairId })
      return false
    }
  }

  /**
   * 获取对冲统计信息
   */
  getHedgingStats() {
    const accountStats = this.accountManager.getAccountStats()
    return {
      ...accountStats,
      hedgePairs: this.hedgingConfig.hedgePairs.size,
      autoHedgingEnabled: this.hedgingConfig.enableAutoHedging,
      totalNetExposure: this.calculateTotalNetExposure(),
      sessionStartTime: Date.now() - 60000, // 模拟会话开始时间
    }
  }

  /**
   * 切换自动对冲
   */
  toggleAutoHedging(enabled: boolean): void {
    this.hedgingConfig.enableAutoHedging = enabled
    logger.info(`自动对冲已${enabled ? '启用' : '禁用'}`)
  }

  /**
   * 获取对冲管理器实例
   */
  getHedgingManager(): SamePlatformHedgingManager | null {
    return this.hedgingManager
  }

  /**
   * 从客户端ID获取账户信息
   */
  private getAccountFromClientId(clientId: string): { accountId: string; privateKey: string } | null {
    // 从环境变量获取真实的账户信息
    const accountIndex = parseInt(clientId.split('-')[1]) || 1
    const accountId = process.env[`PACIFICA_ACCOUNT_${accountIndex}`]
    const privateKey = process.env[`PACIFICA_PRIVATE_KEY_${accountIndex}`]

    if (!accountId || !privateKey) {
      logger.error(`无法获取账户 ${clientId} 的配置信息`)
      return null
    }

    return {
      accountId,
      privateKey,
    }
  }

  /**
   * 紧急停止所有对冲
   */
  async emergencyStopAllHedging(): Promise<void> {
    logger.warn('紧急停止所有对冲操作')
    this.hedgingConfig.enableAutoHedging = false

    if (this.hedgeMonitoringInterval) {
      clearInterval(this.hedgeMonitoringInterval)
      this.hedgeMonitoringInterval = null
    }

    if (this.hedgingManager) {
      await this.hedgingManager.stop()
    }
  }
}
