/**
 * 🛡️ RiskEnvelope - Delta中性控制平面风险包络模型
 *
 * 按照tasks规范实现的风险包络系统，支持：
 * - 每账户独立风险边界
 * - 动态风险参数调整
 * - 多维度风险监控
 * - 紧急风险响应
 * - 与Delta控制深度集成
 */
export interface RiskEnvelopeConfig {
  envelopeId: string // 主键，唯一标识
  accountId: string // 外键，关联ExchangeAccount
  maxDrawdownPercent: number // 最大回撤百分比
  maxLeverage: number // 最大杠杆倍数
  deltaThreshold?: number // Delta阈值（可覆盖账户级设定）
  slippageTolerance: number // 滑点容忍度（百分比）
  maxOrderSize: number // 单笔订单最大大小
  maxDailyVolume: number // 日最大交易量
  emergencyLiquidationThreshold: number // 紧急清算阈值
  createdAt?: Date
  updatedAt?: Date
}

export interface RiskMetrics {
  currentDrawdown: number // 当前回撤
  currentLeverage: number // 当前杠杆
  currentSlippage: number // 当前滑点
  dailyVolume: number // 今日交易量
  riskScore: number // 综合风险评分 (0-100)
  healthStatus: 'healthy' | 'warning' | 'critical' | 'emergency'
  lastUpdate: Date
}

export interface ViolationEvent {
  id: string
  type: 'drawdown' | 'leverage' | 'delta' | 'slippage' | 'volume' | 'emergency'
  severity: 'low' | 'medium' | 'high' | 'critical'
  threshold: number // 阈值
  actual: number // 实际值
  message: string
  timestamp: Date
  resolved: boolean
  resolvedAt?: Date
}

/**
 * RiskEnvelope - 账户风险包络实体
 */
export class RiskEnvelope {
  private config: RiskEnvelopeConfig
  private metrics: RiskMetrics
  private violations: ViolationEvent[] = []
  private emergencyMode = false
  private lastCheck: Date = new Date()
  private riskHistory: Array<{ time: Date; score: number; status: string }> = []

  constructor(config: RiskEnvelopeConfig) {
    this.config = { ...config }
    this.validateConfig()
    this.initializeMetrics()
  }

  /**
   * 验证风险包络配置
   */
  private validateConfig(): void {
    if (!this.config.envelopeId) {
      throw new Error('RiskEnvelope: envelopeId is required')
    }
    if (!this.config.accountId) {
      throw new Error('RiskEnvelope: accountId is required')
    }
    if (this.config.maxDrawdownPercent <= 0 || this.config.maxDrawdownPercent > 1) {
      throw new Error('RiskEnvelope: maxDrawdownPercent must be between 0 and 1')
    }
    if (this.config.maxLeverage <= 0) {
      throw new Error('RiskEnvelope: maxLeverage must be positive')
    }
    if (this.config.slippageTolerance < 0 || this.config.slippageTolerance > 1) {
      throw new Error('RiskEnvelope: slippageTolerance must be between 0 and 1')
    }
  }

  /**
   * 初始化风险指标
   */
  private initializeMetrics(): void {
    this.metrics = {
      currentDrawdown: 0,
      currentLeverage: 1,
      currentSlippage: 0,
      dailyVolume: 0,
      riskScore: 0,
      healthStatus: 'healthy',
      lastUpdate: new Date(),
    }
  }

  /**
   * 更新风险指标
   */
  updateMetrics(newMetrics: Partial<RiskMetrics>): void {
    this.metrics = {
      ...this.metrics,
      ...newMetrics,
      lastUpdate: new Date(),
    }

    // 重新计算风险评分
    this.calculateRiskScore()

    // 检查风险违规
    this.checkViolations()

    // 记录风险历史
    this.recordRiskHistory()
  }

