import numpy as np

from storai.schema.types import Metric


def compute_trend(series, name):
    if len(series) < 3:
        return []

    slope = np.polyfit(range(len(series)), series, 1)[0]
    mean_val = series.mean()

    # Normalize slope to represent % change per period relative to the mean
    # Avoid division by zero
    normalized_slope = slope / mean_val if mean_val != 0 else 0

    metric = Metric(
        type="trend",
        name=name,
        value=float(normalized_slope),
        context={},
    )

    return [metric]
