"""期权买一流动性：深度覆盖 + 买一相对标记偏差。"""

from __future__ import annotations


def contracts_for_eth(qty_eth: float, ct_mult: float) -> float:
    m = float(ct_mult) if ct_mult and ct_mult > 0 else 0.01
    return float(qty_eth) / m


def eth_from_contracts(contracts: float, ct_mult: float) -> float:
    m = float(ct_mult) if ct_mult and ct_mult > 0 else 0.01
    return float(contracts) * m


def bid_covers_eth(*, bid_sz_contracts: float | None, ct_mult: float, need_eth: float) -> bool:
    if bid_sz_contracts is None or bid_sz_contracts <= 0:
        return False
    return eth_from_contracts(bid_sz_contracts, ct_mult) + 1e-12 >= float(need_eth)


def bid_mark_deviation_pct(bid: float | None, mark: float | None) -> float | None:
    """|bid-mark|/mark * 100；无法计算返回 None。"""
    if bid is None or mark is None or mark <= 0 or bid < 0:
        return None
    return abs(float(bid) - float(mark)) / float(mark) * 100.0


def bid_mark_ok(
    *,
    bid: float | None,
    mark: float | None,
    max_dev_pct: float,
) -> tuple[bool, str]:
    """
    买一相对标记偏差是否可接受。
    max_dev_pct: 百分数，如 30 表示 30%。
    """
    if bid is None:
        return False, "期权买一不可用"
    if mark is None or mark <= 0:
        return False, "期权标记价不可用，等待"
    dev = bid_mark_deviation_pct(bid, mark)
    if dev is None:
        return False, "无法计算买一/标记偏差"
    if dev > float(max_dev_pct) + 1e-9:
        return False, f"买一相对标记偏差 {dev:.1f}% > {max_dev_pct:.0f}%，等待"
    return True, ""
