use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use crate::error::{DatasetError, Result};
use crate::config::{DatasetConfig, PeriodKind};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Period {
pub year: i64,
pub month: u8,
pub index: u8,
}
#[must_use]
pub fn period_key(p: Period) -> String {
format!("{}.{:02}.{}", p.year, p.month, p.index)
}
pub fn period_of(date: &str, per: u8) -> Result<Period> {
if per != 3 && per != 6 {
return Err(DatasetError::data(format!(
"only pentad and dekad datasets are supported, not {per} periods a month"
)));
}
let mut parts = date.split('-');
let year = parts
.next()
.and_then(|part| part.parse::<i64>().ok())
.ok_or_else(|| DatasetError::data(format!("not a YYYY-MM-DD date: {date}")))?;
let month = parts
.next()
.and_then(|part| part.parse::<u8>().ok())
.ok_or_else(|| DatasetError::data(format!("not a YYYY-MM-DD date: {date}")))?;
let day = parts
.next()
.and_then(|part| part.parse::<u32>().ok())
.ok_or_else(|| DatasetError::data(format!("not a YYYY-MM-DD date: {date}")))?;
if parts.next().is_some() {
return Err(DatasetError::data(format!("not a YYYY-MM-DD date: {date}")));
}
let span = u32::from(30 / per);
let index = u32::from(per).min(day.div_ceil(span)).max(1);
Ok(Period {
year,
month,
index: u8::try_from(index).unwrap_or(per),
})
}
#[must_use]
pub fn next_period(p: Period, per: u8) -> Period {
if p.index < per {
return Period {
index: p.index + 1,
..p
};
}
if p.month < 12 {
return Period {
month: p.month + 1,
index: 1,
..p
};
}
Period {
year: p.year + 1,
month: 1,
index: 1,
}
}
#[must_use]
pub fn previous_period(p: Period, per: u8) -> Period {
if p.index > 1 {
return Period {
index: p.index - 1,
..p
};
}
if p.month > 1 {
return Period {
month: p.month - 1,
index: per,
..p
};
}
Period {
year: p.year - 1,
month: 12,
index: per,
}
}
#[must_use]
pub fn period_list(latest: Period, count: usize, per: u8) -> Vec<Period> {
let mut list = Vec::with_capacity(count);
let mut current = latest;
for _ in 0..count {
list.push(current);
current = previous_period(current, per);
}
list.reverse();
list
}
#[must_use]
pub fn period_end_iso(p: Period) -> String {
period_end_of(p, 6)
}
#[must_use]
pub fn period_end_of(p: Period, per: u8) -> String {
let span = u32::from(30 / per);
let day = if p.index < per {
u32::from(p.index) * span
} else {
days_in_month(p.year, p.month)
};
format!("{}-{:02}-{day:02}", p.year, p.month)
}
#[must_use]
fn days_in_month(year: i64, month: u8) -> u32 {
match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
_ => {
let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
if leap { 29 } else { 28 }
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RasterOnDisk {
pub period: Period,
pub status: &'static str,
pub file: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Piece {
Text(String),
Year,
Month,
Index,
}
fn template_pieces(template: &str, per: u8) -> Vec<Piece> {
let mut pieces = Vec::new();
let mut rest = template;
while !rest.is_empty() {
if let Some(after) = rest.strip_prefix("{year}") {
pieces.push(Piece::Year);
rest = after;
} else if let Some(after) = rest.strip_prefix("{month}") {
pieces.push(Piece::Month);
rest = after;
} else if let Some(after) = rest
.strip_prefix("{pentad}")
.or_else(|| rest.strip_prefix("{dekad}"))
{
pieces.push(Piece::Index);
rest = after;
} else {
let next = rest.find('{').unwrap_or(rest.len());
pieces.push(Piece::Text(rest[..next].to_owned()));
rest = &rest[next..];
if next == 0 {
let close = rest.find('}').map_or(rest.len(), |at| at + 1);
pieces.push(Piece::Text(rest[..close].to_owned()));
rest = &rest[close..];
}
}
}
let _ = per;
pieces
}
fn match_pieces(pieces: &[Piece], name: &str, per: u8, found: &mut Period) -> bool {
let Some((piece, rest)) = pieces.split_first() else {
return name.is_empty();
};
match piece {
Piece::Text(text) => name
.strip_prefix(text.as_str())
.is_some_and(|tail| match_pieces(rest, tail, per, found)),
Piece::Year => {
if name.len() < 4 || !name.as_bytes()[..4].iter().all(u8::is_ascii_digit) {
return false;
}
let year = name[..4].parse::<i64>().unwrap_or_default();
let saved = *found;
found.year = year;
if match_pieces(rest, &name[4..], per, found) {
return true;
}
*found = saved;
false
}
Piece::Month => {
for digits in [2_usize, 1] {
if name.len() < digits {
continue;
}
let (head, tail) = name.split_at(digits);
if !head.bytes().all(|b| b.is_ascii_digit()) {
continue;
}
let Ok(month) = head.parse::<u8>() else {
continue;
};
let saved = *found;
found.month = month;
if match_pieces(rest, tail, per, found) {
return true;
}
*found = saved;
}
false
}
Piece::Index => {
let mut bytes = name.bytes();
let Some(first) = bytes.next() else {
return false;
};
if !first.is_ascii_digit() || first == b'0' || first - b'0' > per {
return false;
}
let saved = *found;
found.index = first - b'0';
if match_pieces(rest, &name[1..], per, found) {
return true;
}
*found = saved;
false
}
}
}
pub fn rasters_on_disk(
config: &DatasetConfig,
src: &Path,
) -> Result<BTreeMap<String, RasterOnDisk>> {
let per = config.period.periods_per_month();
let mut found = BTreeMap::new();
let dirs: [(&'static str, Option<&str>); 2] = [
("prelim", config.prelim_file_template.as_deref()),
("final", Some(config.file_template.as_str())),
];
for (status, template) in dirs {
let Some(template) = template else {
continue;
};
let pieces = template_pieces(template, per);
let Ok(entries) = fs::read_dir(src.join(status)) else {
continue;
};
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
let mut period = Period {
year: 0,
month: 0,
index: 0,
};
if !match_pieces(&pieces, &name, per, &mut period) {
continue;
}
if !(1..=12).contains(&period.month) {
continue;
}
if !entry.path().is_file() {
continue;
}
found.insert(
period_key(period),
RasterOnDisk {
period,
status,
file: format!("{status}/{name}"),
},
);
}
}
Ok(found)
}
pub fn missing_season(
config: &DatasetConfig,
src: &Path,
start: &str,
end: &str,
) -> Result<Vec<String>> {
let per: u8 = config.period.periods_per_month();
let on_disk = rasters_on_disk(config, src)?;
let mut missing = Vec::new();
let last = period_of(end, per)?;
let mut period = period_of(start, per)?;
while period <= last {
let key = period_key(period);
if !on_disk.contains_key(&key) {
missing.push(key);
}
let next = next_period(period, per);
if next <= period {
break;
}
period = next;
}
Ok(missing)
}
#[must_use]
pub fn periods_per_month(kind: PeriodKind) -> u8 {
kind.periods_per_month()
}
#[cfg(test)]
mod tests {
use super::*;
fn date_of(p: Period) -> String {
format!("{}-{:02}-{:02}", p.year, p.month, p.index)
}
#[test]
fn a_pentad_of_a_date_is_the_five_day_block() {
assert_eq!(
period_of("2026-11-20", 6).expect("pentad"),
Period {
year: 2026,
month: 11,
index: 4
}
);
assert_eq!(
period_of("2026-11-01", 6).expect("pentad"),
Period {
year: 2026,
month: 11,
index: 1
}
);
assert_eq!(
period_of("2026-11-30", 6).expect("pentad"),
Period {
year: 2026,
month: 11,
index: 6
}
);
assert_eq!(
period_of("2026-11-21", 3).expect("dekad"),
Period {
year: 2026,
month: 11,
index: 3
}
);
}
#[test]
fn a_period_after_the_last_one_of_december_is_january() {
assert_eq!(
next_period(
Period {
year: 2026,
month: 12,
index: 6
},
6
),
Period {
year: 2027,
month: 1,
index: 1
}
);
assert_eq!(
next_period(
Period {
year: 2026,
month: 11,
index: 2
},
6
),
Period {
year: 2026,
month: 11,
index: 3
}
);
}
#[test]
fn the_pentad_key_pads_the_month() {
assert_eq!(
period_key(Period {
year: 2026,
month: 6,
index: 2
}),
"2026.06.2"
);
}
#[test]
fn a_template_matches_its_five_day_files() {
let pieces = template_pieces("chirps-v3.0.{year}.{month}.{pentad}.cog", 6);
let mut found = Period {
year: 0,
month: 0,
index: 0,
};
assert!(match_pieces(
&pieces,
"chirps-v3.0.2026.11.4.cog",
6,
&mut found
));
assert_eq!(
found,
Period {
year: 2026,
month: 11,
index: 4
}
);
let mut found = Period {
year: 0,
month: 0,
index: 0,
};
assert!(match_pieces(
&pieces,
"chirps-v3.0.2026.1.1.cog",
6,
&mut found
));
assert_eq!(
found,
Period {
year: 2026,
month: 1,
index: 1
}
);
let mut found = Period {
year: 0,
month: 0,
index: 0,
};
assert!(!match_pieces(
&pieces,
"chirps-v3.0.2026.11.7.cog",
6,
&mut found
));
}
#[test]
fn the_season_of_a_null_period_names_what_the_source_lacks() {
let dir = tempfile::tempdir().expect("a temp dir");
let src = dir.path();
fs::create_dir_all(src.join("final")).expect("mkdir");
fs::write(src.join("final/chirps.2026.6.2.tif"), b"x").expect("write");
let config = DatasetConfig::from_json_str(
r##"{
"id": "rainfall", "name": "Rainfall", "unit": "mm", "period": "pentad",
"scale": 1.0, "offset": 0.0, "valid_min": 0.0, "valid_max": 1000.0,
"nodata": -9999.0, "crs_epsg": 4326,
"file_template": "chirps.{year}.{month}.{pentad}.tif",
"max_zoom": 6, "tile_size": 256, "season_start": "06-01",
"stale_after_days": 20, "attribution": "CHIRPS", "source_url": "https://example.com",
"licence": "CC0-1.0", "ramp": [{"value": 0.0, "color": "#ffffff"},
{"value": 100.0, "color": "#000000"}]
}"##,
)
.expect("config");
let missing = missing_season(&config, src, "2026-06-01", "2026-06-20").expect("season");
assert_eq!(
missing,
vec![
"2026.06.1".to_owned(),
"2026.06.3".to_owned(),
"2026.06.4".to_owned()
]
);
let _ = date_of;
}
}