  /**
   * 计算综合风险评分 (0-100)
   */
  private calculateRiskScore(): void {
    let score = 0

    // 回撤风险 (0-30分)
    const drawdownRatio = this.metrics.currentDrawdown / this.config.maxDrawdownPercent
    score += Math.min(drawdownRatio * 30, 30)

    // 杠杆风险 (0-25分)
    const leverageRatio = this.metrics.currentLeverage / this.config.maxLeverage
    score += Math.min(leverageRatio * 25, 25)

    // 滑点风险 (0-20分)
    const slippageRatio = this.metrics.currentSlippage / this.config.slippageTolerance
    score += Math.min(slippageRatio * 20, 20)

    // 交易量风险 (0-15分)
    const volumeRatio = this.metrics.dailyVolume / this.config.maxDailyVolume
    score += Math.min(volumeRatio * 15, 15)

    // 紧急模式额外风险 (0-10分)
    if (this.emergencyMode) {
      score += 10
    }

    this.metrics.riskScore = Math.min(score, 100)

    // 更新健康状态
    this.updateHealthStatus()
  }

  /**
   * 更新健康状态
   */
  private updateHealthStatus(): void {
    if (this.emergencyMode || this.metrics.riskScore >= 90) {
      this.metrics.healthStatus = 'emergency'
    } else if (this.metrics.riskScore >= 70) {
      this.metrics.healthStatus = 'critical'
    } else if (this.metrics.riskScore >= 40) {
      this.metrics.healthStatus = 'warning'
    } else {
      this.metrics.healthStatus = 'healthy'
    }
  }

  /**
   * 检查风险违规
   */
  private checkViolations(): void {
    // 检查回撤违规
    if (this.metrics.currentDrawdown > this.config.maxDrawdownPercent) {
      this.addViolation(
        'drawdown',
        'critical',
        this.config.maxDrawdownPercent,
        this.metrics.currentDrawdown,
        `回撤超过限制: ${(this.metrics.currentDrawdown * 100).toFixed(2)}% > ${(
          this.config.maxDrawdownPercent * 100
        ).toFixed(2)}%`,
      )
    }

    // 检查杠杆违规
    if (this.metrics.currentLeverage > this.config.maxLeverage) {
      this.addViolation(
        'leverage',
        'high',
        this.config.maxLeverage,
        this.metrics.currentLeverage,
        `杠杆超过限制: ${this.metrics.currentLeverage.toFixed(2)}x > ${this.config.maxLeverage.toFixed(2)}x`,
      )
    }

    // 检查滑点违规
    if (this.metrics.currentSlippage > this.config.slippageTolerance) {
      this.addViolation(
        'slippage',
        'medium',
        this.config.slippageTolerance,
        this.metrics.currentSlippage,
        `滑点超过容忍度: ${(this.metrics.currentSlippage * 100).toFixed(2)}% > ${(
          this.config.slippageTolerance * 100
        ).toFixed(2)}%`,
      )
    }

    // 检查交易量违规
    if (this.metrics.dailyVolume > this.config.maxDailyVolume) {
      this.addViolation(
        'volume',
        'medium',
        this.config.maxDailyVolume,
        this.metrics.dailyVolume,
        `日交易量超过限制: ${this.metrics.dailyVolume.toFixed(2)} > ${this.config.maxDailyVolume.toFixed(2)}`,
      )
    }

    // 检查紧急清算阈值
    if (this.metrics.currentDrawdown >= this.config.emergencyLiquidationThreshold) {
      this.addViolation(
        'emergency',
        'critical',
        this.config.emergencyLiquidationThreshold,
        this.metrics.currentDrawdown,
        `触发紧急清算阈值: ${(this.metrics.currentDrawdown * 100).toFixed(2)}%`,
      )
      this.triggerEmergencyMode('达到紧急清算阈值')
    }
  }

