from storai.schema.types import Metric


def compute_rate(df, time_col, flag_col):
    grouped = df.groupby(time_col)[flag_col].mean().sort_index()

    if len(grouped) < 1:
        return []

    metrics = []
    curr = grouped.iloc[-1]

    # 1. Static Rate (Current status)
    metrics.append(
        Metric(
            type="rate",
            name=flag_col,
            value=float(curr),
            context={"period": str(grouped.index[-1])},
        )
    )

    # 2. Rate Change (if history exists)
    if len(grouped) >= 2:
        prev = grouped.iloc[-2]
        change = curr - prev
        metrics.append(
            Metric(
                type="rate_change",
                name=flag_col,
                value=float(change),
                context={
                    "previous": float(prev),
                    "current": float(curr),
                    "period": str(grouped.index[-1]),
                },
            )
        )

    return metrics
