from qfinindia.volatility.rnd import RND
from qfinindia.volatility.distribution import Distribution
from qfinindia.volatility.tailrisk import TailRisk
from qfinindia.volatility.vol_metrics import VolMetrics


class Analytics:
    """
    Unified analytics interface for option chains.

    Parameters
    ----------
    chain : OptionChain
    expiry : optional
        If None, the first expiry in the chain is used.
    """

    def __init__(self, chain, expiry=None):
        self.chain = chain

        # ---- robust auto-expiry ----
        if expiry is None:
            expiry = chain.default_expiry()
        else:
            expiry = chain.expiry(expiry).default_expiry()

        self.expiry = expiry

        # ---- core objects ----
        self.rnd = RND.from_chain(chain, expiry)
        self.dist = Distribution.from_rnd(self.rnd)
        self.tail = TailRisk.from_distribution(self.dist)
        self.vm = VolMetrics(chain)

    # ============================
    # Core implied metrics
    # ============================

    @property
    def spot(self):
        return self.chain.underlying

    @property
    def forward(self):
        return self.dist.mean()

    @property
    def expected_move(self):
        return self.dist.std()

    @property
    def skew(self):
        return self.dist.skew()

    @property
    def atm_vol(self):
        return self.vm.atm_vol()

    # ============================
    # Tail risk
    # ============================

    def var(self, q=0.05):
        return self.tail.var(q)

    def cvar(self, q=0.05):
        return self.tail.expected_shortfall(q)

    # ============================
    # Bias
    # ============================

    @property
    def bias(self):
        if self.forward > self.spot:
            return "Bullish"
        if self.forward < self.spot:
            return "Bearish"
        return "Neutral"