  /**
   * 添加违规事件
   */
  private addViolation(
    type: ViolationEvent['type'],
    severity: ViolationEvent['severity'],
    threshold: number,
    actual: number,
    message: string,
  ): void {
    const violation: ViolationEvent = {
      id: `${this.config.envelopeId}-${type}-${Date.now()}`,
      type,
      severity,
      threshold,
      actual,
      message,
      timestamp: new Date(),
      resolved: false,
    }

    this.violations.push(violation)

    console.log(`🚨 [RiskEnvelope:${this.config.accountId}] ${severity.toUpperCase()}: ${message}`)

    // 保留最近100条违规记录
    if (this.violations.length > 100) {
      this.violations = this.violations.slice(-100)
    }
  }

  /**
   * 记录风险历史
   */
  private recordRiskHistory(): void {
    this.riskHistory.push({
      time: new Date(),
      score: this.metrics.riskScore,
      status: this.metrics.healthStatus,
    })

    // 保留最近200条记录
    if (this.riskHistory.length > 200) {
      this.riskHistory = this.riskHistory.slice(-200)
    }
  }

  /**
   * 触发紧急模式
   */
  triggerEmergencyMode(reason: string): void {
    this.emergencyMode = true
    this.metrics.healthStatus = 'emergency'
    console.log(`🚨 [RiskEnvelope:${this.config.accountId}] 进入紧急模式: ${reason}`)

    this.addViolation('emergency', 'critical', 0, 1, `紧急模式激活: ${reason}`)
  }

  /**
   * 重置紧急模式
   */
  resetEmergencyMode(): void {
    this.emergencyMode = false
    console.log(`✅ [RiskEnvelope:${this.config.accountId}] 退出紧急模式`)

    // 标记最新的紧急违规为已解决
    const latestEmergencyViolation = this.violations.filter(v => v.type === 'emergency' && !v.resolved).pop()

    if (latestEmergencyViolation) {
      latestEmergencyViolation.resolved = true
      latestEmergencyViolation.resolvedAt = new Date()
    }

    // 重新计算风险评分
    this.calculateRiskScore()
  }

  /**
   * 检查是否可以执行交易
   */
  canExecuteTrade(
    orderSize: number,
    orderType: 'market' | 'limit',
  ): {
    allowed: boolean
    reason?: string
    maxAllowedSize?: number
  } {
    // 紧急模式下禁止新交易
    if (this.emergencyMode) {
      return { allowed: false, reason: '紧急模式下禁止交易' }
    }

    // 检查健康状态
    if (this.metrics.healthStatus === 'emergency') {
      return { allowed: false, reason: '风险状态为emergency，禁止交易' }
    }

    // 检查订单大小限制
    if (orderSize > this.config.maxOrderSize) {
      return {
        allowed: false,
        reason: `订单大小超过限制: ${orderSize} > ${this.config.maxOrderSize}`,
        maxAllowedSize: this.config.maxOrderSize,
      }
    }

    // 检查日交易量限制
    const remainingVolume = this.config.maxDailyVolume - this.metrics.dailyVolume
    if (orderSize > remainingVolume) {
      return {
        allowed: false,
        reason: `超过日交易量限制，剩余: ${remainingVolume.toFixed(2)}`,
        maxAllowedSize: remainingVolume,
      }
    }

    // 风险评分过高时限制市价单
    if (orderType === 'market' && this.metrics.riskScore > 80) {
      return { allowed: false, reason: '风险评分过高，禁止市价单交易' }
    }

    return { allowed: true }
  }

  /**
   * 获取配置
   */
  getConfig(): RiskEnvelopeConfig {
    return { ...this.config }
  }

  /**
   * 获取当前指标
   */
  getMetrics(): RiskMetrics {
    return { ...this.metrics }
  }

  /**
   * 获取活跃违规
   */
  getActiveViolations(): ViolationEvent[] {
    return this.violations.filter(v => !v.resolved)
  }

  /**
   * 获取风险历史
   */
  getRiskHistory(): Array<{ time: Date; score: number; status: string }> {
    return [...this.riskHistory]
  }

  /**
   * 是否处于紧急模式
   */
  isEmergencyMode(): boolean {
    return this.emergencyMode
  }

