"""Run after generate_example.py; requires pandas, torch and timestral.

The first call downloads model weights. TIMESTRAL_MODEL can select a smaller
checkpoint, for example mistralai/Timestral-5M, when testing the workflow.
"""
import os
import numpy as np
import pandas as pd
import torch
from timestral import TimestralForecaster

origin = pd.Timestamp("2026-10-20")
data = pd.read_csv("demand.csv", parse_dates=["ds"])
train = data.loc[data.ds < origin]
future = data.loc[data.ds >= origin]
features = [
    "promotion", "school_vacation", "public_holiday", "is_closed",
    "hour_sin", "hour_cos", "week_sin", "week_cos", "year_sin", "year_cos",
]
# Calendar features are generated from dates and plans, never future y.
context = train.y.to_numpy(dtype=np.float32)[None, None, :]
known = data[features].to_numpy(dtype=np.float32).T[None, :, :]
assert context.shape[-1] <= 32768
assert known.shape[-1] == context.shape[-1] + len(future)
model = TimestralForecaster.from_pretrained(
    os.environ.get("TIMESTRAL_MODEL", "mistralai/Timestral-209M"),
    device="cuda" if torch.cuda.is_available() else "cpu",
)
forecast = model.forecast(
    context, prediction_length=len(future), known_covariates=known,
)

def values(tensor):
    return tensor.detach().cpu().numpy()[0, 0]

result = pd.DataFrame({
    "ds": future.ds.to_numpy(), "prediction": values(forecast.median),
    "lower": values(forecast.quantile(0.1)),
    "upper": values(forecast.quantile(0.9)),
})
result.loc[future.is_closed.to_numpy().astype(bool), ["prediction", "lower", "upper"]] = 0
result.to_csv("timestral_forecast.csv", index=False)
print("Saved timestral_forecast.csv; prediction is the median, not the mean.")
