use crate::{plugins::units::Units, re};
pub(super) fn rewrite(s: &str, units: &Units) -> String {
if let Some(c) = re!(r"^how far (?:do i go|will i travel) at (.+) for (.+)$").captures(s) {
return travel(&c[1], &c[2], units);
}
if let Some(c) = re!(r"^how long does (.+) take at (.+)$").captures(s) {
return format!("({}) / ({}) in hours", &c[1], &c[2]);
}
if let Some(c) = re!(r"^at (.+), how far in (.+)$").captures(s) {
return travel(&c[1], &c[2], units);
}
if let Some(c) = re!(r"^how long to travel (.+) at (.+)$").captures(s) {
return format!("({}) / ({}) in hours", &c[1], &c[2]);
}
if let Some(c) = re!(r"^how many (.+) per (.+) if (.+) covers (.+)$").captures(s) {
return format!("({}) / ({}) * ({}) in {}", &c[3], &c[4], &c[2], &c[1]);
}
s.to_string()
}
fn travel(rate: &str, duration: &str, units: &Units) -> String {
let rate = rate.replace(" per ", "/");
let numerator = rate.split('/').next().unwrap_or(&rate);
let target = units
.quantity(numerator)
.filter(|q| q.unit.dimension == [1, 0, 0, 0, 0, 0, 0, 0])
.map(|q| q.unit.symbol)
.or_else(|| rate.contains("mph").then(|| "mi".into()));
format!(
"{rate} for {duration}{}",
target.map_or(String::new(), |unit| format!(" in {unit}"))
)
}