//! `/stats` dashboard: token totals, cache hit, per-request table. use crate::theme; use hx_core::stats::Summary; use ratatui::layout::Rect; use ratatui::text::{Line, Span}; use ratatui::widgets::{Block, Clear, Paragraph}; fn bar(v: u64, max: u64, w: usize) -> String { let th = theme::t(); let n = (v * w as u64 / max.max(1)) as usize; format!( "{}{}", th.sym.bar_full.repeat(n), th.sym.bar_empty.repeat(w - n) ) } fn k(n: u64) -> String { format!("{:.1}k", n as f64 / 1000.0) } pub fn lines(s: &Summary, rows: usize) -> Vec> { let th = theme::t(); let total = s.fresh + s.cache_read + s.cache_write; let hit = 100 * s.cache_read / total.max(1); let row = |name: &str, v: u64, extra: String| { Line::from(vec![ Span::raw(format!("{name:<8}{:>7} ", k(v))), Span::styled(bar(v, total.max(s.output), 20), th.accent()), Span::styled(extra, th.ok()), ]) }; let mut l = vec![ row("input", total, String::new()), row("output", s.output, String::new()), row("cache r", s.cache_read, format!(" {hit}% hit")), Line::default(), Line::styled( format!("{:<5}{:>9}{:>9}{:>8}", "req", "in", "out", "cache"), th.dim(), ), ]; let skip = s.reqs.len().saturating_sub(rows); for (i, (inp, out, h)) in s.reqs.iter().enumerate().skip(skip) { l.push(Line::from(vec![ Span::raw(format!("#{:<4}{:>9}{:>9}", i + 1, k(*inp), k(*out))), Span::styled( format!("{:>7}%", h), if *h >= 80 { th.ok() } else { th.warn() }, ), ])); } l } pub fn draw(f: &mut ratatui::Frame, s: &Summary, title: &str) { let th = theme::t(); let a = f.area(); let w = (a.width * 6 / 10).clamp(50, 90).min(a.width); let h = (a.height * 7 / 10).clamp(12, 30).min(a.height); let r = Rect::new(a.x + (a.width - w) / 2, a.y + (a.height - h) / 2, w, h); let body = if s.reqs.is_empty() { vec![Line::styled("no usage recorded yet", th.dim())] } else { lines(s, (h as usize).saturating_sub(9)) }; f.render_widget(Clear, r); f.render_widget( Paragraph::new(body).block( Block::bordered() .border_style(th.dim()) .padding(ratatui::widgets::Padding::horizontal(1)) .title(Span::styled(format!(" stats ยท {title} "), th.dim())) .title_bottom(Span::styled(" esc close ", th.dim())), ), r, ); } #[cfg(test)] mod tests { use super::*; #[test] fn table_keeps_latest_rows() { let s = Summary { fresh: 10, cache_read: 90, cache_write: 0, output: 5, reqs: (1..=10).map(|i| (100, 5, i)).collect(), }; let l = lines(&s, 3); assert_eq!(l.len(), 5 + 3); assert!(l[2].to_string().contains("90% hit")); assert!(l.last().unwrap().to_string().starts_with("#10")); } }