use std::path::Path;
use crate::error::{Result, WithinExt as _};
use crate::cli::StatusArgs;
use crate::exit::Exit;
use crate::layout::{
Settings, complete_stages, current_key, date_utc, days_of_date, format_utc_millis,
modified_millis, read_json, settings,
};
use crate::stage::read_stage;
pub fn status_lines(s: &Settings, today: i64) -> Result<Vec<String>> {
let mut lines = vec![format!("dataset {}", s.dataset)];
let Some(id) = complete_stages(&s.stage_root).last().cloned() else {
lines.push(format!(
"build none (nothing staged in {})",
s.stage_root.display()
));
return Ok(lines);
};
let stage = read_stage(s, &id)?;
let current =
read_json(&stage.dir.join(current_key(s))).within(format!("reading {}", current_key(s)))?;
let text = |key: &str| {
current
.get(key)
.and_then(serde_json::Value::as_str)
.map(str::to_owned)
};
let period_end = text("period_end").unwrap_or_default();
let status = text("status").unwrap_or_default();
let stale_after = text("stale_after").unwrap_or_default();
let today_date = date_utc(today);
let age = match (days_of_date(&today_date), days_of_date(&period_end)) {
(Some(today), Some(end)) => (today - end).div_euclid(1),
_ => 0,
};
lines.push(format!("build {id}"));
lines.push(format!("period_end {period_end}"));
lines.push(format!("status {status}"));
lines.push(format!("age_days {age}"));
lines.push(format!(
"state {}",
if today_date > stale_after {
"STALE"
} else {
"FRESH"
}
));
for marker in ["uploaded", "published"] {
let path: &Path = &stage.dir.join(format!("{marker}.json"));
let value = if path.exists() {
format_utc_millis(modified_millis(path)?)
} else {
"no".to_owned()
};
lines.push(format!("{marker} {value}"));
}
Ok(lines)
}
pub fn run(args: &StatusArgs) -> Result<()> {
let s = settings(args.dataset.as_deref(), args.country.as_deref())?;
println!("dataset {}", s.dataset);
let staged = !complete_stages(&s.stage_root).is_empty();
for line in status_lines(&s, crate::layout::unix_seconds())?
.into_iter()
.skip(1)
{
println!("{line}");
}
if staged { Ok(()) } else { Err(Exit(1).into()) }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::layout::Settings;
fn staged(root: &Path, stale_after: &str) {
let id = "2026-11-20.20261120T0000Z";
let dir = root.join("datasets/stage").join(id);
let pointer = dir.join("datasets/rainfall/in/current.json");
std::fs::create_dir_all(pointer.parent().expect("parent")).expect("mkdir");
std::fs::write(
&pointer,
format!(
r#"{{"build_id":"{id}","period_end":"2026-11-18","status":"final","stale_after":"{stale_after}"}}"#
),
)
.expect("write");
std::fs::write(dir.join("stage.json"), r#"{"files":[]}"#).expect("write");
}
#[test]
fn status_reports_stale_when_today_is_after_stale_after() {
let dir = tempfile::tempdir().expect("a temp dir");
staged(dir.path(), "2026-11-01");
let mut s = Settings::for_test("rainfall", "in", "/nonexistent/data");
s.stage_root = dir.path().join("datasets/stage");
let lines = status_lines(&s, 1_795_305_600).expect("status");
assert_eq!(
lines,
[
"dataset rainfall",
"build 2026-11-20.20261120T0000Z",
"period_end 2026-11-18",
"status final",
"age_days 4",
"state STALE",
"uploaded no",
"published no",
]
);
}
#[test]
fn status_reports_fresh_when_today_is_not_after_stale_after() {
let dir = tempfile::tempdir().expect("a temp dir");
staged(dir.path(), "2026-11-30");
let mut s = Settings::for_test("rainfall", "in", "/nonexistent/data");
s.stage_root = dir.path().join("datasets/stage");
let lines = status_lines(&s, 1_795_305_600).expect("status");
assert_eq!(lines[5], "state FRESH");
}
#[test]
fn nothing_staged_prints_build_none() {
let dir = tempfile::tempdir().expect("a temp dir");
let mut s = Settings::for_test("rainfall", "in", "/nonexistent/data");
s.stage_root = dir.path().join("datasets/stage");
let lines = status_lines(&s, 1_795_305_600).expect("status");
assert_eq!(lines.len(), 2);
assert!(
lines[1].starts_with("build none (nothing staged in "),
"{}",
lines[1]
);
}
}