"""
=========================================
CV6 AI Trading OS
Simple Moving Average (SMA)
=========================================
"""

from app.indicators.indicator_validator import IndicatorValidator


class SMAIndicator:

    @staticmethod
    def calculate(
        prices: list[float],
        period: int
    ):
        """
        Calculate Simple Moving Average
        """

        validation = IndicatorValidator.validate_prices(
            prices,
            period
        )

        if not validation["valid"]:
            return validation

        sma_values = []

        for i in range(period - 1, len(prices)):

            window = prices[i - period + 1:i + 1]

            sma = sum(window) / period

            sma_values.append(
                round(sma, 2)
            )

        return sma_values

    @staticmethod
    def latest(
        prices: list[float],
        period: int
    ):

        result = SMAIndicator.calculate(
            prices,
            period
        )

        if isinstance(result, dict):
            return result

        return result[-1]