use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use anyhow::{Context, bail};
use serde::{Deserialize, Serialize};
use crate::config::PeriodKind;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Period {
pub year: i32,
pub month: u8,
pub index: u8,
#[serde(skip)]
pub kind: PeriodKind,
}
impl Period {
#[must_use]
pub const fn start(&self) -> (i32, u8, u8) {
(
self.year,
self.month,
self.index
.saturating_sub(1)
.saturating_mul(self.length())
.saturating_add(1),
)
}
const fn length(&self) -> u8 {
match self.kind {
PeriodKind::Pentad => 5,
PeriodKind::Dekad => 10,
}
}
#[must_use]
pub const fn end(&self) -> (i32, u8, u8) {
let day = if self.index >= self.kind.periods_per_month() {
days_in_month(self.year, self.month)
} else {
self.length().saturating_mul(self.index)
};
(self.year, self.month, day)
}
#[must_use]
pub fn days(&self) -> u8 {
self.end()
.2
.saturating_sub(self.start().2)
.saturating_add(1)
}
#[must_use]
pub fn start_iso(&self) -> String {
let (y, m, d) = self.start();
format!("{y:04}-{m:02}-{d:02}")
}
#[must_use]
pub fn end_iso(&self) -> String {
let (y, m, d) = self.end();
format!("{y:04}-{m:02}-{d:02}")
}
#[must_use]
pub fn slot(&self) -> String {
format!("{:02}-{}", self.month, self.index)
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Status {
Final,
Prelim,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RasterFile {
pub period: Period,
pub status: Status,
pub path: PathBuf,
}
#[must_use]
pub fn match_template(template: &str, file_name: &str) -> Option<Period> {
let mut fields = Fields::default();
if !match_from(template.as_bytes(), file_name.as_bytes(), &mut fields) {
return None;
}
let (index, kind) = match (fields.pentad, fields.dekad) {
(Some(index), None) => (index, PeriodKind::Pentad),
(None, Some(index)) => (index, PeriodKind::Dekad),
_ => return None,
};
Some(Period {
year: fields.year?,
month: fields.month?,
index,
kind,
})
}
#[derive(Debug, Clone, Copy, Default)]
struct Fields {
year: Option<i32>,
month: Option<u8>,
pentad: Option<u8>,
dekad: Option<u8>,
}
fn match_from(template: &[u8], name: &[u8], fields: &mut Fields) -> bool {
let placeholders: [(&[u8], usize, usize); 4] = [
(b"{year}", 4, 4),
(b"{month}", 1, 2),
(b"{pentad}", 1, 1),
(b"{dekad}", 1, 1),
];
for (token, min, max) in placeholders {
let Some(rest) = template.strip_prefix(token) else {
continue;
};
for width in min..=max.min(name.len()) {
let (digits, tail) = name.split_at(width);
let Some(value) = parse_digits(digits) else {
continue;
};
let mut next = *fields;
let valid = match token {
b"{year}" => {
next.year = i32::try_from(value).ok();
true
}
b"{month}" => {
next.month = u8::try_from(value).ok();
(1..=12).contains(&value)
}
b"{dekad}" => {
next.dekad = u8::try_from(value).ok();
(1..=3).contains(&value)
}
_ => {
next.pentad = u8::try_from(value).ok();
(1..=6).contains(&value)
}
};
if valid && match_from(rest, tail, &mut next) {
*fields = next;
return true;
}
}
return false;
}
match (template.split_first(), name.split_first()) {
(None, None) => true,
(Some((t, trest)), Some((n, nrest))) if t == n => match_from(trest, nrest, fields),
_ => false,
}
}
fn parse_digits(digits: &[u8]) -> Option<u32> {
digits.iter().try_fold(0u32, |acc, &b| {
b.is_ascii_digit().then(|| acc * 10 + u32::from(b - b'0'))
})
}
pub fn discover(
dir: &Path,
final_template: &str,
prelim_template: &str,
) -> anyhow::Result<Vec<RasterFile>> {
let mut best: BTreeMap<Period, RasterFile> = BTreeMap::new();
let mut seen: HashMap<(Period, Status), PathBuf> = HashMap::new();
for (sub, status, template) in [
("final", Status::Final, final_template),
("prelim", Status::Prelim, prelim_template),
] {
let folder = dir.join(sub);
let entries = match fs::read_dir(&folder) {
Ok(entries) => entries,
Err(e) if e.kind() == ErrorKind::NotFound => continue,
Err(e) => {
return Err(e).with_context(|| format!("listing {}", folder.display()));
}
};
let mut paths = entries
.map(|entry| entry.map(|e| e.path()))
.collect::<Result<Vec<_>, _>>()
.with_context(|| format!("listing {}", folder.display()))?;
paths.sort();
for path in paths {
let period = path
.file_name()
.and_then(|n| n.to_str())
.and_then(|n| match_template(template, n));
let Some(period) = period else {
tracing::debug!(path = %path.display(), "skipping file that does not match the template");
continue;
};
if !path.is_file() {
tracing::debug!(path = %path.display(), "skipping entry that is not a regular file");
continue;
}
if let Some(first) = seen.insert((period, status), path.clone()) {
bail!(
"{} and {} both hold period {}",
first.display(),
path.display(),
period.start_iso()
);
}
best.entry(period).or_insert(RasterFile {
period,
status,
path,
});
}
}
Ok(best.into_values().collect())
}
#[must_use]
pub fn utc_compact(unix_secs: i64) -> String {
let (y, mo, d, h, mi, _) = civil_utc(unix_secs);
format!("{y:04}{mo:02}{d:02}T{h:02}{mi:02}Z")
}
#[must_use]
pub fn utc_iso(unix_secs: i64) -> String {
let (y, mo, d, h, mi, s) = civil_utc(unix_secs);
format!("{y:04}-{mo:02}-{d:02}T{h:02}:{mi:02}:{s:02}Z")
}
#[must_use]
pub fn date_plus_days(day: (i32, u8, u8), days: u16) -> String {
let (year, month, day) = day;
let (y, m, d) = civil_from_days(days_from_civil(year, month, day) + i64::from(days));
format!("{y:04}-{m:02}-{d:02}")
}
fn days_from_civil(year: i32, month: u8, day: u8) -> i64 {
let (month, day) = (i64::from(month), i64::from(day));
let year = i64::from(year) - i64::from(month <= 2);
let era = year.div_euclid(400);
let yoe = year.rem_euclid(400);
let mp = (month + 9) % 12;
let doy = (153 * mp + 2) / 5 + day - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
}
fn civil_utc(unix_secs: i64) -> (i64, i64, i64, i64, i64, i64) {
let days = unix_secs.div_euclid(86_400);
let secs = unix_secs.rem_euclid(86_400);
let (y, m, d) = civil_from_days(days);
(y, m, d, secs / 3600, secs % 3600 / 60, secs % 60)
}
fn civil_from_days(days: i64) -> (i64, i64, i64) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + i64::from(month <= 2);
(year, month, day)
}
const fn days_in_month(year: i32, month: u8) -> u8 {
match month {
2 if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 => 29,
2 => 28,
4 | 6 | 9 | 11 => 30,
_ => 31,
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
const TEMPLATE: &str = "chirps-v3.0.{year}.{month}.{pentad}.tif";
fn period(year: i32, month: u8, index: u8) -> Period {
Period {
year,
month,
index,
kind: PeriodKind::Pentad,
}
}
fn dekad(year: i32, month: u8, index: u8) -> Period {
Period {
year,
month,
index,
kind: PeriodKind::Dekad,
}
}
#[test]
fn a_dekad_runs_to_the_month_end() {
let leap_third = dekad(2024, 2, 3);
assert_eq!(leap_third.start(), (2024, 2, 21));
assert_eq!(leap_third.end(), (2024, 2, 29));
assert_eq!(leap_third.days(), 9);
let first = dekad(2024, 2, 1);
assert_eq!((first.start().2, first.end().2, first.days()), (1, 10, 10));
let second = dekad(2026, 11, 2);
assert_eq!(second.start_iso(), "2026-11-11");
assert_eq!(second.end_iso(), "2026-11-20");
assert_eq!(second.slot(), "11-2");
assert_eq!(dekad(2026, 7, 3).end_iso(), "2026-07-31");
}
#[test]
fn a_template_with_both_period_tokens_matches_nothing() {
assert_eq!(
match_template("n.{year}.{month}.{pentad}.{dekad}", "n.2026.1.2.3"),
None
);
}
fn touch(dir: &Path, sub: &str, name: &str) {
let folder = dir.join(sub);
fs::create_dir_all(&folder).unwrap();
fs::write(folder.join(name), b"x").unwrap();
}
#[test]
fn pentad_three_of_october_is_the_eleventh_to_the_fifteenth() {
let p = period(2026, 10, 3);
assert_eq!(p.start_iso(), "2026-10-11");
assert_eq!(p.end_iso(), "2026-10-15");
assert_eq!(p.slot(), "10-3");
}
#[test]
fn pentad_six_ends_on_the_last_day() {
for (year, month, last) in [
(2028, 2, "2028-02-29"),
(2026, 2, "2026-02-28"),
(2026, 7, "2026-07-31"),
(1900, 2, "1900-02-28"),
(2000, 2, "2000-02-29"),
] {
assert_eq!(period(year, month, 6).end_iso(), last);
}
}
#[test]
fn a_period_counts_its_days() {
for (year, month, index, days) in [
(2026, 10, 3, 5),
(2026, 2, 6, 3),
(2024, 2, 6, 4),
(1900, 2, 6, 3),
(2026, 11, 6, 5),
(2026, 1, 6, 6),
] {
assert_eq!(
period(year, month, index).days(),
days,
"{year}-{month} pentad {index}"
);
}
}
#[test]
fn the_template_matches_whole_names() {
assert_eq!(
match_template(TEMPLATE, "chirps-v3.0.2026.10.3.tif"),
Some(period(2026, 10, 3))
);
for name in [
"chirps-v3.0.2026.10.3.tif.part",
"chirps-v3.0.2026.13.3.tif",
"chirps-v3.0.2026.10.7.tif",
"x-chirps-v3.0.2026.10.3.tif",
] {
assert_eq!(match_template(TEMPLATE, name), None, "{name}");
}
}
#[test]
fn final_wins_over_prelim_for_the_same_period() {
let dir = tempfile::tempdir().unwrap();
touch(dir.path(), "final", "chirps-v3.0.2026.10.3.tif");
touch(dir.path(), "prelim", "chirps-v3.0.2026.10.3.tif");
touch(dir.path(), "prelim", "chirps-v3.0.2026.10.4.tif");
let files = discover(dir.path(), TEMPLATE, TEMPLATE).unwrap();
assert_eq!(files.len(), 2);
let third = files
.iter()
.find(|f| f.period == period(2026, 10, 3))
.unwrap();
assert_eq!(third.status, Status::Final);
assert!(third.path.to_string_lossy().contains("/final/"));
let fourth = files
.iter()
.find(|f| f.period == period(2026, 10, 4))
.unwrap();
assert_eq!(fourth.status, Status::Prelim);
}
#[test]
fn foreign_and_partial_files_are_skipped() {
let dir = tempfile::tempdir().unwrap();
touch(dir.path(), "final", "chirps-v3.0.2026.10.3.tif");
touch(dir.path(), "final", "README.txt");
touch(dir.path(), "prelim", "chirps-v3.0.2026.10.5.tif.part");
touch(dir.path(), "prelim", "chirps-v3.0.2026.10.5.tif.aria2");
let files = discover(dir.path(), TEMPLATE, TEMPLATE).unwrap();
assert!(files.iter().all(|f| f.period.slot() != "10-5"));
assert!(files.iter().any(|f| f.period == period(2026, 10, 3)));
}
#[test]
fn discovery_does_not_depend_on_creation_order() {
let dir = tempfile::tempdir().unwrap();
for (month, pentad) in [(12, 6), (11, 2), (10, 4), (10, 1), (1, 3)] {
touch(
dir.path(),
"prelim",
&format!("chirps-v3.0.2026.{month}.{pentad}.tif"),
);
}
touch(dir.path(), "final", "chirps-v3.0.2025.12.6.tif");
let files = discover(dir.path(), TEMPLATE, TEMPLATE).unwrap();
assert_eq!(files.len(), 6);
for pair in files.windows(2) {
assert!(pair[0].period < pair[1].period, "{:?}", pair);
}
}
#[test]
fn finals_and_prelims_use_their_own_templates() {
let final_template = "chirps-v3.0.{year}.{month}.{pentad}.cog";
let dir = tempfile::tempdir().unwrap();
touch(dir.path(), "final", "chirps-v3.0.2026.10.6.cog");
touch(dir.path(), "final", "chirps-v3.0.2026.10.5.tif");
touch(dir.path(), "prelim", "chirps-v3.0.2026.11.2.tif");
touch(dir.path(), "prelim", "chirps-v3.0.2026.11.1.cog");
let files = discover(dir.path(), final_template, TEMPLATE).unwrap();
let october = files
.iter()
.find(|f| f.period == period(2026, 10, 6))
.expect("the final .cog is found");
assert_eq!(october.status, Status::Final);
let november = files
.iter()
.find(|f| f.period == period(2026, 11, 2))
.expect("the prelim .tif is found");
assert_eq!(november.status, Status::Prelim);
assert!(
files
.iter()
.all(|f| f.period != period(2026, 10, 5) && f.period != period(2026, 11, 1)),
"a name matching only the other folder's template is skipped: {files:?}"
);
}
#[test]
fn a_directory_matching_the_template_is_skipped() {
let dir = tempfile::tempdir().unwrap();
fs::create_dir_all(dir.path().join("final/chirps-v3.0.2026.10.3.tif")).unwrap();
touch(dir.path(), "final", "chirps-v3.0.2026.10.4.tif");
let files = discover(dir.path(), TEMPLATE, TEMPLATE).unwrap();
assert!(
files.iter().all(|f| f.period != period(2026, 10, 3)),
"{files:?}"
);
let fourth = files
.iter()
.find(|f| f.period == period(2026, 10, 4))
.expect("the regular file is found");
assert!(fourth.path.is_file());
}
#[test]
fn two_names_for_one_period_fail_naming_both() {
let template = "chirps-v3.0.{year}.{month}.{pentad}.cog";
let dir = tempfile::tempdir().unwrap();
touch(dir.path(), "final", "chirps-v3.0.2026.1.3.cog");
touch(dir.path(), "final", "chirps-v3.0.2026.01.3.cog");
let err = discover(dir.path(), template, TEMPLATE).expect_err("two names, one period");
let text = format!("{err:#}");
assert!(text.contains("chirps-v3.0.2026.1.3.cog"), "{text}");
assert!(text.contains("chirps-v3.0.2026.01.3.cog"), "{text}");
}
#[test]
fn utc_formats_match_known_instants() {
assert_eq!(utc_compact(0), "19700101T0000Z");
assert_eq!(utc_compact(1_794_859_463), "20261116T2004Z");
assert_eq!(utc_iso(951_782_400), "2000-02-29T00:00:00Z");
}
#[test]
fn days_are_added_across_months_years_and_leap_days() {
assert_eq!(date_plus_days((2026, 11, 10), 18), "2026-11-28");
assert_eq!(date_plus_days((2026, 12, 31), 18), "2027-01-18");
assert_eq!(date_plus_days((2028, 2, 20), 18), "2028-03-09");
assert_eq!(date_plus_days((2027, 2, 20), 18), "2027-03-10");
assert_eq!(date_plus_days((2026, 6, 5), 0), "2026-06-05");
}
}