import { BasisDataPoint, BasisRiskAssessment, RiskScore, TradingService, ServiceStatus, AccountState } from '../types'
import { AccountManager } from '../account/AccountManager'
import { logger } from '../shared/utils/logger'

/**
 * 风险管理器 - 多维度风险评估和基差分析
 */
export class RiskManager implements TradingService {
  private basisHistory: BasisDataPoint[] = []
  private basisConfig = {
    maxDeviation: 200, // $200 基差预警阈值
    alertThreshold: 100, // $100 基差提醒阈值
    historyRetentionHours: 24, // 保留24小时历史
    enabledSymbols: ['BTC-USD', 'ETH-USD'], // 监控的交易对
    normalThreshold: 0.5, // 0.5% 正常基差阈值
    warningThreshold: 1.0, // 1.0% 基差预警阈值
    criticalThreshold: 2.0, // 2.0% 基差异常阈值
  }

  constructor(private accountManager: AccountManager) {}

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

  async start(): Promise<void> {
    logger.info('RiskManager启动')
  }

  async stop(): Promise<void> {
    logger.info('RiskManager停止')
    this.basisHistory = []
  }

  getStatus(): ServiceStatus {
    return {
      name: 'RiskManager',
      status: 'running',
      lastUpdate: Date.now(),
      details: {
        basisHistoryLength: this.basisHistory.length,
        lastRiskCheck: Date.now(),
      },
    }
  }

  /**
   * 基差风险评估
   */
  async assessBasisRisk(): Promise<BasisRiskAssessment> {
    try {
      // 模拟基差数据计算（生产环境应使用真实API）
      let spotPrice: number | null = null
      let futuresPrice: number | null = null

      try {
        spotPrice = 65000 // 现货价格估算
        futuresPrice = 65000 * (1 + (Math.random() - 0.5) * 0.002) // 期货价格：±0.1% 随机偏差

        logger.debug(`基差评估使用估算价格: 现货=${spotPrice}, 期货=${futuresPrice.toFixed(2)}`)
      } catch (error) {
        logger.warn('基差风险评估时价格获取失败', { error })
      }

      if (!spotPrice || !futuresPrice) {
        return {
          riskLevel: 'LOW',
          currentBasis: null,
          confidence: 0.3,
          message: '无法获取实时价格数据，基差风险评估置信度低',
          timestamp: Date.now(),
        }
      }

      // 计算基差和基差率
      const basis = futuresPrice - spotPrice
      const basisPercent = (basis / spotPrice) * 100

      // 基差风险评估逻辑
      let riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL'
      let message: string

      const absBasisPercent = Math.abs(basisPercent)

      if (absBasisPercent > this.basisConfig.criticalThreshold) {
        riskLevel = 'CRITICAL'
        message = `基差极端偏离 ${basisPercent.toFixed(3)}%，市场可能存在异常`
      } else if (absBasisPercent > this.basisConfig.warningThreshold) {
        riskLevel = 'HIGH'
        message = `基差偏离较大 ${basisPercent.toFixed(3)}%，套利风险增加`
      } else if (absBasisPercent > this.basisConfig.normalThreshold) {
        riskLevel = 'MEDIUM'
        message = `基差轻微偏离 ${basisPercent.toFixed(3)}%，需持续监控`
      } else {
        riskLevel = 'LOW'
        message = `基差正常 ${basisPercent.toFixed(3)}%，风险可控`
      }

      // 保存基差历史数据
      const basisDataPoint: BasisDataPoint = {
        spotPrice,
        futuresPrice,
        basis,
        basisPercent,
        timestamp: Date.now(),
      }

      this.updateBasisHistory(basisDataPoint)

      return {
        riskLevel,
        currentBasis: basisPercent,
        confidence: 0.8,
        message,
        timestamp: Date.now(),
      }
    } catch (error: any) {
      logger.error('基差风险评估失败', { error: error.message })
      return {
        riskLevel: 'MEDIUM',
        currentBasis: null,
        confidence: 0.2,
        message: '基差风险评估异常，建议谨慎交易',
        timestamp: Date.now(),
      }
    }
  }

