from storai.schema.types import Metric


def compute_growth(df, time_col, metric_col):
    if time_col not in df.columns:
        return []

    grouped = df.groupby(time_col)[metric_col].sum().sort_index()

    if len(grouped) < 2:
        return []

    metrics = []
    periods = list(grouped.index)

    for idx in range(1, len(grouped)):
        prev = grouped.iloc[idx - 1]
        curr = grouped.iloc[idx]

        if prev == 0:
            continue

        growth = (curr - prev) / prev
        metrics.append(
            Metric(
                type="growth",
                name=metric_col,
                value=growth,
                context={
                    "previous": float(prev),
                    "current": float(curr),
                    "period": str(periods[idx]),
                    "previous_period": str(periods[idx - 1]),
                },
            )
        )

    return metrics
