/**
 * 🏦 ExchangeAccount - Delta中性控制平面账户模型
 *
 * 按照tasks规范重构的核心账户实体，支持：
 * - Delta中性控制参数
 * - 资金利用率目标管理 (50%-80%)
 * - 风险包络关联
 * - 代理会话管理
 * - 紧急控制状态
 */
export interface ExchangeAccountConfig {
  accountId: string // 主键，唯一标识
  exchange: 'pacifica' | 'aster' | 'binance' // 交易所类型
  accountName: string // 展示用别名
  publicKey: string // 经过加密存储
  privateKey?: string // 私钥（加密存储）
  proxyProfile: string // 引用代理配置ID
  utilizationTargetMin: number // 默认0.5 (50%)
  utilizationTargetMax: number // 默认0.8 (80%)
  deltaThreshold: number // BTC等值，默认0.0005
  maxPositionValue: number // 账户允许的最大名义价值
  stopLossConfigId: string // 引用止损模板
  status: 'active' | 'paused' | 'emergency' // 账户状态
  createdAt?: Date
  updatedAt?: Date
}

export interface AccountMetrics {
  currentUtilization: number // 当前资金利用率
  currentDelta: number // 当前Delta敞口 (BTC等值)
  netPosition: number // 净仓位
  totalBalance: number // 总余额
  availableBalance: number // 可用余额
  unrealizedPnl: number // 未实现盈亏
  leverage: number // 当前杠杆倍数
  lastUpdate: Date // 最后更新时间
}

export interface DeltaControlParams {
  targetDelta: number // 目标Delta (通常为0)
  deltaThreshold: number // Delta阈值
  rebalanceThreshold: number // 再平衡触发阈值
  maxHedgeSize: number // 单次最大对冲大小
  emergencyThreshold: number // 紧急对冲阈值
  controlCycleInterval: number // 控制循环间隔(ms)
}

/**
 * ExchangeAccount - Delta中性控制平面的核心账户实体
 */
export class ExchangeAccount {
  private config: ExchangeAccountConfig
  private metrics: AccountMetrics
  private deltaParams: DeltaControlParams
  private riskEnvelopeId?: string
  private proxySessionIds: string[] = []
  private lastDeltaCheck: Date = new Date()
  private deltaHistory: Array<{ time: Date; delta: number; utilization: number }> = []

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

  /**
   * 验证账户配置
   */
  private validateConfig(): void {
    if (!this.config.accountId) {
      throw new Error('ExchangeAccount: accountId is required')
    }
    if (this.config.utilizationTargetMin < 0 || this.config.utilizationTargetMin > 1) {
      throw new Error('ExchangeAccount: utilizationTargetMin must be between 0 and 1')
    }
    if (this.config.utilizationTargetMax < 0 || this.config.utilizationTargetMax > 1) {
      throw new Error('ExchangeAccount: utilizationTargetMax must be between 0 and 1')
    }
    if (this.config.utilizationTargetMin >= this.config.utilizationTargetMax) {
      throw new Error('ExchangeAccount: utilizationTargetMin must be less than utilizationTargetMax')
    }
    if (this.config.deltaThreshold <= 0) {
      throw new Error('ExchangeAccount: deltaThreshold must be positive')
    }
  }

  /**
   * 初始化账户指标
   */
  private initializeMetrics(): void {
    this.metrics = {
      currentUtilization: 0,
      currentDelta: 0,
      netPosition: 0,
      totalBalance: 0,
      availableBalance: 0,
      unrealizedPnl: 0,
      leverage: 1,
      lastUpdate: new Date(),
    }
  }

  /**
   * 初始化Delta控制参数
   */
  private initializeDeltaParams(): void {
    this.deltaParams = {
      targetDelta: 0, // Delta中性目标
      deltaThreshold: this.config.deltaThreshold,
      rebalanceThreshold: this.config.deltaThreshold * 0.8, // 80%阈值时开始再平衡
      maxHedgeSize: this.config.maxPositionValue * 0.1, // 最大10%仓位进行对冲
      emergencyThreshold: this.config.deltaThreshold * 2, // 2倍阈值紧急对冲
      controlCycleInterval: 8000, // 8秒控制循环
    }
  }

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

    // 记录Delta历史
    this.recordDeltaHistory()

