import polars as pl
from limen.indicators.sma import sma
import limen._feature_constraints as _check

DEFAULT_SMA_PERIODS = [5, 10, 20, 50]
EPSILON = 1e-10


def sma_ratios(data: pl.DataFrame, periods: list[int] | None = None, price_col: str = 'close') -> pl.DataFrame:

    '''
    Compute price to SMA ratios for multiple time periods.

    Args:
        data (pl.DataFrame): Klines dataset with price column
        periods (list): List of SMA periods to calculate ratios for
        price_col (str): Name of the price column (default: 'close')

    Returns:
        pl.DataFrame: The input data with new columns 'sma_{period}_ratio'
    '''

    _check.names(price_col=price_col)

    if periods is None:
        periods = DEFAULT_SMA_PERIODS
    periods = _check.integer_sequence('periods', periods, minimum=2, maximum=100000)
    df = data.clone()

    for period in periods:
        sma_col = f'{price_col}_sma_{period}'

        # Calculate SMA if not already present
        if sma_col not in df.collect_schema().names():
            df = sma(df, price_col, period)

        # Add ratio column
        df = df.with_columns([
            (pl.col(price_col) / (pl.col(sma_col) + EPSILON)).alias(f'sma_{period}_ratio')
        ])

    return df
