"""Price/RSI divergence flag — port fedele da V15."""

from __future__ import annotations

import pandas as pd


def calc_divergence(df: pd.DataFrame, rsi_series: pd.Series) -> str:
    """
    Returns "BULLISH", "BEARISH", or "NONE".

    Bearish: price made a new high vs last 9 bars but RSI did not.
    Bullish: price made a new low vs last 9 bars but RSI did not.
    """
    ph = df["close"].iloc[-1] > df["close"].iloc[-10:-1].max()
    pl = df["close"].iloc[-1] < df["close"].iloc[-10:-1].min()
    rh = rsi_series.iloc[-1] > rsi_series.iloc[-10:-1].max()
    rl = rsi_series.iloc[-1] < rsi_series.iloc[-10:-1].min()
    if ph and not rh:
        return "BEARISH"
    if pl and not rl:
        return "BULLISH"
    return "NONE"
