"""Volatility Ranking Agent — scores a symbol's tradability from ATR%,
day change, and relative volume."""
from .base import Agent, AgentResult
from .indicators import atr


class VolatilityAgent(Agent):
    name = "volatility"

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

        # Score: ideal ATR% between 2 and 6 — enough movement, not chaos.
        if atr_pct <= 0.5:
            vol_score = 10.0
        elif atr_pct < 2:
            vol_score = 30 + (atr_pct - 0.5) / 1.5 * 40
        elif atr_pct <= 6:
            vol_score = 70 + (atr_pct - 2) / 4 * 30
        else:
            vol_score = max(40.0, 100 - (atr_pct - 6) * 10)

        rvol_bonus = min(20.0, max(0.0, (quote["relative_volume"] - 1) * 10))
        score = round(min(100.0, vol_score * 0.8 + rvol_bonus), 1)

        return AgentResult(
            agent=self.name,
            score=score,
            data={"atr": a, "atr_pct": round(atr_pct, 2), "relative_volume": quote["relative_volume"]},
            notes=[f"ATR {a:.2f} ({atr_pct:.1f}% of price), relative volume {quote['relative_volume']:.1f}x"],
        )
