use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use crate::error::{
DatasetError, IoOp, IoResultExt as _, IoStepExt as _, NumberResultExt as _, Result,
};
use crate::cli::ListsArgs;
use crate::exit::Exit;
use crate::period::{Period, period_key, period_list};
const PENTADS_PER_YEAR: i64 = 72;
const PENTADS_PER_MONTH: i64 = 6;
const SERIES_LEN: usize = 12;
const FINAL: &str =
"/products/CHIRPS/v3.0/pentads/global/cogs/chirps-v3.0.{year}.{month}.{pentad}.cog";
const PRELIM: &str =
"/products/CHIRPS/v3.0/prelim/pentads/global/tifs/chirps-v3.0.{year}.{month}.{pentad}.tif";
fn listed(text: &str) -> BTreeMap<String, Period> {
let mut found = BTreeMap::new();
let bytes = text.as_bytes();
let needle = b"chirps-v3.0.";
let mut at = 0;
while let Some(offset) = find(&bytes[at..], needle) {
let start = at + offset + needle.len();
if let Some((period, end)) = name_at(text, start)
&& !bytes
.get(end)
.is_some_and(|byte| byte.is_ascii_alphanumeric() || *byte == b'_' || *byte == b'.')
{
found.insert(period_key(period), period);
}
at = start;
}
found
}
fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
haystack
.windows(needle.len())
.position(|window| window == needle)
}
fn name_at(text: &str, start: usize) -> Option<(Period, usize)> {
let bytes = text.as_bytes();
let year = digits(bytes, start, 4)?;
if bytes.get(start + 4).copied() != Some(b'.') {
return None;
}
let (month, after_month) = digits_upto(bytes, start + 5, 2)?;
if !(1..=12).contains(&month) || bytes.get(after_month).copied() != Some(b'.') {
return None;
}
let (index, after_index) = digits_upto(bytes, after_month + 1, 1)?;
if !(1..=6).contains(&index) || bytes.get(after_index).copied() != Some(b'.') {
return None;
}
let rest = &text[after_index + 1..];
if !(rest.starts_with("cog") || rest.starts_with("tif")) {
return None;
}
let end = after_index + 4;
Some((
Period {
year: i64::from(year),
month,
index,
},
end,
))
}
fn digits(bytes: &[u8], start: usize, width: usize) -> Option<u32> {
let slice = bytes.get(start..start + width)?;
if !slice.iter().all(u8::is_ascii_digit) {
return None;
}
std::str::from_utf8(slice).ok()?.parse().ok()
}
fn digits_upto(bytes: &[u8], start: usize, width: usize) -> Option<(u8, usize)> {
let mut end = start;
while end < bytes.len() && end - start < width && bytes[end].is_ascii_digit() {
end += 1;
}
if end == start {
return None;
}
let value = std::str::from_utf8(&bytes[start..end]).ok()?.parse().ok()?;
Some((value, end))
}
fn season_slot(text: &str) -> Result<(u8, u8)> {
let message = format!(
"season start must be MM-DD on a pentad start (day 1, 6, 11, 16, 21 or 26): {text}"
);
let bytes = text.as_bytes();
if bytes.len() != 5 || bytes[2] != b'-' {
return Err(DatasetError::data(message.to_string()));
}
let month = digits(bytes, 0, 2).ok_or_else(|| DatasetError::data("month"))?;
let day = digits(bytes, 3, 2).ok_or_else(|| DatasetError::data("day"))?;
if !(1..=12).contains(&month) || !(1..=26).contains(&day) || (day - 1) % 5 != 0 {
return Err(DatasetError::data(message.to_string()));
}
Ok((
u8::try_from(month).unwrap_or_default(),
u8::try_from((day - 1) / 5 + 1).unwrap_or_default(),
))
}
fn fill(pattern: &str, p: Period) -> String {
let path = match pattern.split_once("://") {
Some((_, rest)) => rest.find('/').map_or(pattern, |slash| &rest[slash..]),
None => pattern,
};
path.replace("{year}", &p.year.to_string())
.replace("{month}", &format!("{:02}", p.month))
.replace("{pentad}", &p.index.to_string())
}
fn chirps_lines(periods: &[Period], finals: &BTreeMap<String, Period>) -> Vec<String> {
periods
.iter()
.map(|p| {
let key = period_key(*p);
if finals.contains_key(&key) {
format!("final {}", fill(FINAL, *p))
} else {
format!("prelim {}", fill(PRELIM, *p))
}
})
.collect()
}
fn baseline_lines(from: i64, to: i64) -> Vec<String> {
let mut lines = Vec::new();
for year in from..=to {
for month in 1..=12_u8 {
for index in 1..=6_u8 {
lines.push(format!(
"final {}",
fill(FINAL, Period { year, month, index })
));
}
}
}
lines
}
pub fn write_lists(
listing_final: &Path,
listing_prelim: &Path,
season_start: &str,
baseline: &str,
out: &Path,
) -> Result<Period> {
write_lists_to(
&mut std::io::stdout(),
listing_final,
listing_prelim,
season_start,
baseline,
out,
)
}
pub fn write_lists_quiet(
listing_final: &Path,
listing_prelim: &Path,
season_start: &str,
baseline: &str,
out: &Path,
) -> Result<Period> {
write_lists_to(
&mut std::io::sink(),
listing_final,
listing_prelim,
season_start,
baseline,
out,
)
}
pub fn write_lists_to<W: std::io::Write + ?Sized>(
out: &mut W,
listing_final: &Path,
listing_prelim: &Path,
season_start: &str,
baseline: &str,
out_dir: &Path,
) -> Result<Period> {
let finals = listed(&fs::read_to_string(listing_final).io_at(IoOp::Read, listing_final)?);
let prelims = listed(&fs::read_to_string(listing_prelim).io_at(IoOp::Read, listing_prelim)?);
let latest = finals
.values()
.chain(prelims.values())
.max()
.copied()
.ok_or_else(|| {
DatasetError::data({
format!(
"no CHIRPS pentad names in {} or {}",
listing_final.display(),
listing_prelim.display()
)
})
})?;
let (month, index) = season_slot(season_start)?;
let start = Period {
year: latest.year,
month,
index,
};
let season_year = if start <= latest {
latest.year
} else {
latest.year - 1
};
let season_count = (latest.year - season_year) * PENTADS_PER_YEAR
+ (i64::from(latest.month) - i64::from(month)) * PENTADS_PER_MONTH
+ (i64::from(latest.index) - i64::from(index))
+ 1;
let season_count = usize::try_from(season_count.max(0)).number_of("season length")?;
let series = period_list(latest, SERIES_LEN, 6);
let season = period_list(latest, season_count, 6);
for period in series.iter().chain(season.iter()) {
let key = period_key(*period);
if !finals.contains_key(&key) && !prelims.contains_key(&key) {
eprintln!("not on the host: {key}");
}
}
let years: Vec<&str> = baseline.split('-').collect();
let (Ok(from), Ok(to)) = (
years.first().copied().unwrap_or_default().parse::<i64>(),
years.get(1).copied().unwrap_or_default().parse::<i64>(),
) else {
return Err(DatasetError::data(format!(
"baseline must be YYYY-YYYY: {baseline}"
)));
};
if from > to {
return Err(DatasetError::data(format!(
"baseline must be YYYY-YYYY: {baseline}"
)));
}
fs::create_dir_all(out_dir).io_at(IoOp::Create, out_dir)?;
for (name, lines) in [
("series.txt", chirps_lines(&series, &finals)),
("season.txt", chirps_lines(&season, &finals)),
("baseline.txt", baseline_lines(from, to)),
] {
let path = out_dir.join(name);
fs::write(&path, format!("{}\n", lines.join("\n"))).io_at(IoOp::Write, &path)?;
writeln!(out, "{name} {} lines", lines.len()).io_step("writing the lists report")?;
}
writeln!(out, "latest {}", period_key(latest)).io_step("writing the lists report")?;
Ok(latest)
}
pub fn run(args: &ListsArgs) -> Result<()> {
let (Some(listing_final), Some(listing_prelim), Some(season_start), Some(out)) = (
args.listing_final.as_deref(),
args.listing_prelim.as_deref(),
args.season_start.as_deref(),
args.out.as_deref(),
) else {
return Err(DatasetError::Exit(Exit(2)));
};
let baseline = args.baseline.as_deref().unwrap_or("1991-2020");
write_lists(
Path::new(listing_final),
Path::new(listing_prelim),
season_start,
baseline,
Path::new(out),
)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_name_is_a_pentad_and_nothing_else() {
let found = listed(
"<a href=\"chirps-v3.0.2026.11.4.cog\">x</a> \
chirps-v3.0.2026.1.1.tif chirps-v3.0.2026.11.7.cog \
chirps-v3.0.2026.11.4.cog.bak chirps-v3.0.2026.13.1.cog",
);
let keys: Vec<&str> = found.keys().map(String::as_str).collect();
assert_eq!(keys, vec!["2026.01.1", "2026.11.4"]);
}
#[test]
fn the_latest_pentad_of_a_season_crossing_the_year_is_the_new_year() {
let dir = tempfile::tempdir().expect("a temp dir");
let finals = dir.path().join("final.html");
let prelims = dir.path().join("prelim.html");
std::fs::write(
&finals,
"chirps-v3.0.2025.12.5.cog chirps-v3.0.2026.1.1.cog chirps-v3.0.2026.1.2.cog",
)
.expect("write");
std::fs::write(&prelims, "").expect("write");
let out = dir.path().join("lists");
let latest = write_lists(&finals, &prelims, "11-06", "1991-2020", &out).expect("lists");
assert_eq!(period_key(latest), "2026.01.2");
let season = std::fs::read_to_string(out.join("season.txt")).expect("season");
let lines: Vec<&str> = season.lines().collect();
assert_eq!(lines.len(), 13);
assert_eq!(
lines.first().copied(),
Some(
"prelim /products/CHIRPS/v3.0/prelim/pentads/global/tifs/chirps-v3.0.2025.11.2.tif"
)
);
assert_eq!(
lines.last().copied(),
Some("final /products/CHIRPS/v3.0/pentads/global/cogs/chirps-v3.0.2026.01.2.cog")
);
let series = std::fs::read_to_string(out.join("series.txt")).expect("series");
assert_eq!(series.lines().count(), 12);
let baseline = std::fs::read_to_string(out.join("baseline.txt")).expect("baseline");
assert_eq!(baseline.lines().count(), 2160);
}
#[test]
fn a_season_start_off_a_pentad_is_refused() {
assert!(season_slot("06-02").is_err());
assert!(season_slot("06-26").is_ok());
}
}