use std::path::PathBuf;
use std::time::UNIX_EPOCH;
use serde::{Serialize, de::DeserializeOwned};
pub(crate) const USAGE_CACHE_FILE: &str = "usage_cache.json";
pub(crate) const THIRD_PARTY_CACHE_FILE: &str = "third_party_cache.json";
pub(crate) const ACCOUNT_ID_CACHE_FILE: &str = "account_id.json";
pub(crate) fn profile_cache_path(name: &str, file: &str) -> Option<PathBuf> {
crate::profile::profile_dir(name).ok().map(|p| p.join(file))
}
pub(crate) fn load_profile_cache<T: DeserializeOwned>(name: &str, file: &str) -> Option<T> {
profile_cache_path(name, file).and_then(|p| {
let text = std::fs::read_to_string(p).ok()?;
serde_json::from_str::<T>(&text).ok()
})
}
pub(crate) fn write_profile_cache<T: Serialize>(name: &str, file: &str, value: &T) {
let Some(path) = profile_cache_path(name, file) else {
return;
};
let Ok(json) = serde_json::to_string(value) else {
return;
};
let _ = crate::profile::atomic_write_600(&path, json.as_bytes());
}
pub(crate) fn profile_cache_mtime_ms(name: &str, file: &str) -> Option<u64> {
let modified = std::fs::metadata(profile_cache_path(name, file)?)
.ok()?
.modified()
.ok()?;
modified
.duration_since(UNIX_EPOCH)
.ok()
.map(|d| d.as_millis() as u64)
}