"""Example: Dual-timeframe signal.

Combines a short-term RSI signal with a longer-term trend filter.
Only takes RSI signals when they align with the trend direction.
"""

from __future__ import annotations

from vanta.tracker import TrackerBase
from vanta.indicators import RSI, EMA


class DualTimeframeTracker(TrackerBase):
    """RSI signal filtered by trend direction."""

    def __init__(self, rsi_period: int = 14, trend_period: int = 50):
        super().__init__()
        self.rsi = RSI(period=rsi_period)
        self.fast_ema = EMA(period=rsi_period)
        self.trend_ema = EMA(period=trend_period)

    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:
                price = float(close)
                self.rsi.update(price)
                self.fast_ema.update(price)
                self.trend_ema.update(price)

    def predict(self, symbol: str, horizon_seconds: int, step_seconds: int) -> dict:
        if not all([self.rsi.ready, self.fast_ema.ready, self.trend_ema.ready]):
            return {"expected_return": 0.0}

        # Trend direction
        uptrend = self.fast_ema.value > self.trend_ema.value
        rsi = self.rsi.value

        if uptrend and rsi < 40:
            # Uptrend + oversold dip → buy the dip
            strength = (40 - rsi) / 40
            return {"expected_return": 0.004 * strength}

        if not uptrend and rsi > 60:
            # Downtrend + overbought bounce → fade the bounce
            strength = (rsi - 60) / 40
            return {"expected_return": -0.004 * strength}

        return {"expected_return": 0.0}
