"""Example: Bollinger Bands breakout signal.

Detects when price breaks above or below Bollinger Bands.
Breakout above upper band → short (mean reversion).
Breakout below lower band → long (mean reversion).
Uses percent_b to scale signal strength.
"""

from __future__ import annotations

from vanta.tracker import TrackerBase
from vanta.indicators import BollingerBands


class BollingerBreakoutTracker(TrackerBase):
    """Mean-reversion signal using Bollinger Band extremes."""

    def __init__(self, period: int = 20, num_std: float = 2.0):
        super().__init__()
        self.bb = BollingerBands(period=period, num_std=num_std)
        self._last_close: float | None = None

    def tick(self, data: dict) -> None:
        super().tick(data)
        for candle in data.get("candles_1m", []):
            close = candle.get("close")
            if close is not None:
                self.bb.update(float(close))
                self._last_close = float(close)

    def predict(self, symbol: str, horizon_seconds: int, step_seconds: int) -> dict:
        if not self.bb.ready or self._last_close is None:
            return {"expected_return": 0.0}

        pct_b = self.bb.value.percent_b

        # Outside bands → expect reversion
        if pct_b > 1.0:
            # Above upper band — expect price to fall
            return {"expected_return": -0.003 * (pct_b - 1.0)}
        elif pct_b < 0.0:
            # Below lower band — expect price to rise
            return {"expected_return": 0.003 * abs(pct_b)}

        return {"expected_return": 0.0}
