"""
AkDevz AI Market Intelligence — Market Regime Classification Engine
Classifies market state into 12 distinct regimes based on trend, volatility, and volume.
"""
from typing import Dict, Any, List

class MarketRegimeEngine:
    @staticmethod
    def classify_regime(
        ltp: float,
        vwap: float,
        ema_9: float,
        ema_20: float,
        ema_50: float,
        adx: float,
        atr_current: float,
        atr_avg: float,
        open_price: float,
        prev_close: float
    ) -> Dict[str, Any]:
        reasons = []

        # Gap calculation
        gap_pct = ((open_price - prev_close) / prev_close) * 100.0 if prev_close > 0 else 0.0

        # Trend alignments
        is_above_vwap = ltp > vwap if vwap > 0 else False
        bullish_ema_stack = ema_9 > ema_20 > ema_50 if (ema_9 > 0 and ema_20 > 0 and ema_50 > 0) else False
        bearish_ema_stack = ema_9 < ema_20 < ema_50 if (ema_9 > 0 and ema_20 > 0 and ema_50 > 0) else False

        is_trending = adx >= 25.0 if adx > 0 else False
        is_choppy = adx < 18.0 if adx > 0 else True
        is_vol_expanding = atr_current > (1.25 * atr_avg) if (atr_avg > 0 and atr_current > 0) else False
        is_vol_contracting = atr_current < (0.75 * atr_avg) if (atr_avg > 0 and atr_current > 0) else False

        # Regime evaluation
        if abs(gap_pct) >= 0.75 and is_trending:
            if gap_pct > 0 and is_above_vwap:
                regime = "GAP_AND_GO"
                confidence = 85.0
                reasons.append(f"Significant gap up (+{gap_pct:.2f}%) holding above VWAP with ADX {adx:.1f}")
            elif gap_pct < 0 and not is_above_vwap:
                regime = "GAP_AND_GO"
                confidence = 85.0
                reasons.append(f"Significant gap down ({gap_pct:.2f}%) holding below VWAP with ADX {adx:.1f}")
            else:
                regime = "GAP_REVERSAL"
                confidence = 75.0
                reasons.append(f"Gap of {gap_pct:.2f}% failing to sustain; mean-reverting towards VWAP")
        elif is_trending and bullish_ema_stack and is_above_vwap:
            regime = "STRONG_BULLISH"
            confidence = 90.0
            reasons.append(f"Price above VWAP ({vwap:.2f}) with aligned 9/20/50 EMA stack and strong ADX ({adx:.1f})")
        elif is_trending and bearish_ema_stack and not is_above_vwap:
            regime = "STRONG_BEARISH"
            confidence = 90.0
            reasons.append(f"Price below VWAP ({vwap:.2f}) with descending 9/20/50 EMA stack and strong ADX ({adx:.1f})")
        elif bullish_ema_stack and is_above_vwap:
            regime = "WEAK_BULLISH"
            confidence = 70.0
            reasons.append("Bullish EMA alignment but ADX indicates moderate/weak momentum")
        elif bearish_ema_stack and not is_above_vwap:
            regime = "WEAK_BEARISH"
            confidence = 70.0
            reasons.append("Bearish EMA alignment but ADX indicates moderate/weak momentum")
        elif is_vol_expanding:
            regime = "HIGH_VOLATILITY"
            confidence = 80.0
            reasons.append(f"ATR expansion ({atr_current:.2f} > 1.25x avg {atr_avg:.2f}); wider stop-losses required")
        elif is_choppy:
            regime = "CHOPPY"
            confidence = 85.0
            reasons.append(f"ADX at {adx:.1f} (<18) indicating choppy sideways noise; breakout trades unsafe")
        elif is_vol_contracting:
            regime = "LOW_VOLATILITY"
            confidence = 75.0
            reasons.append(f"ATR contracting ({atr_current:.2f} < 0.75x avg); range compression preceding expansion")
        else:
            regime = "SIDEWAYS"
            confidence = 65.0
            reasons.append("Oscillating around VWAP without multi-timeframe directional agreement")

        return {
            "regime": regime,
            "confidence_pct": confidence,
            "is_trending": is_trending,
            "is_choppy": is_choppy,
            "reasons": reasons,
        }
