Skip to main content

ai_usagebar/
format.rs

1//! `{placeholder}` substitution for `--format` and `--tooltip-format`.
2//!
3//! Same surface as claudebar (claudebar:625-667): placeholders are surrounded
4//! by `{}`, unknown placeholders are left untouched (matching bash parameter
5//! expansion's default behavior — claudebar uses `${text//\{x\}/$val}` which
6//! is a no-op for unknown keys).
7//!
8//! Built on a `Map<&str, String>` so each vendor can register its own
9//! placeholder set and the rendering code doesn't need to know what they are.
10
11use std::collections::HashMap;
12use std::time::Duration;
13
14use chrono::{DateTime, Local, Utc};
15
16use crate::usage::{ResetCredit, ResetCredits};
17
18/// A monetary amount, with the sign outside the symbol. `format!("${v:.2}")`
19/// puts it inside — `$-5.71` — which reads as a typo rather than as debt, and
20/// several providers let a balance go negative: OpenRouter overruns its
21/// credits, Moonshot carries an explicit `cash_balance` debt.
22///
23/// The sign is decided from the *rounded* magnitude, so neither a negative
24/// zero off the wire nor a sub-cent debt can produce the nonsense `-$0.00`.
25///
26/// This is the one place that decides what money looks like. Every renderer
27/// goes through it so a debt cannot be spelled two ways in two panels.
28pub fn money(v: f64, currency: &str) -> String {
29    let magnitude = format!("{:.2}", v.abs());
30    let sign = if v < 0.0 && magnitude != "0.00" {
31        "-"
32    } else {
33        ""
34    };
35    with_currency(sign, &magnitude, Some(currency))
36}
37
38/// Attach a currency to an already-formatted magnitude and sign.
39///
40/// The one table that decides which currencies get a symbol. [`money`] works in
41/// `f64` at two decimals and [`crate::usage::fmt_minor`] works in integer minor
42/// units at the currency's own scale — two different numbers, but they must not
43/// disagree about what a euro looks like. They did: `money` rendered EUR as
44/// `3.50 EUR` while `fmt_minor` rendered the same currency as `€3.50`.
45///
46/// `None` means a payload that predates any currency field; those were always
47/// USD. A code with no symbol here trails the code instead of guessing one,
48/// which is still truthful — rendering R$ 141.57 as "$141.57" is a claim about
49/// the wrong currency, the same class of defect as a fabricated number.
50pub fn with_currency(sign: &str, number: &str, currency: Option<&str>) -> String {
51    match currency {
52        None | Some("USD") => format!("{sign}${number}"),
53        Some("BRL") => format!("{sign}R${number}"),
54        Some("EUR") => format!("{sign}€{number}"),
55        Some("GBP") => format!("{sign}£{number}"),
56        Some("JPY") | Some("CNY") => format!("{sign}¥{number}"),
57        Some(other) => format!("{sign}{number} {other}"),
58    }
59}
60
61/// Upper-case the first character, leaving the rest alone.
62///
63/// Vendor plans arrive lower-cased (`"pro"`, `"max"`, `"glm coding pro"`) and
64/// every one of them wants the same title-ish label. `char::to_uppercase` can
65/// yield more than one char, so this is not `s[..1].to_uppercase() + &s[1..]`.
66pub fn capitalize(s: &str) -> String {
67    let mut chars = s.chars();
68    match chars.next() {
69        Some(first) => {
70            let mut out = String::with_capacity(s.len());
71            out.extend(first.to_uppercase());
72            out.push_str(chars.as_str());
73            out
74        }
75        None => String::new(),
76    }
77}
78
79/// [`money`] for the providers that only ever bill in dollars.
80pub fn usd(v: f64) -> String {
81    money(v, "USD")
82}
83
84pub fn local_time_hm(when: DateTime<Utc>) -> String {
85    when.with_timezone(&Local).format("%H:%M").to_string()
86}
87
88pub fn local_time_hms(when: DateTime<Utc>) -> String {
89    when.with_timezone(&Local).format("%H:%M:%S").to_string()
90}
91
92pub fn local_date_hm(when: DateTime<Utc>) -> String {
93    when.with_timezone(&Local)
94        .format("%b %-d %H:%M")
95        .to_string()
96}
97
98/// Compact count for placeholders and tooltips that have to stay on one line.
99pub fn reset_credits(credits: &ResetCredits) -> String {
100    let noun = if credits.available == 1 {
101        "reset"
102    } else {
103        "resets"
104    };
105    format!("{} {noun} available", credits.available)
106}
107
108/// One row per banked reset, soonest expiry first. This is what the panel,
109/// TUI, and tooltip list — a single "2 available · next expires Oct 4" line
110/// hides that two credits can lapse hours apart on the same day.
111pub fn reset_credit_lines(credits: &ResetCredits, now: DateTime<Utc>) -> Vec<String> {
112    let mut items = credits.credits.clone();
113    items.sort_by_key(|credit| credit.expires_at);
114    let mut lines: Vec<String> = items
115        .iter()
116        .map(|credit| reset_credit_line(credit, now))
117        .collect();
118    if lines.is_empty() && credits.available > 0 {
119        lines.push(reset_credits(credits));
120    }
121    lines
122}
123
124fn reset_credit_line(credit: &ResetCredit, now: DateTime<Utc>) -> String {
125    let expiry = match credit.expires_at {
126        Some(expires) if expires <= now => format!("expired {}", local_date_hm(expires)),
127        Some(expires) => format!(
128            "expires {} ({})",
129            local_date_hm(expires),
130            crate::countdown::format(Some(expires), now)
131        ),
132        None => "no expiry reported".into(),
133    };
134    match credit
135        .title
136        .as_deref()
137        .map(str::trim)
138        .filter(|title| !title.is_empty())
139    {
140        Some(title) => format!("{title} · {expiry}"),
141        None => capitalize(&expiry),
142    }
143}
144
145pub fn updated_at_hm(now: DateTime<Utc>, cache_age: Option<Duration>) -> String {
146    match cache_age {
147        Some(age) => local_time_hm(now - chrono::Duration::from_std(age).unwrap_or_default()),
148        None => "—".to_string(),
149    }
150}
151
152/// Substitute every `{key}` in `template` with `values[key]`. Unknown keys
153/// are left as-is.
154///
155/// This is a single-pass scan; an O(N) implementation that does no
156/// re-substitution. (Avoids the bash pitfall where replacement text
157/// containing `{foo}` would get further substituted.)
158pub fn substitute(template: &str, values: &HashMap<&str, String>) -> String {
159    let mut out = String::with_capacity(template.len());
160    let mut rest = template;
161    while !rest.is_empty() {
162        match rest.find('{') {
163            None => {
164                out.push_str(rest);
165                break;
166            }
167            Some(open) => {
168                // Copy everything up to the '{'.
169                out.push_str(&rest[..open]);
170                let after_open = &rest[open + 1..];
171                if let Some(close) = after_open.find('}') {
172                    let key = &after_open[..close];
173                    if let Some(val) = values.get(key) {
174                        out.push_str(val);
175                        rest = &after_open[close + 1..];
176                        continue;
177                    }
178                }
179                // Unmatched or unknown — keep the '{' literal and continue.
180                out.push('{');
181                rest = after_open;
182            }
183        }
184    }
185    out
186}
187
188/// Convenience: build a placeholder map from `(&str, impl Into<String>)` pairs.
189pub fn placeholders<I, V>(pairs: I) -> HashMap<&'static str, String>
190where
191    I: IntoIterator<Item = (&'static str, V)>,
192    V: Into<String>,
193{
194    pairs.into_iter().map(|(k, v)| (k, v.into())).collect()
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    fn pm(pairs: &[(&'static str, &str)]) -> HashMap<&'static str, String> {
202        placeholders(pairs.iter().map(|(k, v)| (*k, v.to_string())))
203    }
204
205    fn offer(title: Option<&str>, expires: &str) -> ResetCredit {
206        ResetCredit {
207            title: title.map(str::to_string),
208            expires_at: Some(expires.parse().unwrap()),
209        }
210    }
211
212    #[test]
213    fn a_reset_inventory_lists_each_credit_soonest_first() {
214        let now = "2026-07-04T00:00:00Z".parse::<DateTime<Utc>>().unwrap();
215        let credits = ResetCredits {
216            available: 2,
217            credits: vec![
218                offer(Some("Full reset (Weekly + 5 hr)"), "2026-08-01T00:00:00Z"),
219                offer(Some("Full reset (Weekly + 5 hr)"), "2026-07-17T00:00:00Z"),
220            ],
221        };
222        assert_eq!(reset_credits(&credits), "2 resets available");
223        let lines = reset_credit_lines(&credits, now);
224        assert_eq!(lines.len(), 2, "{lines:?}");
225        assert!(lines[0].contains("Full reset (Weekly + 5 hr)"), "{lines:?}");
226        assert!(lines[0].contains("(13d 0h)"), "{lines:?}");
227        assert!(lines[1].contains("(28d 0h)"), "{lines:?}");
228    }
229
230    #[test]
231    fn a_lapsed_deadline_reads_as_expired_rather_than_now() {
232        let now = "2026-07-04T00:00:00Z".parse::<DateTime<Utc>>().unwrap();
233        let lines = reset_credit_lines(
234            &ResetCredits {
235                available: 1,
236                credits: vec![offer(None, "2026-07-01T00:00:00Z")],
237            },
238            now,
239        );
240        assert_eq!(lines.len(), 1);
241        assert!(lines[0].starts_with("Expired "), "{lines:?}");
242        assert!(!lines[0].contains("(now)"), "{lines:?}");
243    }
244
245    #[test]
246    fn a_count_without_detail_still_renders_the_inventory() {
247        let now = "2026-07-04T00:00:00Z".parse::<DateTime<Utc>>().unwrap();
248        assert_eq!(
249            reset_credit_lines(
250                &ResetCredits {
251                    available: 2,
252                    credits: vec![]
253                },
254                now
255            ),
256            vec!["2 resets available"]
257        );
258    }
259
260    #[test]
261    fn single_substitution() {
262        let v = pm(&[("session_pct", "42")]);
263        assert_eq!(substitute("{session_pct}%", &v), "42%");
264    }
265
266    #[test]
267    fn usd_keeps_the_sign_outside_the_symbol() {
268        assert_eq!(usd(74.5), "$74.50");
269        assert_eq!(usd(0.0), "$0.00");
270        assert_eq!(usd(-5.71), "-$5.71");
271        // A negative zero off the wire is not a debt, and must not print as
272        // one — `format!("{:.2}")` alone would render it "$-0.00".
273        assert_eq!(usd(-0.0), "$0.00");
274        // Neither is a debt too small to show a cent.
275        assert_eq!(usd(-0.001), "$0.00");
276        // One that does round to a cent keeps its sign.
277        assert_eq!(usd(-0.006), "-$0.01");
278    }
279
280    #[test]
281    fn money_places_the_sign_ahead_of_every_currency() {
282        assert_eq!(money(20.0, "CNY"), "¥20.00");
283        assert_eq!(money(-20.0, "CNY"), "-¥20.00");
284        // A currency trails its code only when this table has no symbol for
285        // it; the sign still leads either way.
286        assert_eq!(money(3.5, "SEK"), "3.50 SEK");
287        assert_eq!(money(-3.5, "SEK"), "-3.50 SEK");
288        // usd() is the same policy, not a second one.
289        assert_eq!(money(-5.71, "USD"), usd(-5.71));
290        assert_eq!(money(-0.0, "CNY"), "¥0.00");
291    }
292
293    /// `money` and `usage::fmt_minor` compute different numbers — f64 at two
294    /// decimals versus integer minor units at the currency's own scale — but a
295    /// euro must look like a euro in both. They disagreed once: `money` had no
296    /// EUR/GBP/BRL/JPY entry and trailed the code while `fmt_minor` printed the
297    /// symbol, so the same currency read two ways in two panels.
298    #[test]
299    fn the_two_money_formatters_agree_on_every_symbol() {
300        for (code, symbol) in [
301            ("USD", "$"),
302            ("BRL", "R$"),
303            ("EUR", "€"),
304            ("GBP", "£"),
305            ("JPY", "¥"),
306            ("CNY", "¥"),
307        ] {
308            assert_eq!(money(3.5, code), format!("{symbol}3.50"), "money {code}");
309            assert_eq!(
310                crate::usage::fmt_minor(350, 2, Some(code)),
311                format!("{symbol}3.50"),
312                "fmt_minor {code}"
313            );
314        }
315        // And they agree that an unlisted code trails instead of guessing.
316        assert_eq!(money(3.5, "SEK"), "3.50 SEK");
317        assert_eq!(crate::usage::fmt_minor(350, 2, Some("SEK")), "3.50 SEK");
318        // fmt_minor keeps its own scale: JPY has no minor unit.
319        assert_eq!(crate::usage::fmt_minor(350, 0, Some("JPY")), "¥350");
320    }
321
322    #[test]
323    fn multiple_substitutions() {
324        let v = pm(&[("a", "1"), ("b", "2")]);
325        assert_eq!(substitute("{a}-{b}-{a}", &v), "1-2-1");
326    }
327
328    #[test]
329    fn unknown_placeholder_passes_through() {
330        let v = pm(&[("a", "1")]);
331        assert_eq!(substitute("{a} {unknown}", &v), "1 {unknown}");
332    }
333
334    #[test]
335    fn no_re_substitution_in_replacement_text() {
336        // Replacement text containing {a} must NOT be re-expanded.
337        let v = pm(&[("a", "{a}"), ("b", "X")]);
338        assert_eq!(substitute("{b}{a}{b}", &v), "X{a}X");
339    }
340
341    #[test]
342    fn empty_template() {
343        let v = pm(&[("a", "1")]);
344        assert_eq!(substitute("", &v), "");
345    }
346
347    #[test]
348    fn template_without_braces() {
349        let v = pm(&[("a", "1")]);
350        assert_eq!(substitute("hello world", &v), "hello world");
351    }
352
353    #[test]
354    fn unmatched_open_brace_is_literal() {
355        let v = pm(&[("a", "1")]);
356        assert_eq!(substitute("{a {x", &v), "{a {x");
357    }
358
359    #[test]
360    fn placeholders_with_underscores_and_digits() {
361        let v = pm(&[("session_pct_2", "x")]);
362        assert_eq!(substitute("{session_pct_2}", &v), "x");
363    }
364
365    #[test]
366    fn utf8_around_braces() {
367        let v = pm(&[("x", "→")]);
368        assert_eq!(substitute("α{x}β", &v), "α→β");
369    }
370}