import numpy as np
import pandas as pd
from sklearn.linear_model import Ridge

URL = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv"
y = pd.read_csv(URL, index_col="Date", parse_dates=True)["Temp"].to_numpy()
L, H, K = 90, 14, 25                     # look-back, horizon, moving-average kernel

def decompose(windows, k=K):
    """Trend = centred moving average (edges padded), remainder = window - trend."""
    pad = np.pad(windows, ((0, 0), (k // 2, k // 2)), mode="edge")
    trend = np.stack([np.convolve(w, np.ones(k) / k, mode="valid") for w in pad])
    return trend, windows - trend

idx = np.arange(len(y) - L - H + 1)
X = np.stack([y[i:i + L] for i in idx])               # inputs: last L days
Y = np.stack([y[i + L:i + L + H] for i in idx])       # targets: next H days
split = int(0.8 * len(idx))

trend, rem = decompose(X)
# DLinear = one linear map for the trend + one for the remainder (here with a little ridge penalty)
lin_t = Ridge(alpha=1.0).fit(trend[:split], Y[:split])
lin_r = Ridge(alpha=1.0).fit(rem[:split], Y[:split] - lin_t.predict(trend[:split]))
pred = lin_t.predict(trend[split:]) + lin_r.predict(rem[split:])

mae_by_h = np.abs(pred - Y[split:]).mean(axis=0)
print("MAE by horizon (days 1, 7, 14):", mae_by_h[[0, 6, 13]].round(2))
print("seasonal-naive MAE (same day last year):", np.abs(y[-365 * 2:-365] - y[-365:]).mean().round(2))