  /**
   * 获取风险包络摘要
   */
  getSummary(): any {
    return {
      envelopeId: this.config.envelopeId,
      accountId: this.config.accountId,
      riskScore: this.metrics.riskScore,
      healthStatus: this.metrics.healthStatus,
      emergencyMode: this.emergencyMode,
      activeViolations: this.getActiveViolations().length,
      limits: {
        maxDrawdown: `${(this.config.maxDrawdownPercent * 100).toFixed(1)}%`,
        maxLeverage: `${this.config.maxLeverage.toFixed(1)}x`,
        maxSlippage: `${(this.config.slippageTolerance * 100).toFixed(1)}%`,
        maxOrderSize: this.config.maxOrderSize,
        maxDailyVolume: this.config.maxDailyVolume,
      },
      current: {
        drawdown: `${(this.metrics.currentDrawdown * 100).toFixed(2)}%`,
        leverage: `${this.metrics.currentLeverage.toFixed(2)}x`,
        slippage: `${(this.metrics.currentSlippage * 100).toFixed(2)}%`,
        dailyVolume: this.metrics.dailyVolume.toFixed(2),
      },
      lastUpdate: this.metrics.lastUpdate,
    }
  }
}

/**
 * 风险指标
 */
export interface RiskMetrics {
  envelopeId: string
  accountId: string
  currentDelta: number // BTC 等值
  deltaDeviation: number // 偏离目标的程度
  currentUtilization: number // 当前利用率
  maxUtilization: number // 历史最大利用率
  currentDrawdown: number // 当前回撤
  maxDrawdown: number // 历史最大回撤
  currentLeverage: number // 当前杠杆
  maxLeverage: number // 历史最大杠杆
  slippage: number // 当前滑点
  positionValue: number // 当前仓位价值
  availableBalance: number // 可用余额
  totalBalance: number // 总余额
  timestamp: Date
}

/**
 * 风险警报
 */
export interface RiskAlert {
  alertId: string
  envelopeId: string
  accountId: string
  type:
    | 'delta-breach'
    | 'utilization-high'
    | 'utilization-low'
    | 'drawdown-exceeded'
    | 'leverage-exceeded'
    | 'slippage-high'
  severity: 'INFO' | 'WARN' | 'CRITICAL'
  message: string
  currentValue: number
  threshold: number
  deviation: number
  timestamp: Date
  acknowledged: boolean
  resolved: boolean
}

/**
 * 风险控制动作
 */
export interface RiskControlAction {
  actionId: string
  envelopeId: string
  accountId: string
  triggerAlertId: string
  actionType: 'hedge' | 'reduce-position' | 'emergency-stop' | 'halt-trading'
  description: string
  parameters: Record<string, any>
  status: 'pending' | 'executing' | 'completed' | 'failed'
  createdAt: Date
  completedAt?: Date
  error?: string
}

import { TradingService, ServiceStatus } from '../modules/types'
import { logger } from '../shared/utils/logger'

/**
 * RiskEnvelopeManager - 管理多个风险包络
 */
export class RiskEnvelopeManager implements TradingService {
  private status: 'stopped' | 'initializing' | 'running' | 'stopping' | 'error' = 'stopped'
  private lastStatusChange = Date.now()
  private envelopes: Map<string, RiskEnvelope> = new Map()
  private globalRiskLimits = {
    maxSystemRiskScore: 75,
    maxEmergencyAccounts: 2,
    maxCriticalAccounts: 5,
  }

  async initialize(): Promise<void> {
    logger.info('RiskEnvelopeManager初始化')
    this.status = 'running'
    this.lastStatusChange = Date.now()
  }

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

  async stop(): Promise<void> {
    logger.info('RiskEnvelopeManager停止')
    this.status = 'stopped'
    this.lastStatusChange = Date.now()
  }

