"""Market Regime Agent — classifies the overall market so strategies only
run in conditions they're built for (audit Phase 7: restricted strategies /
restricted market sessions).

Classification from the index proxy (SPY by default):
- bull:  price above SMA50 and EMA21 above SMA50
- bear:  price below SMA50 and EMA21 below SMA50
- chop:  mixed structure — trend-following strategies are DISABLED
- high_volatility overlay: index ATR% above threshold — position sizing halved
"""
import os

from .base import Agent, AgentResult
from .indicators import atr, ema, sma

REGIME_SYMBOL = os.getenv("REGIME_SYMBOL", "SPY")
HIGH_VOL_ATR_PCT = float(os.getenv("REGIME_HIGH_VOL_ATR_PCT", "2.5"))


class RegimeAgent(Agent):
    name = "regime"

    def run(self, context: dict) -> AgentResult:
        bars = context["history"]
        closes = [b["close"] for b in bars]
        price = closes[-1]
        e21, s50 = ema(closes, 21), sma(closes, 50)
        a = atr(bars) or 0.0
        atr_pct = (a / price * 100) if price else 0.0

        if e21 is None or s50 is None:
            regime = "unknown"
        elif price > s50 and e21 > s50:
            regime = "bull"
        elif price < s50 and e21 < s50:
            regime = "bear"
        else:
            regime = "chop"

        high_vol = atr_pct >= HIGH_VOL_ATR_PCT
        notes = [f"Index regime: {regime.upper()} (price {price:.2f} vs SMA50 "
                 f"{s50:.2f})" if s50 else "Insufficient index history",
                 f"Index ATR {atr_pct:.1f}% — {'HIGH volatility, sizing halved' if high_vol else 'normal volatility'}"]

        return AgentResult(
            agent=self.name,
            score=100.0 if regime in ("bull", "bear") else 40.0,
            data={"regime": regime, "high_volatility": high_vol,
                  "atr_pct": round(atr_pct, 2), "risk_scale": 0.5 if high_vol else 1.0},
            notes=notes,
        )
