import { HedgeDecision, HedgeRequest } from './types'

export class HedgeCalculator {
  decide(req: HedgeRequest): HedgeDecision {
    const { perpPosition, prices, funding, config } = req

    // 非开仓状态不对冲
    if (!perpPosition.isOpen || perpPosition.size === 0) {
      return { shouldHedge: false, method: config.preferredMethod, hedgeQuantity: 0, reason: 'position_closed' }
    }

    const positionNotionalUsd = Math.abs(perpPosition.size * prices.perpPrice)
    if (positionNotionalUsd < config.thresholds.minNotionalUSD) {
      return { shouldHedge: false, method: config.preferredMethod, hedgeQuantity: 0, reason: 'notional_below_min' }
    }

    // 计算当前 delta 偏差（简化：方向 * 数量）
    const direction = perpPosition.side === 'long' ? 1 : -1
    const currentDelta = direction * perpPosition.size // 以 base 数量计

    // 目标 delta = 0，考虑相关系数与价格换算
    const hedgeQtyRaw =
      -currentDelta * (prices.perpPrice / prices.hedgePrice) * Math.max(0, Math.min(1, prices.correlation || 1))

    // 偏差阈值控制：若需要调整的数量占仓位比例过小则不执行
    const deltaDeviationPct = Math.abs(hedgeQtyRaw) / Math.max(1e-9, Math.abs(perpPosition.size))
    if (deltaDeviationPct < config.thresholds.deltaDeviationPct) {
      return { shouldHedge: false, method: config.preferredMethod, hedgeQuantity: 0, reason: 'delta_within_threshold' }
    }

    // 资金费率驱动：若费率绝对值低于门槛则不进行“费率对冲”
    if (Math.abs(funding.fundingRate) < config.thresholds.minFundingRate) {
      return { shouldHedge: false, method: config.preferredMethod, hedgeQuantity: 0, reason: 'funding_rate_low' }
    }

    // 粗略估算单周期资金费收益（正费率多付，负费率可赚）
    const expectedFundingPnlPerPeriod = -funding.fundingRate * positionNotionalUsd

    return {
      shouldHedge: true,
      method: config.preferredMethod,
      hedgeQuantity: hedgeQtyRaw,
      reason: 'delta_neutral_funding_driven',
      expectedFundingPnlPerPeriod,
    }
  }
}

export const hedgeCalculator = new HedgeCalculator()
