"""Original synthetic teaching example: safe lag features and recursive forecasts.

Daily observations arrive without delay. Fixed-origin 14-day forecasts never
receive the intermediate actuals. A separately labelled one-step protocol does.
"""
import json
import platform

import numpy as np
import pandas as pd
import sklearn
from sklearn.ensemble import RandomForestRegressor


PERIOD = 7
HORIZON = 14
PATTERN = (-6, -3, 0, 2, 5, 11, 8)
DISTURBANCE = (-1, 0, 1, 0, -1)
SERIES = [50 + 0.1 * t + PATTERN[t % PERIOD] + DISTURBANCE[t % 5]
          for t in range(168)]
FEATURES = ["lag1", "lag7", "rolling7"] + [f"weekday{k}" for k in range(7)]
CANDIDATES = ("seasonal_naive", "random_forest")


def feature_table(history):
    """Row t predicts y[t]; every target-derived feature ends at t-1."""
    y = pd.Series(history, dtype=float)
    table = pd.DataFrame({"target": y, "lag1": y.shift(1),
                          "lag7": y.shift(7),
                          "rolling7": y.shift(1).rolling(7).mean()})
    for k in range(7):
        table[f"weekday{k}"] = (table.index % 7 == k).astype(int)
    return table.dropna()


def next_features(history):
    """History may contain previous predictions during recursive deployment."""
    t = len(history)
    assert t >= 7
    return [history[-1], history[-7], float(np.mean(history[-7:]))] + [
        int(t % 7 == k) for k in range(7)]


def fit_forest(history):
    table = feature_table(history)
    model = RandomForestRegressor(n_estimators=40, max_depth=6,
                                  min_samples_leaf=3, random_state=7, n_jobs=1)
    model.fit(table[FEATURES].to_numpy(), table["target"].to_numpy())
    return model


def forecast(history, name, model=None):
    """Only the observed prefix is supplied; recursively append own predictions."""
    prefix = list(history)
    if name == "seasonal_naive":
        return [prefix[-PERIOD + h % PERIOD] for h in range(HORIZON)]
    assert name == "random_forest" and model is not None
    predicted = []
    for _ in range(HORIZON):
        value = float(model.predict([next_features(prefix)])[0])
        predicted.append(value)
        prefix.append(value)
    return predicted


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


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


def main():
    validation = []
    for origin in (126, 140):
        history = SERIES[:origin]
        model = fit_forest(history)
        for name in CANDIDATES:
            predicted = forecast(history, name, model)
            validation.append({"origin": origin, "training_target_indices": [7, origin - 1],
                "forecast_indices": [origin, origin + HORIZON - 1], "model": name,
                "prediction": rounded(predicted), "truth": rounded(SERIES[origin:origin + HORIZON]),
                "MAE": mae(SERIES[origin:origin + HORIZON], predicted)})
    scores = {name: float(np.mean([row["MAE"] for row in validation
                                  if row["model"] == name])) for name in CANDIDATES}
    selected = min(CANDIDATES, key=lambda name: (scores[name], CANDIDATES.index(name)))
    # Freeze selection before reading final-block errors.
    origin = 154
    model = fit_forest(SERIES[:origin])
    final = []
    for name in CANDIDATES:
        prediction = forecast(SERIES[:origin], name, model)
        final.append({"model": name, "selected_using_validation_only": name == selected,
            "prediction": rounded(prediction), "truth": rounded(SERIES[origin:]),
            "MAE": mae(SERIES[origin:], prediction)})

    # Different information contract: true past is revealed before each next day.
    # Same already-fitted forest, no refits; this is not a fixed-origin result.
    one_step = [float(model.predict([next_features(SERIES[:t])])[0])
                for t in range(origin, len(SERIES))]

    table = feature_table(SERIES[:origin])
    alignment_error = max(abs(a - b) for t in table.index
                          for a, b in zip(table.loc[t, FEATURES], next_features(SERIES[:t])))
    assert alignment_error < 1e-12
    # Perturb y[10] itself: correctly shifted features for target 10 stay fixed;
    # the unshifted rolling mean includes the unavailable target and changes.
    changed = SERIES.copy()
    changed[10] += 70
    safe = feature_table(SERIES).loc[10, FEATURES].to_numpy()
    safe_changed = feature_table(changed).loc[10, FEATURES].to_numpy()
    assert np.array_equal(safe, safe_changed)
    unsafe_delta = float(pd.Series(changed).rolling(7).mean()[10]
                         - pd.Series(SERIES).rolling(7).mean()[10])
    assert abs(unsafe_delta - 10) < 1e-12
    print(json.dumps({"scope": "Hand-set 168-point daily teaching signal; actual fitted forest, "
        "not an external benchmark. Calendar known, observations available without delay.",
        "versions": {"python": platform.python_version(), "numpy": np.__version__,
            "pandas": pd.__version__, "sklearn": sklearn.__version__},
        "series": rounded(SERIES), "features": FEATURES,
        "first_three_training_rows": table.head(3).reset_index(names="target_index").to_dict("records"),
        "feature_alignment_max_error": alignment_error,
        "target_perturbation_check": {"index": 10, "target_increase": 70,
            "shifted_features_unchanged": True, "unshifted_rolling_mean_change": unsafe_delta},
        "validation": validation, "mean_validation_MAE": scores,
        "selected_before_final_evaluation": selected,
        "final_fixed_origin": {"origin": origin, "training_target_indices": [7, 153],
            "forecast_indices": [154, 167], "horizon": HORIZON, "results": final},
        "different_one_step_observed_history_protocol": {
            "refit": False, "predictions": rounded(one_step), "MAE": mae(SERIES[origin:], one_step),
            "scope": "Each prediction gets actual observations through t-1. "
                     "Not available to the fixed-origin 14-day forecast; not a rival model score."},
        "limits": ["The pattern, candidate hyperparameters and folds were fixed for teaching.",
            "Validation training prefixes overlap; folds are not independent samples.",
            "No random-split comparison, prediction intervals or general model ranking.",
            "Tree forecasts can fail under extrapolation or distribution shift.",
            "Real panels require grouping; delayed values require availability-time handling."]},
        ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
