use serde_json::{Value, json};
use csusage_adapter_common::print_table_for_agent;
use crate::{
BucketKind, LoadedEntry, Result, cli::AgentReportKind, cli::SharedArgs, cli::WeekDay,
summarize_by_key, summarize_summaries_by_bucket, totals_json,
};
pub fn report_from_rows(rows: &[crate::UsageSummary], kind: AgentReportKind) -> Value {
let rows_json = rows
.iter()
.map(|row| csusage_core::agent_summary_json(row, kind, false))
.collect::<Vec<_>>();
json!({
rows_key(kind): rows_json,
"totals": totals_json(rows),
})
}
pub fn summarize_entries(
entries: &[LoadedEntry],
kind: AgentReportKind,
) -> Result<Vec<crate::UsageSummary>> {
match kind {
AgentReportKind::Daily => summarize_by_key(
entries,
|entry| entry.date.clone(),
|date| (date.to_string(), None),
),
AgentReportKind::Monthly => {
let daily = summarize_by_key(
entries,
|entry| entry.date.clone(),
|date| (date.to_string(), None),
)?;
Ok(summarize_summaries_by_bucket(
&daily,
BucketKind::Monthly,
WeekDay::Sunday,
))
}
AgentReportKind::Session => summarize_by_key(
entries,
|entry| entry.session_id.to_string(),
|session_id| (session_id.to_string(), None),
)
.map(|mut rows| {
for row in &mut rows {
row.session_id = row.date.take();
}
rows
}),
AgentReportKind::Weekly => {
let daily = summarize_entries(entries, AgentReportKind::Daily)?;
Ok(summarize_summaries_by_bucket(
&daily,
BucketKind::Weekly,
WeekDay::Sunday,
))
}
}
}
fn rows_key(kind: AgentReportKind) -> &'static str {
match kind {
AgentReportKind::Daily => "daily",
AgentReportKind::Weekly => "weekly",
AgentReportKind::Monthly => "monthly",
AgentReportKind::Session => "sessions",
}
}
pub fn print_table(
kind: AgentReportKind,
rows: &[crate::UsageSummary],
shared: &SharedArgs,
) -> Result<()> {
print_table_for_agent("Amp", kind, rows, shared)
}