"""MACD histogram — deceleration flag + last bar value (port fedele da V15)."""

from __future__ import annotations

from typing import Tuple

import pandas as pd


def _macd_hist(df: pd.DataFrame) -> pd.Series:
    """Compute the MACD histogram series (EMA12-EMA26 minus its signal EMA9)."""
    ema12 = df["close"].ewm(span=12).mean()
    ema26 = df["close"].ewm(span=26).mean()
    macd_line = ema12 - ema26
    signal = macd_line.ewm(span=9).mean()
    return macd_line - signal


def calc_macd_decel(df: pd.DataFrame) -> bool:
    """
    True when |hist[-1]| < |hist[-2]| — i.e. MACD histogram is
    decelerating (momentum waning). Used as a soft signal in MR
    entry prompt and TF/MR exit prompts.
    """
    hist = _macd_hist(df)
    return bool(abs(hist.iloc[-1]) < abs(hist.iloc[-2]))


def calc_macd_hist(df: pd.DataFrame) -> float:
    """
    Last MACD histogram bar value. Positive ⇒ momentum bullish,
    negativo ⇒ momentum bearish. V18: usato dal gate
    MACD_ACCELERATING_AGAINST in brain_mr.evaluate_entry per scartare
    entry MR contro un momentum che sta accelerando contro la direzione.
    """
    hist = _macd_hist(df)
    return float(hist.iloc[-1])


def calc_macd_decel_and_hist(df: pd.DataFrame) -> Tuple[bool, float]:
    """
    Combined helper — calcola la serie istogramma una sola volta e
    ritorna (decelerating, hist_last). Preferito dal builder
    TechSnapshot per evitare di computare due volte EMA12/EMA26/signal.
    """
    hist = _macd_hist(df)
    decel = bool(abs(hist.iloc[-1]) < abs(hist.iloc[-2]))
    return decel, float(hist.iloc[-1])
