# src/risk/sizing/percent_risk.py
from .base import PositionSizer


class PercentRiskSizer(PositionSizer):
    """
    Position sizing basado en % de riesgo por trade,
    limitado por capital disponible.
    """

    def __init__(self, risk_fraction: float):
        if not 0 < risk_fraction <= 1:
            raise ValueError("risk_fraction debe estar entre 0 y 1")
        self.risk_fraction = risk_fraction

    def calculate_size(
        self,
        *,
        capital: float,
        entry_price: float,
        stop_price: float | None = None,
        max_capital: float | None = None,
        volatility=None,
    ) -> float:

        if stop_price is None:
            raise ValueError("PercentRiskSizer requiere stop_price")

        distance = abs(entry_price - stop_price)
        if distance <= 0:
            return 0.0

        # 1️⃣ Riesgo máximo permitido
        risk_amount = capital * self.risk_fraction
        units_by_risk = risk_amount / distance

        # 2️⃣ Límite por capital disponible
        if max_capital is not None:
            max_units_by_cash = max_capital / entry_price
            units = min(units_by_risk, max_units_by_cash)
        else:
            units = units_by_risk

        return max(units, 0.0)
