import pandas as pd
import pandas_ta as ta


def detect_market_condition(df: pd.DataFrame) -> str:
    """
    Classify the current market condition using ADX and Bollinger Band width.

    Returns one of:
        TRENDING_UP      — ADX > 25 and price above midline
        TRENDING_DOWN    — ADX > 25 and price below midline
        HIGH_VOLATILITY  — BB width > 5% of midband
        SIDEWAYS         — everything else
    """
    if df is None or len(df) < 30:
        return "SIDEWAYS"

    # ADX (Average Directional Index) — measures trend strength
    adx_df = ta.adx(df["high"], df["low"], df["close"], length=14)
    if adx_df is None or adx_df.empty:
        return "SIDEWAYS"

    adx_col = [c for c in adx_df.columns if c.startswith("ADX_")]
    dmp_col = [c for c in adx_df.columns if c.startswith("DMP_")]
    dmn_col = [c for c in adx_df.columns if c.startswith("DMN_")]

    if not adx_col:
        return "SIDEWAYS"

    adx_val = float(adx_df[adx_col[0]].dropna().iloc[-1]) if not adx_df[adx_col[0]].dropna().empty else 0.0
    dmp_val = float(adx_df[dmp_col[0]].dropna().iloc[-1]) if dmp_col and not adx_df[dmp_col[0]].dropna().empty else 0.0
    dmn_val = float(adx_df[dmn_col[0]].dropna().iloc[-1]) if dmn_col and not adx_df[dmn_col[0]].dropna().empty else 0.0

    # Bollinger Bands — measures volatility
    bb = ta.bbands(df["close"], length=20, std=2)
    bb_width = 0.0
    if bb is not None and not bb.empty:
        upper_col = [c for c in bb.columns if "BBU" in c]
        lower_col = [c for c in bb.columns if "BBL" in c]
        mid_col = [c for c in bb.columns if "BBM" in c]
        if upper_col and lower_col and mid_col:
            upper = float(bb[upper_col[0]].dropna().iloc[-1])
            lower = float(bb[lower_col[0]].dropna().iloc[-1])
            mid = float(bb[mid_col[0]].dropna().iloc[-1])
            if mid > 0:
                bb_width = (upper - lower) / mid * 100  # as percentage

    if adx_val > 25:
        if dmp_val > dmn_val:
            return "TRENDING_UP"
        else:
            return "TRENDING_DOWN"

    if bb_width > 5.0:
        return "HIGH_VOLATILITY"

    return "SIDEWAYS"
