use crate::display::common::ProviderTotal;
use crate::models::{PerProviderUsage, Provider, ProviderActiveDays, UsageResult};
use serde_json::Value;
use std::borrow::Cow;
#[derive(Default)]
pub struct UsageRow {
pub model: String, pub display_model: String, pub input_tokens: i64,
pub output_tokens: i64,
pub reasoning_tokens: i64,
pub cache_read: i64,
pub cache_creation: i64,
pub total: i64,
pub cost: f64,
}
impl UsageRow {
#[inline]
pub fn output_with_reasoning(&self) -> i64 {
self.output_tokens + self.reasoning_tokens
}
}
#[derive(Default)]
pub struct UsageTotals {
pub input_tokens: i64,
pub output_tokens: i64,
pub reasoning_tokens: i64,
pub cache_read: i64,
pub cache_creation: i64,
pub total: i64,
pub cost: f64,
}
impl UsageTotals {
pub fn accumulate(&mut self, row: &UsageRow) {
self.input_tokens += row.input_tokens;
self.output_tokens += row.output_tokens;
self.reasoning_tokens += row.reasoning_tokens;
self.cache_read += row.cache_read;
self.cache_creation += row.cache_creation;
self.total += row.total;
self.cost += row.cost;
}
#[inline]
pub fn output_with_reasoning(&self) -> i64 {
self.output_tokens + self.reasoning_tokens
}
}
#[derive(Default, Clone)]
pub struct ProviderStats {
pub total_tokens: i64,
pub total_cost: f64,
pub days_count: usize,
}
impl ProviderStats {
fn accumulate_row(&mut self, row: &UsageRow) {
self.total_tokens += row.total;
self.total_cost += row.cost;
}
}
pub type UsageProviderTotals = crate::display::common::ProviderTotals<ProviderStats>;
#[derive(Default)]
pub struct UsageSummary {
pub rows: Vec<UsageRow>,
pub totals: UsageTotals,
pub provider_totals: UsageProviderTotals,
}
pub fn calculate_provider_totals_from_per_provider(
per_provider: &PerProviderUsage,
provider_days: &ProviderActiveDays,
pricing_map: &crate::pricing::ModelPricingMap,
opencode_costs: &crate::constants::FastHashMap<String, f64>,
) -> UsageProviderTotals {
let mut totals = UsageProviderTotals::default();
totals.claude.days_count = provider_days.claude;
totals.codex.days_count = provider_days.codex;
totals.copilot.days_count = provider_days.copilot;
totals.gemini.days_count = provider_days.gemini;
totals.opencode.days_count = provider_days.opencode;
totals.overall.days_count = provider_days.total;
accumulate_provider(&mut totals.claude, &per_provider.claude, pricing_map, None);
accumulate_provider(&mut totals.codex, &per_provider.codex, pricing_map, None);
accumulate_provider(
&mut totals.copilot,
&per_provider.copilot,
pricing_map,
None,
);
accumulate_provider(&mut totals.gemini, &per_provider.gemini, pricing_map, None);
accumulate_provider(
&mut totals.opencode,
&per_provider.opencode,
pricing_map,
Some(opencode_costs),
);
totals.overall.total_tokens = totals.claude.total_tokens
+ totals.codex.total_tokens
+ totals.copilot.total_tokens
+ totals.gemini.total_tokens
+ totals.opencode.total_tokens;
totals.overall.total_cost = totals.claude.total_cost
+ totals.codex.total_cost
+ totals.copilot.total_cost
+ totals.gemini.total_cost
+ totals.opencode.total_cost;
totals
}
fn accumulate_provider(
stats: &mut ProviderStats,
usage: &UsageResult,
pricing_map: &crate::pricing::ModelPricingMap,
opencode_costs: Option<&crate::constants::FastHashMap<String, f64>>,
) {
for (model, raw_usage) in usage {
let opencode_cost = opencode_costs.map(|m| m.get(model).copied().unwrap_or(0.0));
let row = extract_usage_row(model, raw_usage, pricing_map, opencode_cost);
stats.accumulate_row(&row);
}
}
pub fn build_provider_total_rows(
totals: &UsageProviderTotals,
) -> Vec<ProviderTotal<'_, ProviderStats>> {
let mut rows = Vec::with_capacity(6);
if totals.claude.days_count > 0 {
rows.push(ProviderTotal::new(
Provider::ClaudeCode,
&totals.claude,
false,
));
}
if totals.codex.days_count > 0 {
rows.push(ProviderTotal::new(Provider::Codex, &totals.codex, false));
}
if totals.copilot.days_count > 0 {
rows.push(ProviderTotal::new(
Provider::Copilot,
&totals.copilot,
false,
));
}
if totals.gemini.days_count > 0 {
rows.push(ProviderTotal::new(Provider::Gemini, &totals.gemini, false));
}
if totals.opencode.days_count > 0 {
rows.push(ProviderTotal::new(
Provider::OpenCode,
&totals.opencode,
false,
));
}
if totals.overall.days_count > 0 || rows.is_empty() {
rows.push(ProviderTotal::new_overall(&totals.overall));
}
rows
}
pub fn build_usage_summary(
usage_data: &UsageResult,
per_provider: &PerProviderUsage,
provider_days: &ProviderActiveDays,
pricing_map: &crate::pricing::ModelPricingMap,
opencode_costs: &crate::constants::FastHashMap<String, f64>,
) -> UsageSummary {
if usage_data.is_empty() {
return UsageSummary::default();
}
let mut summary = UsageSummary::default();
summary.rows.reserve(usage_data.len());
for (model, usage) in usage_data.iter() {
let (cost, matched_model) =
resolve_merged_row_cost(model, per_provider, pricing_map, opencode_costs)
.unwrap_or_else(|| price_usage(model, usage, pricing_map, None));
let row = build_usage_row(model, usage, cost, matched_model);
summary.rows.push(row);
}
summary.rows.sort_by(|a, b| {
a.cost
.partial_cmp(&b.cost)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| a.model.cmp(&b.model))
});
for row in &summary.rows {
summary.totals.accumulate(row);
}
summary.provider_totals = calculate_provider_totals_from_per_provider(
per_provider,
provider_days,
pricing_map,
opencode_costs,
);
summary
}
fn extract_usage_row(
model: &str,
usage: &Value,
pricing_map: &crate::pricing::ModelPricingMap,
opencode_cost: Option<f64>,
) -> UsageRow {
let (cost, matched_model) = price_usage(model, usage, pricing_map, opencode_cost);
build_usage_row(model, usage, cost, matched_model)
}
fn price_usage(
model: &str,
usage: &Value,
pricing_map: &crate::pricing::ModelPricingMap,
opencode_cost: Option<f64>,
) -> (f64, Option<String>) {
use crate::usage::resolve_model_cost;
use crate::utils::extract_token_counts;
let counts = extract_token_counts(usage);
resolve_model_cost(model, &counts, pricing_map, opencode_cost)
}
fn resolve_merged_row_cost(
model: &str,
per_provider: &PerProviderUsage,
pricing_map: &crate::pricing::ModelPricingMap,
opencode_costs: &crate::constants::FastHashMap<String, f64>,
) -> Option<(f64, Option<String>)> {
let mut total_cost = 0.0;
let mut matched_model = None;
let mut found = false;
for usage in [
&per_provider.claude,
&per_provider.codex,
&per_provider.copilot,
&per_provider.gemini,
] {
if let Some(raw_usage) = usage.get(model) {
found = true;
let (cost, matched) = price_usage(model, raw_usage, pricing_map, None);
total_cost += cost;
if matched_model.is_none() {
matched_model = matched;
}
}
}
if let Some(raw_usage) = per_provider.opencode.get(model) {
found = true;
let opencode_cost = opencode_costs.get(model).copied().unwrap_or(0.0);
let (cost, matched) = price_usage(model, raw_usage, pricing_map, Some(opencode_cost));
total_cost += cost;
if matched_model.is_none() {
matched_model = matched;
}
}
found.then_some((total_cost, matched_model))
}
fn build_usage_row(
model: &str,
usage: &Value,
cost: f64,
matched_model: Option<String>,
) -> UsageRow {
use crate::utils::extract_token_counts;
let counts = extract_token_counts(usage);
let display_model = if let Some(matched) = &matched_model {
Cow::Owned(format!("{} ({})", model, matched))
} else {
Cow::Borrowed(model)
};
UsageRow {
model: model.to_string(),
display_model: display_model.into_owned(),
input_tokens: counts.input_tokens,
output_tokens: counts.output_tokens,
reasoning_tokens: counts.reasoning_tokens,
cache_read: counts.cache_read,
cache_creation: counts.cache_creation,
total: counts.total,
cost,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::pricing::{ModelPricing, ModelPricingMap, clear_pricing_cache};
use serde_json::json;
#[test]
fn merged_rows_price_opencode_fallback_only_for_opencode_tokens() {
clear_pricing_cache();
let mut raw_pricing = std::collections::HashMap::new();
raw_pricing.insert(
"shared".to_string(),
ModelPricing {
input_cost_per_token: 0.01,
..Default::default()
},
);
let pricing_map = ModelPricingMap::new(raw_pricing);
let mut usage_data = UsageResult::default();
usage_data.insert("shared-pro".to_string(), json!({"input_tokens": 200}));
let mut per_provider = PerProviderUsage::default();
per_provider
.claude
.insert("shared-pro".to_string(), json!({"input_tokens": 100}));
per_provider
.opencode
.insert("shared-pro".to_string(), json!({"input_tokens": 100}));
let mut opencode_costs = crate::constants::FastHashMap::default();
opencode_costs.insert("shared-pro".to_string(), 7.0);
let summary = build_usage_summary(
&usage_data,
&per_provider,
&ProviderActiveDays::default(),
&pricing_map,
&opencode_costs,
);
assert_eq!(summary.rows.len(), 1);
assert!((summary.rows[0].cost - 8.0).abs() < 1e-9);
assert_eq!(summary.rows[0].display_model, "shared-pro (shared)");
}
}