  getStatus(): ServiceStatus {
    return {
      name: 'RiskEnvelopeManager',
      status: this.status === 'running' ? 'running' : 'stopped',
      lastUpdate: this.lastStatusChange,
    }
  }

  getLastStatusChange(): number {
    return this.lastStatusChange
  }

  /**
   * 创建风险包络
   */
  createRiskEnvelope(config: RiskEnvelopeConfig): RiskEnvelope {
    const envelope = new RiskEnvelope(config)
    this.envelopes.set(config.envelopeId, envelope)
    logger.info(`✅ [RiskEnvelopeManager] 创建风险包络: ${config.envelopeId} (账户: ${config.accountId})`)
    return envelope
  }

  /**
   * 添加风险包络
   */
  addEnvelope(config: RiskEnvelopeConfig): RiskEnvelope {
    const envelope = new RiskEnvelope(config)
    this.envelopes.set(config.envelopeId, envelope)
    console.log(`✅ [RiskEnvelopeManager] 添加风险包络: ${config.envelopeId} (账户: ${config.accountId})`)
    return envelope
  }

  /**
   * 获取风险包络
   */
  getRiskEnvelope(envelopeId: string): RiskEnvelope | undefined {
    return this.envelopes.get(envelopeId)
  }

  /**
   * 获取风险包络
   */
  getEnvelope(envelopeId: string): RiskEnvelope | undefined {
    return this.envelopes.get(envelopeId)
  }

  /**
   * 根据账户ID获取风险包络
   */
  getRiskEnvelopeByAccount(accountId: string): RiskEnvelope | undefined {
    for (const envelope of this.envelopes.values()) {
      if (envelope.getConfig().accountId === accountId) {
        return envelope
      }
    }
    return undefined
  }

  /**
   * 根据账户ID获取风险包络
   */
  getEnvelopeByAccount(accountId: string): RiskEnvelope | undefined {
    for (const envelope of this.envelopes.values()) {
      if (envelope.getConfig().accountId === accountId) {
        return envelope
      }
    }
    return undefined
  }

  /**
   * 获取所有风险包络
   */
  getAllEnvelopes(): RiskEnvelope[] {
    return Array.from(this.envelopes.values())
  }

  /**
   * 获取系统风险摘要
   */
  getSystemRiskSummary(): any {
    const envelopes = this.getAllEnvelopes()
    const systemRiskScore = this.calculateSystemRiskScore()

    const statusCounts = {
      healthy: 0,
      warning: 0,
      critical: 0,
      emergency: 0,
    }

    envelopes.forEach(envelope => {
      const status = envelope.getMetrics().healthStatus
      statusCounts[status]++
    })

    return {
      totalEnvelopes: envelopes.length,
      systemRiskScore,
      statusCounts,
      globalLimits: this.globalRiskLimits,
      systemHealthy:
        systemRiskScore < this.globalRiskLimits.maxSystemRiskScore &&
        statusCounts.emergency <= this.globalRiskLimits.maxEmergencyAccounts &&
        statusCounts.critical <= this.globalRiskLimits.maxCriticalAccounts,
      envelopes: envelopes.map(env => env.getSummary()),
    }
  }

  /**
   * 计算系统风险评分
   */
  private calculateSystemRiskScore(): number {
    const envelopes = this.getAllEnvelopes()
    if (envelopes.length === 0) return 0

    const totalRiskScore = envelopes.reduce((sum, env) => sum + env.getMetrics().riskScore, 0)
    return totalRiskScore / envelopes.length
  }

  /**
   * 检查系统是否可以执行交易
   */
  canSystemExecuteTrade(): { allowed: boolean; reason?: string } {
    const summary = this.getSystemRiskSummary()

    if (!summary.systemHealthy) {
      return { allowed: false, reason: '系统风险过高，暂停交易' }
    }

    if (summary.statusCounts.emergency > 0) {
      return { allowed: false, reason: '存在紧急状态账户，暂停系统交易' }
    }

    return { allowed: true }
  }
}
