#!/usr/bin/env python3
# Source: t6-practitioner-toolkit.html
import numpy as np

def rolling_origin_splits(n, initial, horizon, step):
    """Yield (train_idx, test_idx). Train always ends before test starts."""
    if any(not isinstance(v, int) for v in (n, initial, horizon, step)):
        raise ValueError("Split counts must be integers")
    if n < 0 or min(initial, horizon, step) <= 0:
        raise ValueError("Use nonnegative length and positive split sizes")
    end = initial  # Each step lowers n - end until the next test exceeds n.
    while end + horizon <= n:
        yield np.arange(0, end), np.arange(end, end + horizon)
        end += step

def backtest(y, fit_predict, initial=365, horizon=28, step=28):
    errs = []
    for tr, te in rolling_origin_splits(len(y), initial, horizon, step):
        pred = fit_predict(y[tr], horizon)
        if np.sum(np.abs(y[te])) == 0:
            raise ValueError("WAPE is undefined when the test target sum is zero")
        errs.append(np.sum(np.abs(y[te] - pred)) / np.sum(np.abs(y[te])))  # WAPE
    if not errs:
        raise ValueError("No full test windows fit")
    return float(np.mean(errs)), float(np.std(errs))

def seasonal_naive(train, horizon, season=7):
    last = train[-season:]
    return np.resize(last, horizon)   # repeat last week
