use crate::cache::global_cache;
use crate::cli::TimeRange;
use crate::constants::{FastHashMap, capacity};
use crate::models::ProviderActiveDays;
use crate::utils::{collect_files_with_dates, is_gemini_chat_file, is_json_file};
use anyhow::Result;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashSet;
use std::path::Path;
use std::sync::Arc;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AggregatedAnalysisRow {
pub model: String,
pub edit_lines: usize,
pub read_lines: usize,
pub write_lines: usize,
pub bash_count: usize,
pub edit_count: usize,
pub read_count: usize,
pub todo_write_count: usize,
pub write_count: usize,
}
pub struct AnalysisData {
pub rows: Vec<AggregatedAnalysisRow>,
pub provider_days: ProviderActiveDays,
}
pub fn analyze_all_sessions(time_range: TimeRange) -> Result<AnalysisData> {
let paths = crate::utils::resolve_paths()?;
let mut aggregated: FastHashMap<String, AggregatedAnalysisRow> =
FastHashMap::with_capacity(capacity::MODEL_COMBINATIONS);
let mut claude_dates: HashSet<String> = HashSet::new();
let mut codex_dates: HashSet<String> = HashSet::new();
let mut copilot_dates: HashSet<String> = HashSet::new();
let mut gemini_dates: HashSet<String> = HashSet::new();
if paths.claude_session_dir.exists() {
process_analysis_directory(
&paths.claude_session_dir,
&mut aggregated,
&mut claude_dates,
is_json_file,
time_range,
)?;
}
if paths.codex_session_dir.exists() {
process_analysis_directory(
&paths.codex_session_dir,
&mut aggregated,
&mut codex_dates,
is_json_file,
time_range,
)?;
}
if paths.copilot_session_dir.exists() {
process_analysis_directory(
&paths.copilot_session_dir,
&mut aggregated,
&mut copilot_dates,
is_json_file,
time_range,
)?;
}
if paths.gemini_session_dir.exists() {
process_analysis_directory(
&paths.gemini_session_dir,
&mut aggregated,
&mut gemini_dates,
is_gemini_chat_file,
time_range,
)?;
}
let mut all_dates: HashSet<&String> = HashSet::new();
all_dates.extend(claude_dates.iter());
all_dates.extend(codex_dates.iter());
all_dates.extend(copilot_dates.iter());
all_dates.extend(gemini_dates.iter());
let provider_days = ProviderActiveDays {
claude: claude_dates.len(),
codex: codex_dates.len(),
copilot: copilot_dates.len(),
gemini: gemini_dates.len(),
total: all_dates.len(),
};
let mut results: Vec<AggregatedAnalysisRow> = aggregated.into_values().collect();
results.sort_unstable_by(|a, b| a.model.cmp(&b.model));
Ok(AnalysisData {
rows: results,
provider_days,
})
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderGroupedAnalysis {
#[serde(rename = "Claude-Code")]
pub claude: Vec<Value>,
#[serde(rename = "Codex")]
pub codex: Vec<Value>,
#[serde(rename = "Copilot-CLI")]
pub copilot: Vec<Value>,
#[serde(rename = "Gemini")]
pub gemini: Vec<Value>,
}
pub fn analyze_all_sessions_by_provider(time_range: TimeRange) -> Result<ProviderGroupedAnalysis> {
let paths = crate::utils::resolve_paths()?;
let mut claude_results: Vec<Value> = Vec::new();
let mut codex_results: Vec<Value> = Vec::new();
let mut copilot_results: Vec<Value> = Vec::new();
let mut gemini_results: Vec<Value> = Vec::new();
if paths.claude_session_dir.exists() {
process_full_analysis_directory(
&paths.claude_session_dir,
&mut claude_results,
is_json_file,
time_range,
)?;
}
if paths.codex_session_dir.exists() {
process_full_analysis_directory(
&paths.codex_session_dir,
&mut codex_results,
is_json_file,
time_range,
)?;
}
if paths.copilot_session_dir.exists() {
process_full_analysis_directory(
&paths.copilot_session_dir,
&mut copilot_results,
is_json_file,
time_range,
)?;
}
if paths.gemini_session_dir.exists() {
process_full_analysis_directory(
&paths.gemini_session_dir,
&mut gemini_results,
is_gemini_chat_file,
time_range,
)?;
}
Ok(ProviderGroupedAnalysis {
claude: claude_results,
codex: codex_results,
copilot: copilot_results,
gemini: gemini_results,
})
}
fn process_full_analysis_directory<P, F>(
dir: P,
results: &mut Vec<Value>,
filter_fn: F,
time_range: TimeRange,
) -> Result<()>
where
P: AsRef<Path>,
F: Copy + Fn(&Path) -> bool + Sync + Send,
{
let dir = dir.as_ref();
let files = collect_files_with_dates(dir, filter_fn, time_range)?;
let analyzed: Vec<Arc<Value>> = files
.par_iter()
.filter_map(
|file_info| match global_cache().get_or_parse(&file_info.path) {
Ok(analysis_arc) => Some(analysis_arc),
Err(e) => {
eprintln!(
"Warning: Failed to analyze {}: {}",
file_info.path.display(),
e
);
None
}
},
)
.collect();
results.extend(analyzed.iter().map(|arc| (**arc).clone()));
Ok(())
}
fn process_analysis_directory<P, F>(
dir: P,
aggregated: &mut FastHashMap<String, AggregatedAnalysisRow>,
unique_dates: &mut HashSet<String>,
filter_fn: F,
time_range: TimeRange,
) -> Result<()>
where
P: AsRef<Path>,
F: Copy + Fn(&Path) -> bool + Sync + Send,
{
let dir = dir.as_ref();
let files = collect_files_with_dates(dir, filter_fn, time_range)?;
let file_aggregations: Vec<(String, Arc<Value>)> = files
.par_iter()
.filter_map(
|file_info| match global_cache().get_or_parse(&file_info.path) {
Ok(analysis_arc) => Some((file_info.modified_date.clone(), analysis_arc)),
Err(e) => {
eprintln!(
"Warning: Failed to analyze {}: {}",
file_info.path.display(),
e
);
None
}
},
)
.collect();
for (date, analysis_arc) in file_aggregations {
unique_dates.insert(date);
aggregate_analysis_result(aggregated, &analysis_arc);
}
Ok(())
}
fn aggregate_analysis_result(
aggregated: &mut FastHashMap<String, AggregatedAnalysisRow>,
analysis: &Value,
) {
let Some(records) = analysis.get("records").and_then(|r| r.as_array()) else {
return;
};
for record in records {
let Some(record_obj) = record.as_object() else {
continue;
};
let Some(conv_usage) = record_obj
.get("conversationUsage")
.and_then(|c| c.as_object())
else {
continue;
};
for (model, _usage) in conv_usage {
if model.contains("<synthetic>") {
continue;
}
let entry =
aggregated
.entry(model.to_string())
.or_insert_with(|| AggregatedAnalysisRow {
model: model.to_string(),
edit_lines: 0,
read_lines: 0,
write_lines: 0,
bash_count: 0,
edit_count: 0,
read_count: 0,
todo_write_count: 0,
write_count: 0,
});
entry.edit_lines += record_obj
.get("totalEditLines")
.and_then(|v| v.as_u64())
.unwrap_or(0) as usize;
entry.read_lines += record_obj
.get("totalReadLines")
.and_then(|v| v.as_u64())
.unwrap_or(0) as usize;
entry.write_lines += record_obj
.get("totalWriteLines")
.and_then(|v| v.as_u64())
.unwrap_or(0) as usize;
if let Some(tool_calls) = record_obj.get("toolCallCounts").and_then(|t| t.as_object()) {
entry.bash_count +=
tool_calls.get("Bash").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
entry.edit_count +=
tool_calls.get("Edit").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
entry.read_count +=
tool_calls.get("Read").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
entry.todo_write_count += tool_calls
.get("TodoWrite")
.and_then(|v| v.as_u64())
.unwrap_or(0) as usize;
entry.write_count += tool_calls
.get("Write")
.and_then(|v| v.as_u64())
.unwrap_or(0) as usize;
}
}
}
}