1use crate::usage_log;
2use serde::{Deserialize, Serialize};
3use std::cmp::Ordering;
4use std::collections::HashMap;
5use std::fs::File;
6use std::io::{BufRead, BufReader, ErrorKind};
7use std::path::Path;
8
9#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
10pub struct Group {
11 pub cost_usd: f64,
12 pub unpriced: u64,
13 pub lines: u64,
14 pub runs: u64,
15 pub input: u64,
16 pub cached: u64,
17 pub output: u64,
18 pub thinking: u64,
19}
20
21impl Group {
22 fn add(&mut self, entry: &usage_log::Entry) {
23 match entry.cost_usd {
24 Some(cost) => self.cost_usd += cost,
25 None => self.unpriced += 1,
26 }
27 self.lines += 1;
28 if is_run(entry) {
29 self.runs += 1;
30 }
31 self.input += entry.input;
32 self.cached += entry.cached;
33 self.output += entry.output;
34 self.thinking += entry.thinking;
35 }
36}
37
38#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
39pub struct DayRow {
40 pub day: String,
41 #[serde(flatten)]
42 pub group: Group,
43}
44
45#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
46pub struct KindRow {
47 pub kind: String,
48 #[serde(flatten)]
49 pub group: Group,
50}
51
52#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
53pub struct SurfaceRow {
54 pub surface: Option<String>,
55 pub name: Option<String>,
56 pub last_ts: u64,
57 #[serde(flatten)]
58 pub group: Group,
59}
60
61#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
62pub struct RepoRow {
63 pub repo: String,
64 #[serde(flatten)]
65 pub group: Group,
66}
67
68#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
69pub struct ModelRow {
70 pub model: String,
71 #[serde(flatten)]
72 pub group: Group,
73}
74
75#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
76pub struct Report {
77 pub generated_at: u64,
78 pub since: Option<u64>,
79 pub log: String,
80 pub log_exists: bool,
81 pub unreadable_lines: u64,
82 pub totals: Group,
83 pub by_day: Vec<DayRow>,
84 pub by_kind: Vec<KindRow>,
85 pub by_surface: Vec<SurfaceRow>,
86 pub by_repo: Vec<RepoRow>,
87 pub by_model: Vec<ModelRow>,
88}
89
90struct SurfaceAcc {
91 group: Group,
92 last_ts: u64,
93 latest_name: Option<(u64, String)>,
94}
95
96pub fn kind_of(entry: &usage_log::Entry) -> &'static str {
97 if entry.outcome == "model_review" {
98 "review"
99 } else if entry.research {
100 "research"
101 } else if entry.dispatch.is_some() {
102 "implementer"
103 } else {
104 "conversation"
105 }
106}
107
108fn is_run(entry: &usage_log::Entry) -> bool {
109 entry.dispatch.is_some() && entry.outcome != "turn" && entry.outcome != "model_review"
110}
111
112pub fn utc_day(ts: u64) -> String {
113 let days = (ts / 86_400) as i64;
114 let z = days + 719_468;
115 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
116 let doe = (z - era * 146_097) as u64;
117 let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
118 let y = yoe as i64 + era * 400;
119 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
120 let mp = (5 * doy + 2) / 153;
121 let d = doy - (153 * mp + 2) / 5 + 1;
122 let m = if mp < 10 { mp + 3 } else { mp - 9 };
123 let year = if m <= 2 { y + 1 } else { y };
124 format!("{year:04}-{m:02}-{d:02}")
125}
126
127fn cmp_surface_key(a: Option<&str>, b: Option<&str>) -> Ordering {
128 match (a, b) {
129 (Some(a), Some(b)) => a.cmp(b),
130 (Some(_), None) => Ordering::Less,
131 (None, Some(_)) => Ordering::Greater,
132 (None, None) => Ordering::Equal,
133 }
134}
135
136pub fn build(log: &Path, since: Option<u64>, now: u64) -> Result<Report, String> {
138 let log_str = log.to_string_lossy().into_owned();
139 let file = match File::open(log) {
140 Ok(file) => file,
141 Err(err) if err.kind() == ErrorKind::NotFound => {
142 return Ok(Report {
143 generated_at: now,
144 since,
145 log: log_str,
146 log_exists: false,
147 unreadable_lines: 0,
148 totals: Group::default(),
149 by_day: Vec::new(),
150 by_kind: Vec::new(),
151 by_surface: Vec::new(),
152 by_repo: Vec::new(),
153 by_model: Vec::new(),
154 });
155 }
156 Err(err) => {
157 return Err(format!("failed to open {}: {err}", log.display()));
158 }
159 };
160
161 let reader = BufReader::new(file);
162 let mut unreadable_lines = 0u64;
163 let mut totals = Group::default();
164 let mut day_map: HashMap<String, Group> = HashMap::new();
165 let mut kind_map: HashMap<&'static str, Group> = HashMap::new();
166 let mut surface_map: HashMap<Option<String>, SurfaceAcc> = HashMap::new();
167 let mut repo_map: HashMap<String, Group> = HashMap::new();
168 let mut model_map: HashMap<String, Group> = HashMap::new();
169
170 for line_res in reader.lines() {
171 let line = line_res.map_err(|err| format!("failed to read {}: {err}", log.display()))?;
172 let trimmed = line.trim();
173 if trimmed.is_empty() {
174 continue;
175 }
176 let Ok(entry) = serde_json::from_str::<usage_log::Entry>(trimmed) else {
177 unreadable_lines += 1;
178 continue;
179 };
180 if let Some(min_ts) = since {
181 if entry.ts < min_ts {
182 continue;
183 }
184 }
185
186 totals.add(&entry);
187 day_map.entry(utc_day(entry.ts)).or_default().add(&entry);
188 kind_map.entry(kind_of(&entry)).or_default().add(&entry);
189
190 let surface_acc = surface_map
191 .entry(entry.surface.clone())
192 .or_insert_with(|| SurfaceAcc {
193 group: Group::default(),
194 last_ts: entry.ts,
195 latest_name: None,
196 });
197 surface_acc.group.add(&entry);
198 if entry.ts > surface_acc.last_ts {
199 surface_acc.last_ts = entry.ts;
200 }
201 if entry.surface.is_some() {
202 if let Some(name) = entry.surface_name.as_deref() {
203 let replace = match &surface_acc.latest_name {
204 None => true,
205 Some((prev_ts, _)) => entry.ts >= *prev_ts,
206 };
207 if replace {
208 surface_acc.latest_name = Some((entry.ts, name.to_string()));
209 }
210 }
211 }
212
213 repo_map.entry(entry.repo.clone()).or_default().add(&entry);
214 model_map
215 .entry(entry.model.clone())
216 .or_default()
217 .add(&entry);
218 }
219
220 let mut by_day: Vec<DayRow> = day_map
221 .into_iter()
222 .map(|(day, group)| DayRow { day, group })
223 .collect();
224 by_day.sort_by(|a, b| a.day.cmp(&b.day));
225
226 let mut by_kind: Vec<KindRow> = kind_map
227 .into_iter()
228 .map(|(kind, group)| KindRow {
229 kind: kind.to_string(),
230 group,
231 })
232 .collect();
233 by_kind.sort_by(|a, b| {
234 b.group
235 .cost_usd
236 .total_cmp(&a.group.cost_usd)
237 .then_with(|| a.kind.cmp(&b.kind))
238 });
239
240 let mut by_surface: Vec<SurfaceRow> = surface_map
241 .into_iter()
242 .map(|(surface, acc)| SurfaceRow {
243 surface,
244 name: acc.latest_name.map(|(_, name)| name),
245 last_ts: acc.last_ts,
246 group: acc.group,
247 })
248 .collect();
249 by_surface.sort_by(|a, b| {
250 b.group
251 .cost_usd
252 .total_cmp(&a.group.cost_usd)
253 .then_with(|| cmp_surface_key(a.surface.as_deref(), b.surface.as_deref()))
254 });
255
256 let mut by_repo: Vec<RepoRow> = repo_map
257 .into_iter()
258 .map(|(repo, group)| RepoRow { repo, group })
259 .collect();
260 by_repo.sort_by(|a, b| {
261 b.group
262 .cost_usd
263 .total_cmp(&a.group.cost_usd)
264 .then_with(|| a.repo.cmp(&b.repo))
265 });
266
267 let mut by_model: Vec<ModelRow> = model_map
268 .into_iter()
269 .map(|(model, group)| ModelRow { model, group })
270 .collect();
271 by_model.sort_by(|a, b| {
272 b.group
273 .cost_usd
274 .total_cmp(&a.group.cost_usd)
275 .then_with(|| a.model.cmp(&b.model))
276 });
277
278 Ok(Report {
279 generated_at: now,
280 since,
281 log: log_str,
282 log_exists: true,
283 unreadable_lines,
284 totals,
285 by_day,
286 by_kind,
287 by_surface,
288 by_repo,
289 by_model,
290 })
291}