use reqwest::Url;
use time::{Date, PrimitiveDateTime};
use super::url::{
QueryParam, build_endpoint_url, push_api_param, push_api_values, push_display_param,
push_float_param,
};
use super::validation::{
format_hour, is_non_zero_u8, is_non_zero_u16, validate_at_most, validate_coordinates,
validate_fixed_range_windows,
};
use crate::response::decode_forecast_json;
use crate::units::{
CellSelection, PrecipitationUnit, TemperatureUnit, TimeFormat, Timezone, WindSpeedUnit,
};
use crate::variables::{DailyVar, EnsembleModel, HourlyVar};
use crate::{Client, EnsembleResponse, Error, Result};
const MAX_FORECAST_DAYS: u8 = 35;
const MAX_PAST_DAYS: u8 = 92;
const MAX_FORECAST_HOURS: u16 = 35 * 24;
#[derive(Debug)]
#[must_use = "ensemble builders do nothing until `.send().await` is called"]
pub struct EnsembleBuilder<'a> {
client: &'a Client,
latitude: f64,
longitude: f64,
hourly: Vec<HourlyVar>,
daily: Vec<DailyVar>,
models: Vec<EnsembleModel>,
temperature_unit: Option<TemperatureUnit>,
wind_speed_unit: Option<WindSpeedUnit>,
precipitation_unit: Option<PrecipitationUnit>,
timeformat: Option<TimeFormat>,
timezone: Option<Timezone>,
past_days: Option<u8>,
forecast_days: Option<u8>,
past_hours: Option<u16>,
forecast_hours: Option<u16>,
date_range: Option<(Date, Date)>,
hour_range: Option<(PrimitiveDateTime, PrimitiveDateTime)>,
cell_selection: Option<CellSelection>,
elevation: Option<f64>,
}
impl<'a> EnsembleBuilder<'a> {
pub(crate) fn new(client: &'a Client, latitude: f64, longitude: f64) -> Self {
Self {
client,
latitude,
longitude,
hourly: Vec::new(),
daily: Vec::new(),
models: Vec::new(),
temperature_unit: None,
wind_speed_unit: None,
precipitation_unit: None,
timeformat: None,
timezone: None,
past_days: None,
forecast_days: None,
past_hours: None,
forecast_hours: None,
date_range: None,
hour_range: None,
cell_selection: None,
elevation: None,
}
}
pub fn hourly<I>(mut self, variables: I) -> Self
where
I: IntoIterator<Item = HourlyVar>,
{
self.hourly.extend(variables);
self
}
pub fn daily<I>(mut self, variables: I) -> Self
where
I: IntoIterator<Item = DailyVar>,
{
self.daily.extend(variables);
self
}
pub fn models<I>(mut self, models: I) -> Self
where
I: IntoIterator<Item = EnsembleModel>,
{
self.models.extend(models);
self
}
pub fn temperature_unit(mut self, unit: TemperatureUnit) -> Self {
self.temperature_unit = Some(unit);
self
}
pub fn wind_speed_unit(mut self, unit: WindSpeedUnit) -> Self {
self.wind_speed_unit = Some(unit);
self
}
pub fn precipitation_unit(mut self, unit: PrecipitationUnit) -> Self {
self.precipitation_unit = Some(unit);
self
}
pub fn timeformat(mut self, format: TimeFormat) -> Self {
self.timeformat = Some(format);
self
}
pub fn timezone(mut self, timezone: Timezone) -> Self {
self.timezone = Some(timezone);
self
}
pub fn past_days(mut self, days: u8) -> Self {
self.past_days = Some(days);
self
}
pub fn forecast_days(mut self, days: u8) -> Self {
self.forecast_days = Some(days);
self
}
pub fn past_hours(mut self, hours: u16) -> Self {
self.past_hours = Some(hours);
self
}
pub fn forecast_hours(mut self, hours: u16) -> Self {
self.forecast_hours = Some(hours);
self
}
pub fn date_range(mut self, start: Date, end: Date) -> Self {
self.date_range = Some((start, end));
self
}
pub fn hour_range(mut self, start: PrimitiveDateTime, end: PrimitiveDateTime) -> Self {
self.hour_range = Some((start, end));
self
}
pub fn cell_selection(mut self, selection: CellSelection) -> Self {
self.cell_selection = Some(selection);
self
}
pub fn elevation(mut self, meters: f64) -> Self {
self.elevation = Some(meters);
self
}
pub async fn send(self) -> Result<EnsembleResponse> {
let url = self.build_url()?;
let body = self.client.execute(self.client.http.get(url)).await?;
decode_forecast_json(&body)
}
pub(crate) fn build_url(&self) -> Result<Url> {
self.validate()?;
let mut params: Vec<QueryParam> = vec![
("latitude", self.latitude.to_string()),
("longitude", self.longitude.to_string()),
];
push_api_values(&mut params, "hourly", &self.hourly);
push_api_values(&mut params, "daily", &self.daily);
push_api_values(&mut params, "models", &self.models);
push_api_param(
&mut params,
"temperature_unit",
self.temperature_unit.as_ref(),
);
push_api_param(
&mut params,
"wind_speed_unit",
self.wind_speed_unit.as_ref(),
);
push_api_param(
&mut params,
"precipitation_unit",
self.precipitation_unit.as_ref(),
);
push_api_param(&mut params, "timeformat", self.timeformat.as_ref());
push_api_param(&mut params, "timezone", self.timezone.as_ref());
push_display_param(
&mut params,
"past_days",
self.past_days.filter(|days| *days > 0),
);
push_display_param(&mut params, "forecast_days", self.forecast_days);
push_display_param(
&mut params,
"past_hours",
self.past_hours.filter(|hours| *hours > 0),
);
push_display_param(
&mut params,
"forecast_hours",
self.forecast_hours.filter(|hours| *hours > 0),
);
if let Some((start, end)) = self.date_range {
params.push(("start_date", start.to_string()));
params.push(("end_date", end.to_string()));
}
if let Some((start, end)) = self.hour_range {
params.push(("start_hour", format_hour(start)?));
params.push(("end_hour", format_hour(end)?));
}
push_api_param(&mut params, "cell_selection", self.cell_selection.as_ref());
push_float_param(&mut params, "elevation", self.elevation);
build_endpoint_url(
&self.client.ensemble_base,
"ensemble_base_url",
"v1/ensemble",
self.client.api_key.as_deref(),
params,
)
}
fn validate(&self) -> Result<()> {
validate_coordinates(self.latitude, self.longitude)?;
if self.hourly.is_empty() && self.daily.is_empty() {
return Err(Error::InvalidParam {
field: "variables",
reason: "set at least one hourly or daily variable".into(),
});
}
if self.models.is_empty() {
return Err(Error::InvalidParam {
field: "models",
reason: "set at least one ensemble model".into(),
});
}
validate_at_most("past_days", self.past_days, MAX_PAST_DAYS)?;
validate_at_most("forecast_days", self.forecast_days, MAX_FORECAST_DAYS)?;
validate_at_most("forecast_hours", self.forecast_hours, MAX_FORECAST_HOURS)?;
self.validate_hourly_variables()?;
validate_fixed_range_windows(
self.date_range,
self.hour_range,
&[
("past_days", is_non_zero_u8(self.past_days)),
("forecast_days", self.forecast_days.is_some()),
("past_hours", is_non_zero_u16(self.past_hours)),
("forecast_hours", is_non_zero_u16(self.forecast_hours)),
],
)
}
fn validate_hourly_variables(&self) -> Result<()> {
for var in &self.hourly {
var.validate_weather_request()?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{EnsembleModel, HourlyVar, TemperatureUnit, Timezone};
use time::macros::{date, datetime};
#[test]
fn build_ensemble_url_with_hourly_variables() {
let client = Client::builder()
.ensemble_base_url("https://example.com/ensemble?token=abc")
.unwrap()
.build()
.unwrap();
let url = client
.ensemble(47.3769, 8.5417)
.hourly([HourlyVar::Temperature2m])
.models([EnsembleModel::IconSeamlessEps])
.timezone(Timezone::Iana("Europe/Zurich".to_owned()))
.temperature_unit(TemperatureUnit::Fahrenheit)
.forecast_hours(1)
.build_url()
.unwrap();
assert_eq!(
url.as_str(),
"https://example.com/ensemble/v1/ensemble?token=abc&latitude=47.3769&longitude=8.5417&hourly=temperature_2m&models=icon_seamless_eps&temperature_unit=fahrenheit&timezone=Europe%2FZurich&forecast_hours=1"
);
}
#[test]
fn build_ensemble_url_with_date_and_hour_ranges() {
let client = Client::builder()
.ensemble_base_url("https://example.com")
.unwrap()
.build()
.unwrap();
let date_url = client
.ensemble(47.3769, 8.5417)
.hourly([HourlyVar::Temperature2m])
.models([EnsembleModel::IconSeamlessEps])
.date_range(date!(2026 - 05 - 01), date!(2026 - 05 - 02))
.build_url()
.unwrap();
assert!(date_url.as_str().contains("start_date=2026-05-01"));
assert!(date_url.as_str().contains("end_date=2026-05-02"));
let hour_url = client
.ensemble(47.3769, 8.5417)
.hourly([HourlyVar::Temperature2m])
.models([EnsembleModel::IconSeamlessEps])
.hour_range(datetime!(2026-05-01 00:00), datetime!(2026-05-01 01:00))
.build_url()
.unwrap();
assert!(hour_url.as_str().contains("start_hour=2026-05-01T00%3A00"));
assert!(hour_url.as_str().contains("end_hour=2026-05-01T01%3A00"));
}
#[test]
fn rejects_empty_ensemble_variable_set() {
let client = Client::new();
let err = client
.ensemble(47.3769, 8.5417)
.models([EnsembleModel::IconSeamlessEps])
.build_url()
.unwrap_err();
assert!(matches!(
err,
Error::InvalidParam {
field: "variables",
..
}
));
}
#[test]
fn rejects_missing_ensemble_models() {
let client = Client::new();
let err = client
.ensemble(47.3769, 8.5417)
.hourly([HourlyVar::Temperature2m])
.build_url()
.unwrap_err();
assert!(matches!(
err,
Error::InvalidParam {
field: "models",
..
}
));
}
#[test]
fn rejects_ensemble_date_range_with_relative_window() {
let client = Client::new();
let err = client
.ensemble(47.3769, 8.5417)
.hourly([HourlyVar::Temperature2m])
.models([EnsembleModel::IconSeamlessEps])
.forecast_hours(1)
.date_range(date!(2026 - 05 - 01), date!(2026 - 05 - 02))
.build_url()
.unwrap_err();
assert!(matches!(
err,
Error::MutuallyExclusive {
first: "date_range",
second: "forecast_hours",
}
));
}
}