  /**
   * 智能风险评估 - 多维度风险分析
   */
  async calculateIntelligentRiskScore(stats: any): Promise<RiskScore> {
    const factors: string[] = []
    const recommendations: string[] = []
    let riskScore = 0

    const accountStates = this.accountManager.getAllAccountStates()

    // 1. 交易成功率风险 (权重30%)
    const successRate = stats.totalTrades > 0 ? stats.successfulTrades / stats.totalTrades : 1
    if (successRate < 0.5) {
      riskScore += 30
      factors.push(`低成功率: ${(successRate * 100).toFixed(1)}%`)
      recommendations.push('建议降低交易频率或调整策略参数')
    } else if (successRate < 0.7) {
      riskScore += 15
      factors.push(`中等成功率: ${(successRate * 100).toFixed(1)}%`)
    }

    // 2. 仓位集中度风险 (权重25%)
    const totalPosition = Array.from(accountStates.values()).reduce(
      (sum, account) => sum + Math.abs(account.netPosition),
      0,
    )
    const totalBalance = Array.from(accountStates.values()).reduce((sum, account) => sum + account.lastBalance, 0)
    const avgBalance = totalBalance / Math.max(1, accountStates.size)

    const highPositionThreshold = avgBalance > 1000 ? 0.02 : avgBalance > 500 ? 0.015 : avgBalance > 200 ? 0.01 : 0.005
    const mediumPositionThreshold =
      avgBalance > 1000 ? 0.01 : avgBalance > 500 ? 0.008 : avgBalance > 200 ? 0.005 : 0.003

    if (totalPosition > highPositionThreshold) {
      riskScore += 25
      factors.push(`高仓位集中度: ${totalPosition.toFixed(4)} BTC (~${(totalPosition * 65000).toFixed(0)} USDT)`)
      recommendations.push('立即执行平仓操作降低风险暴露')
    } else if (totalPosition > mediumPositionThreshold) {
      riskScore += 12
      factors.push(`中等仓位集中度: ${totalPosition.toFixed(4)} BTC (~${(totalPosition * 65000).toFixed(0)} USDT)`)
      recommendations.push('考虑部分平仓以控制风险')
    }

    // 3. 资金安全风险 (权重20%)
    if (avgBalance < 50) {
      riskScore += 20
      factors.push(`低资金余额: $${avgBalance.toFixed(2)}`)
      recommendations.push('资金不足，建议停止交易或充值')
    } else if (avgBalance < 200) {
      riskScore += 10
      factors.push(`中低资金余额: $${avgBalance.toFixed(2)}`)
      recommendations.push('谨慎交易，限制交易规模')
    }

    // 4. 交易频率风险 (权重15%)
    const sessionTime = (Date.now() - stats.sessionStartTime) / 1000 / 60 // 分钟
    const tradeFrequency = sessionTime > 0 ? stats.totalTrades / sessionTime : 0
    if (tradeFrequency > 3) {
      riskScore += 15
      factors.push(`高频交易: ${tradeFrequency.toFixed(2)}笔/分钟`)
      recommendations.push('降低交易频率，避免账户被限制')
    } else if (tradeFrequency > 2) {
      riskScore += 8
      factors.push(`中高频交易: ${tradeFrequency.toFixed(2)}笔/分钟`)
    }

    // 5. Delta中性风险 (权重10%)
    const netDelta = Array.from(accountStates.values()).reduce((sum, account) => sum + account.netPosition, 0)
    const highDeltaThreshold = avgBalance > 1000 ? 0.008 : avgBalance > 500 ? 0.005 : avgBalance > 200 ? 0.003 : 0.002
    const mediumDeltaThreshold = avgBalance > 1000 ? 0.004 : avgBalance > 500 ? 0.003 : avgBalance > 200 ? 0.002 : 0.001

    if (Math.abs(netDelta) > highDeltaThreshold) {
      riskScore += 10
      factors.push(`Delta偏离: ${netDelta.toFixed(4)} BTC (~${(netDelta * 65000).toFixed(0)} USDT)`)
      recommendations.push('立即执行对冲操作恢复Delta中性')
    } else if (Math.abs(netDelta) > mediumDeltaThreshold) {
      riskScore += 5
      factors.push(`轻微 Delta偏离: ${netDelta.toFixed(4)} BTC (~${(netDelta * 65000).toFixed(0)} USDT)`)
    }

    // 6. 基差风险监控 (权重10%)
    const basisRisk = await this.assessBasisRisk()
    if (basisRisk.riskLevel === 'HIGH') {
      riskScore += 10
      factors.push(`高基差风险: ${basisRisk.currentBasis?.toFixed(2) || 'N/A'}% 偏离`)
      recommendations.push('基差异常，谨慎执行套利交易')
    } else if (basisRisk.riskLevel === 'MEDIUM') {
      riskScore += 5
      factors.push(`中等基差风险: ${basisRisk.currentBasis?.toFixed(2) || 'N/A'}% 偏离`)
      recommendations.push('监控基差变化趋势')
    } else if (basisRisk.riskLevel === 'CRITICAL') {
      riskScore += 15
      factors.push(`极端基差风险: ${basisRisk.currentBasis?.toFixed(2) || 'N/A'}% 异常偏离`)
      recommendations.push('暂停所有基差相关交易，等待市场恢复正常')
    }

    // 确定风险等级
    let riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL'
    if (riskScore >= 60) {
      riskLevel = 'CRITICAL'
      recommendations.unshift('紧急停止所有交易并进行风险评估')
    } else if (riskScore >= 40) {
      riskLevel = 'HIGH'
      recommendations.unshift('高度警惕，考虑暂停交易')
    } else if (riskScore >= 20) {
      riskLevel = 'MEDIUM'
      recommendations.unshift('中等风险，加强监控')
    } else {
      riskLevel = 'LOW'
      recommendations.push('风险可控，可继续正常交易')
    }

    return {
      riskScore,
      riskLevel,
      riskFactors: factors,
      recommendations,
    }
  }

