"""
Trailing stop manager: updates SL as price moves in our favour.
"""
import logging
from tabdeal_bot.config.settings import TradingConfig
from tabdeal_bot.exchange.models import Direction

logger = logging.getLogger(__name__)


class TrailingStopManager:
    def __init__(self, cfg: TradingConfig):
        self.cfg = cfg
        self._best_price: float = 0.0
        self._current_sl: float = 0.0
        self._direction: Direction = Direction.NONE

    def reset(self, entry_price: float, sl_price: float, direction: Direction):
        self._best_price = entry_price
        self._current_sl = sl_price
        self._direction = direction

    def update(self, current_price: float, atr: float) -> float:
        """
        Returns new SL price (possibly unchanged).
        Call on every price tick / candle close.
        """
        if not self.cfg.trailing_stop_enabled or self._direction == Direction.NONE:
            return self._current_sl

        trail = atr * self.cfg.trailing_stop_atr_multiplier

        if self._direction == Direction.LONG:
            if current_price > self._best_price:
                self._best_price = current_price
                new_sl = current_price - trail
                if new_sl > self._current_sl:
                    logger.info("Trailing SL updated: %.4f → %.4f", self._current_sl, new_sl)
                    self._current_sl = new_sl
        else:  # SHORT
            if current_price < self._best_price:
                self._best_price = current_price
                new_sl = current_price + trail
                if new_sl < self._current_sl:
                    logger.info("Trailing SL updated: %.4f → %.4f", self._current_sl, new_sl)
                    self._current_sl = new_sl

        return self._current_sl

    @property
    def current_sl(self) -> float:
        return self._current_sl