    // 检查是否需要Delta控制
    this.checkDeltaNeutralRequirement()
  }

  /**
   * 记录Delta历史
   */
  private recordDeltaHistory(): void {
    this.deltaHistory.push({
      time: new Date(),
      delta: this.metrics.currentDelta,
      utilization: this.metrics.currentUtilization,
    })

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

  /**
   * 检查Delta中性要求
   */
  private checkDeltaNeutralRequirement(): boolean {
    const deltaExceeded = Math.abs(this.metrics.currentDelta) > this.deltaParams.deltaThreshold
    const utilizationOutOfRange =
      this.metrics.currentUtilization < this.config.utilizationTargetMin ||
      this.metrics.currentUtilization > this.config.utilizationTargetMax

    if (deltaExceeded || utilizationOutOfRange) {
      console.log(
        `🚨 [${this.config.accountId}] Delta中性检查: Delta=${this.metrics.currentDelta.toFixed(6)}, 利用率=${(
          this.metrics.currentUtilization * 100
        ).toFixed(1)}%`,
      )
      return true
    }

    return false
  }

  /**
   * 判断是否需要紧急对冲
   */
  needsEmergencyHedge(): boolean {
    return (
      Math.abs(this.metrics.currentDelta) > this.deltaParams.emergencyThreshold || this.config.status === 'emergency'
    )
  }

  /**
   * 判断是否需要再平衡
   */
  needsRebalance(): boolean {
    return (
      Math.abs(this.metrics.currentDelta) > this.deltaParams.rebalanceThreshold ||
      this.metrics.currentUtilization < this.config.utilizationTargetMin ||
      this.metrics.currentUtilization > this.config.utilizationTargetMax
    )
  }

  /**
   * 计算建议的对冲大小
   */
  calculateHedgeSize(): number {
    const deltaDiff = this.metrics.currentDelta - this.deltaParams.targetDelta
    let hedgeSize = Math.abs(deltaDiff)

    // 限制最大对冲大小
    hedgeSize = Math.min(hedgeSize, this.deltaParams.maxHedgeSize)

    // 如果是紧急情况，使用更激进的对冲
    if (this.needsEmergencyHedge()) {
      hedgeSize = Math.min(Math.abs(deltaDiff), this.config.maxPositionValue * 0.2)
    }

    return hedgeSize
  }

  /**
   * 计算目标利用率调整
   */
  calculateUtilizationAdjustment(): number {
    const currentUtil = this.metrics.currentUtilization
    const targetMin = this.config.utilizationTargetMin
    const targetMax = this.config.utilizationTargetMax
    const targetCenter = (targetMin + targetMax) / 2

    if (currentUtil < targetMin) {
      return targetCenter - currentUtil // 需要增加利用率
    } else if (currentUtil > targetMax) {
      return targetCenter - currentUtil // 需要减少利用率
    }

    return 0 // 在目标范围内
  }

  /**
   * 设置紧急状态
   */
  setEmergencyStatus(reason: string): void {
    this.config.status = 'emergency'
    this.config.updatedAt = new Date()
    console.log(`🚨 [${this.config.accountId}] 进入紧急状态: ${reason}`)
  }

  /**
   * 重置为正常状态
   */
  resetToActive(): void {
    this.config.status = 'active'
    this.config.updatedAt = new Date()
    console.log(`✅ [${this.config.accountId}] 恢复正常状态`)
  }

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

  /**
   * 获取账户指标
   */
  getMetrics(): AccountMetrics {
    return { ...this.metrics }
  }

  /**
   * 获取Delta控制参数
   */
  getDeltaParams(): DeltaControlParams {
    return { ...this.deltaParams }
  }

  /**
   * 获取Delta历史
   */
  getDeltaHistory(): Array<{ time: Date; delta: number; utilization: number }> {
    return [...this.deltaHistory]
  }

  /**
   * 关联风险包络
   */
  setRiskEnvelope(envelopeId: string): void {
    this.riskEnvelopeId = envelopeId
  }

  /**
   * 添加代理会话
   */
  addProxySession(sessionId: string): void {
    if (!this.proxySessionIds.includes(sessionId)) {
      this.proxySessionIds.push(sessionId)
    }
  }

  /**
   * 移除代理会话
   */
  removeProxySession(sessionId: string): void {
    this.proxySessionIds = this.proxySessionIds.filter(id => id !== sessionId)
  }

  /**
   * 获取账户状态摘要
   */
  getStatusSummary(): any {
    return {
      accountId: this.config.accountId,
      exchange: this.config.exchange,
      status: this.config.status,
      delta: {
        current: this.metrics.currentDelta,
        threshold: this.deltaParams.deltaThreshold,
        needsHedge: this.needsEmergencyHedge(),
        needsRebalance: this.needsRebalance(),
      },
      utilization: {
        current: this.metrics.currentUtilization,
        target: `${(this.config.utilizationTargetMin * 100).toFixed(0)}%-${(
          this.config.utilizationTargetMax * 100
        ).toFixed(0)}%`,
        adjustment: this.calculateUtilizationAdjustment(),
      },
      position: {
        net: this.metrics.netPosition,
        total: this.metrics.totalBalance,
        available: this.metrics.availableBalance,
        pnl: this.metrics.unrealizedPnl,
      },
      riskEnvelopeId: this.riskEnvelopeId,
      proxySessionCount: this.proxySessionIds.length,
      lastUpdate: this.metrics.lastUpdate,
    }
  }
}

/**
 * 账户余额信息
 */
export interface AccountBalance {
  asset: string
  total: string // 字符串表示，保留精度
  available: string // 字符串表示，保留精度
}

/**
 * 账户仓位信息
 */
export interface AccountPosition {
  symbol: string
  side: 'long' | 'short'
  size: string // 字符串表示，保留精度
  entryPrice: string // 字符串表示，保留精度
  markPrice: string // 字符串表示，保留精度
  unrealizedPnl: string // 字符串表示，保留精度
}

/**
 * 账户利用率信息
 */
export interface AccountUtilization {
  value: number // 数值型，便于对齐 50%-80% 目标
  formula: string // 公式描述
}

/**
 * 账户同步请求
 */
export interface AccountSyncRequest {
  requestId: string
  accounts: Array<{
    accountId: string
    exchange: string
    nonce: number
  }>
}

/**
 * 账户同步响应
 */
export interface AccountSyncResponse {
  requestId: string
  timestamp: string
  results: Array<{
    accountId: string
    status: 'success' | 'failed'
    balances?: AccountBalance[]
    positions?: AccountPosition[]
    utilization?: AccountUtilization
  }>
  errors: Array<{
    accountId: string
    code: string
    message: string
    retryable?: boolean
  }>
}
