"""Original deterministic teaching series; actual statsmodels ARIMA fits.

Validation uses two expanding origins; the final block never selects a model.
The signal is hand-specified, not a random sample or a forecasting benchmark.
"""
import json
import platform
import warnings

import numpy as np
import pandas as pd
import scipy
import statsmodels
from statsmodels.tsa.arima.model import ARIMA


PERIOD = 12
HORIZON = 12
PATTERN = (-10, -8, -4, 0, 4, 8, 12, 14, 10, 4, -4, -8)
DISTURBANCE = (-1, 0, 1, 0, -1)
SERIES = [100 + 0.4 * t + PATTERN[t % PERIOD] + DISTURBANCE[t % 5]
          for t in range(96)]
CANDIDATES = ("last_value", "seasonal_naive", "ARIMA(1,1,0)", "ARIMA(0,1,1)")


def forecast(history, name):
    """Accept history only: future observations are not an input."""
    history = np.asarray(history, dtype=float)
    if name == "last_value":
        return np.repeat(history[-1], HORIZON), None, None, []
    if name == "seasonal_naive":
        assert len(history) >= PERIOD and HORIZON <= PERIOD
        return history[-PERIOD:][:HORIZON].copy(), None, None, []
    order = {"ARIMA(1,1,0)": (1, 1, 0), "ARIMA(0,1,1)": (0, 1, 1)}[name]
    with warnings.catch_warnings(record=True) as recorded:
        warnings.simplefilter("always")
        fitted = ARIMA(history, order=order, trend="n",
                       enforce_stationarity=True, enforce_invertibility=True).fit()
        prediction = fitted.get_forecast(steps=HORIZON)
        mean = np.asarray(prediction.predicted_mean)
        interval = np.asarray(prediction.conf_int(alpha=0.05))
    assert fitted.mle_retvals.get("converged", False), name
    assert np.isfinite(mean).all() and np.isfinite(interval).all()
    assert (interval[:, 0] <= mean).all() and (mean <= interval[:, 1]).all()
    return mean, interval, dict(zip(fitted.param_names, map(float, fitted.params))), [
        str(item.message) for item in recorded]


def mae(truth, predicted):
    return float(np.mean(np.abs(np.asarray(truth) - np.asarray(predicted))))


def numbers(values):
    return np.round(np.asarray(values), 8).tolist()


def main():
    validation = []
    for origin in (60, 72):
        history = SERIES[:origin]
        truth = SERIES[origin:origin + HORIZON]
        assert len(history) == origin and len(truth) == HORIZON
        for name in CANDIDATES:
            predicted, _, parameters, messages = forecast(history, name)
            validation.append({"origin": origin, "training_indices": [0, origin - 1],
                "forecast_indices": [origin, origin + HORIZON - 1], "model": name,
                "forecast": numbers(predicted), "truth": numbers(truth),
                "MAE": mae(truth, predicted), "parameters": parameters,
                "warnings": messages})
    scores = {name: float(np.mean([r["MAE"] for r in validation if r["model"] == name]))
              for name in CANDIDATES}
    selected = min(CANDIDATES, key=lambda name: (scores[name], CANDIDATES.index(name)))
    # Freeze the selection before evaluating any final-block errors.
    final_origin = 84
    final = []
    for name in CANDIDATES:
        predicted, interval, parameters, messages = forecast(SERIES[:final_origin], name)
        truth = SERIES[final_origin:final_origin + HORIZON]
        row = {"model": name, "selected_using_validation_only": name == selected,
            "training_indices": [0, final_origin - 1], "forecast_indices": [84, 95],
            "forecast": numbers(predicted), "truth": numbers(truth),
            "MAE": mae(truth, predicted), "parameters": parameters, "warnings": messages}
        if interval is not None:
            row["model_based_95_percent_prediction_interval"] = numbers(interval)
            row["interval_scope"] = (
                "Conditional on this fitted ARIMA specification and estimated parameters; "
                "not simultaneous coverage, a confidence band for the mean, or validated "
                "95% real-world coverage on this deterministic teaching signal.")
        final.append(row)
    first_difference = np.diff(SERIES[:60])
    seasonal_difference = np.asarray(SERIES[12:60]) - np.asarray(SERIES[:48])
    print(json.dumps({"scope": "Hand-set deterministic 96-point series; actual ARIMA fitting, "
        "two-origin fixed-horizon validation, then one untouched final block. No RNG, "
        "external dataset, hyperparameter search, or claim of general model superiority.",
        "versions": {"python": platform.python_version(), "numpy": np.__version__,
            "pandas": pd.__version__, "scipy": scipy.__version__,
            "statsmodels": statsmodels.__version__},
        "series": numbers(SERIES), "period": PERIOD, "horizon": HORIZON,
        "ordinary_first_differences_first_12": numbers(first_difference[:12]),
        "seasonal_lag12_differences_first_12": numbers(seasonal_difference[:12]),
        "validation": validation, "mean_validation_MAE": scores,
        "selected_before_final_evaluation": selected, "final_block": final,
        "limits": ["The final block is evaluated once and never used for model selection.",
            "Each forecast block is predicted entirely from its origin; no rolling test updates.",
            "Overlapping training histories mean validation folds are not independent samples.",
            "Period and candidate orders were fixed as part of this teaching design.",
            "Residual diagnostics, structural changes, calibrated intervals and external validation "
            "would be needed for a real application."]}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
