"""Options Analysis Agent — evaluates the options chain for the signal
direction: liquidity, open interest, bid/ask spread, IV, and Greeks.
Selects the best contract and scores chain quality 0-100."""
from .base import Agent, AgentResult
from ..services.market_data import MarketDataProvider


class OptionsAnalysisAgent(Agent):
    name = "options"

    def __init__(self, provider: MarketDataProvider):
        self.provider = provider

    def run(self, context: dict) -> AgentResult:
        symbol = context["symbol"]
        direction = context.get("direction", "CALL")
        price = context["quote"]["price"]
        opt_type = "call" if direction == "CALL" else "put"

        chain = [c for c in self.provider.get_options_chain(symbol) if c["type"] == opt_type]
        if not chain:
            return AgentResult(agent=self.name, score=0.0, notes=["No options chain available"])

        best, best_score, notes = None, -1.0, []
        for c in chain:
            mid = (c["bid"] + c["ask"]) / 2
            if mid <= 0:
                continue
            spread_pct = (c["ask"] - c["bid"]) / mid * 100
            target_delta = 0.55 if opt_type == "call" else -0.55
            delta_fit = max(0.0, 1 - abs(c["delta"] - target_delta) / 0.5)
            liquidity = min(1.0, c["open_interest"] / 5000) * 0.6 + min(1.0, c["volume"] / 2000) * 0.4
            tightness = max(0.0, 1 - spread_pct / 15)
            iv_quality = max(0.0, 1 - max(0.0, c["iv"] - 1.0))  # penalize IV > 100%
            s = (delta_fit * 35 + liquidity * 30 + tightness * 25 + iv_quality * 10)
            if s > best_score:
                best_score, best = s, {**c, "mid": round(mid, 2), "spread_pct": round(spread_pct, 1)}

        if best is None:
            return AgentResult(agent=self.name, score=0.0, notes=["No tradable contracts found"])

        notes.append(
            f"Selected {symbol} {best['expiry']} {best['strike']} {opt_type.upper()} "
            f"(delta {best['delta']}, OI {best['open_interest']}, spread {best['spread_pct']}%)"
        )
        if best["spread_pct"] > 10:
            notes.append("Wide bid/ask spread — execution cost risk")
        if best["open_interest"] < 500:
            notes.append("Low open interest — limited liquidity")
        if best["iv"] > 0.9:
            notes.append(f"Elevated IV {best['iv']:.0%} — premium is expensive")

        return AgentResult(agent=self.name, score=round(min(100.0, best_score), 1),
                           direction=direction, data={"contract": best, "moneyness_ref": price},
                           notes=notes)