  /**
   * 计算动态敞口阈值
   */
  calculateDynamicExposureThreshold(): number {
    const accountStates = this.accountManager.getAllAccountStates()
    const accounts = Array.from(accountStates.values())
    if (accounts.length === 0) return 0.0003

    // 计算最高使用率
    let maxUtilizationRate = 0
    accounts.forEach(account => {
      if (account.lastBalance > 0) {
        const utilizationRate = Math.abs(account.lastBalance - account.availableBalance) / account.lastBalance
        maxUtilizationRate = Math.max(maxUtilizationRate, utilizationRate)
      }
    })

    // 基础阈值
    let baseThreshold = 0.0003

    // 根据使用率动态调整阈值
    if (maxUtilizationRate >= 0.95) {
      baseThreshold = 0.0001
    } else if (maxUtilizationRate >= 0.9) {
      baseThreshold = 0.00015
    } else if (maxUtilizationRate >= 0.8) {
      baseThreshold = 0.0002
    } else if (maxUtilizationRate >= 0.7) {
      baseThreshold = 0.00025
    }

    return baseThreshold
  }

  /**
   * 更新基差历史数据
   */
  private updateBasisHistory(dataPoint: BasisDataPoint): void {
    if (!this.basisHistory) {
      this.basisHistory = []
    }
    this.basisHistory.push(dataPoint)
    if (this.basisHistory.length > 100) {
      this.basisHistory.shift()
    }
  }

  /**
   * 获取基差历史数据
   */
  getBasisHistory(): BasisDataPoint[] {
    return this.basisHistory
  }
}
