cc-token-usage 3.1.0

Analyze Claude Code session token usage, costs, and efficiency
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
use std::fmt::Write as _;

use chrono::{Datelike, NaiveDate};

use crate::analysis::heatmap::HeatmapResult;
use crate::analysis::validate::ValidationReport;
use crate::analysis::wrapped::WrappedResult;
use crate::analysis::{OverviewResult, ProjectResult, SessionResult, TrendResult};
use crate::pricing::calculator::PricingCalculator;

// ─── Helpers ────────────────────────────────────────────────────────────────

fn format_number(n: u64) -> String {
    let s = n.to_string();
    let mut result = String::with_capacity(s.len() + s.len() / 3);
    for (i, ch) in s.chars().rev().enumerate() {
        if i > 0 && i % 3 == 0 {
            result.push(',');
        }
        result.push(ch);
    }
    result.chars().rev().collect()
}

fn format_cost(c: f64) -> String {
    let abs = c.abs();
    let total_cents = (abs * 100.0).round() as u64;
    let whole = total_cents / 100;
    let cents = total_cents % 100;
    let sign = if c < 0.0 { "-" } else { "" };
    format!("{}${}.{:02}", sign, format_number(whole), cents)
}

fn format_duration(minutes: f64) -> String {
    if minutes < 1.0 {
        format!("{:.0}s", minutes * 60.0)
    } else if minutes < 60.0 {
        format!("{:.0}m", minutes)
    } else {
        let h = (minutes / 60.0).floor();
        let m = (minutes % 60.0).round();
        format!("{:.0}h{:.0}m", h, m)
    }
}

// ─── 1. Overview ────────────────────────────────────────────────────────────

pub fn render_overview(result: &OverviewResult, calc: &PricingCalculator) -> String {
    let mut out = String::new();
    let _ = calc;

    let range = result
        .quality
        .time_range
        .map(|(s, e)| {
            let ls = s.with_timezone(&chrono::Local);
            let le = e.with_timezone(&chrono::Local);
            format!("{} ~ {}", ls.format("%Y-%m-%d"), le.format("%Y-%m-%d"))
        })
        .unwrap_or_default();

    writeln!(out, "Claude Code Token Report").unwrap();
    writeln!(out, "{}", range).unwrap();
    writeln!(out).unwrap();

    writeln!(
        out,
        "  {} conversations, {} rounds of back-and-forth",
        format_number(result.total_sessions as u64),
        format_number(result.total_turns as u64)
    )
    .unwrap();
    if result.total_agent_turns > 0 {
        writeln!(
            out,
            "  ({} agent turns, {:.0}% of total)",
            format_number(result.total_agent_turns as u64),
            result.total_agent_turns as f64 / result.total_turns.max(1) as f64 * 100.0
        )
        .unwrap();
    }
    writeln!(out).unwrap();

    writeln!(
        out,
        "  Claude read  {} tokens",
        format_number(result.total_context_tokens)
    )
    .unwrap();
    writeln!(
        out,
        "  Claude wrote {} tokens",
        format_number(result.total_output_tokens)
    )
    .unwrap();
    writeln!(out).unwrap();

    writeln!(
        out,
        "  Cache saved you {} ({:.0}% of reads were free)",
        format_cost(result.cache_savings.total_saved),
        result.cache_savings.savings_pct
    )
    .unwrap();
    writeln!(
        out,
        "  All that would cost {} at API rates",
        format_cost(result.total_cost)
    )
    .unwrap();

    // Subscription value
    if let Some(ref sub) = result.subscription_value {
        writeln!(
            out,
            "  Subscription: {}/mo -> {:.1}x value multiplier",
            format_cost(sub.monthly_price),
            sub.value_multiplier
        )
        .unwrap();
    }

    // Model breakdown
    writeln!(out).unwrap();
    writeln!(
        out,
        "  Model                      Wrote        Rounds     Cost"
    )
    .unwrap();
    writeln!(
        out,
        "  ---------------------------------------------------------"
    )
    .unwrap();

    let mut models: Vec<(&String, &crate::analysis::AggregatedTokens)> =
        result.tokens_by_model.iter().collect();
    models.sort_by(|a, b| {
        let ca = result.cost_by_model.get(a.0).unwrap_or(&0.0);
        let cb = result.cost_by_model.get(b.0).unwrap_or(&0.0);
        cb.partial_cmp(ca).unwrap_or(std::cmp::Ordering::Equal)
    });

    for (model, tokens) in &models {
        let cost = result.cost_by_model.get(*model).unwrap_or(&0.0);
        let short = short_model(model);
        writeln!(
            out,
            "  {:<25} {:>10} {:>9} {:>9}",
            short,
            format_number(tokens.output_tokens),
            format_number(tokens.turns as u64),
            format_cost(*cost)
        )
        .unwrap();
    }

    // Cost by category
    writeln!(out).unwrap();
    let cat = &result.cost_by_category;
    let total = result.total_cost.max(0.001);
    writeln!(out, "  Cost Breakdown").unwrap();
    writeln!(
        out,
        "    Output:      {:>9}  ({:.0}%)",
        format_cost(cat.output_cost),
        cat.output_cost / total * 100.0
    )
    .unwrap();
    writeln!(
        out,
        "    Cache Write: {:>9}  ({:.0}%)",
        format_cost(cat.cache_write_5m_cost + cat.cache_write_1h_cost),
        (cat.cache_write_5m_cost + cat.cache_write_1h_cost) / total * 100.0
    )
    .unwrap();
    writeln!(
        out,
        "    Input:       {:>9}  ({:.0}%)",
        format_cost(cat.input_cost),
        cat.input_cost / total * 100.0
    )
    .unwrap();
    writeln!(
        out,
        "    Cache Read:  {:>9}  ({:.0}%)",
        format_cost(cat.cache_read_cost),
        cat.cache_read_cost / total * 100.0
    )
    .unwrap();

    // Efficiency metrics
    writeln!(out).unwrap();
    writeln!(out, "  Efficiency").unwrap();
    writeln!(
        out,
        "    Output ratio:       {:.2}% ({} output / {} input)",
        result.output_ratio,
        format_number(result.total_output_tokens),
        format_number(result.total_context_tokens)
    )
    .unwrap();
    writeln!(
        out,
        "    Cost per turn:      ${:.3}/turn",
        result.cost_per_turn
    )
    .unwrap();
    writeln!(
        out,
        "    Output per turn:    {} tokens/turn avg",
        format_number(result.tokens_per_output_turn)
    )
    .unwrap();

    // Tool usage top 10
    if !result.tool_counts.is_empty() {
        writeln!(out).unwrap();
        writeln!(out, "  Top Tools").unwrap();
        for (name, count) in result.tool_counts.iter().take(10) {
            let bar_len =
                (*count as f64 / result.tool_counts[0].1.max(1) as f64 * 20.0).round() as usize;
            writeln!(
                out,
                "    {:<18} {:>6}  {}",
                name,
                format_number(*count as u64),
                "".repeat(bar_len)
            )
            .unwrap();
        }
    }

    // Top 5 projects
    if !result.session_summaries.is_empty() {
        writeln!(out).unwrap();
        writeln!(
            out,
            "  Top Projects                              Sessions   Turns    Cost"
        )
        .unwrap();
        writeln!(
            out,
            "  -------------------------------------------------------------------"
        )
        .unwrap();

        let mut project_map: std::collections::HashMap<&str, (usize, usize, f64)> =
            std::collections::HashMap::new();
        for s in &result.session_summaries {
            let e = project_map.entry(&s.project_display_name).or_default();
            e.0 += 1;
            e.1 += s.turn_count;
            e.2 += s.cost;
        }
        let mut projects: Vec<_> = project_map.into_iter().collect();
        projects.sort_by(|a, b| {
            b.1 .2
                .partial_cmp(&a.1 .2)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        for (name, (sessions, turns, cost)) in projects.iter().take(5) {
            writeln!(
                out,
                "  {:<40} {:>5} {:>7} {:>9}",
                name,
                sessions,
                turns,
                format_cost(*cost)
            )
            .unwrap();
        }
    }

    // Usage insights
    if !result.session_summaries.is_empty() {
        let summaries = &result.session_summaries;

        // Daily average cost
        if let Some((start, end)) = result.quality.time_range {
            let days = (end - start).num_days().max(1) as f64;
            writeln!(out).unwrap();
            writeln!(
                out,
                "  Daily avg: {} / day  ({} days)",
                format_cost(result.total_cost / days),
                days as u64
            )
            .unwrap();
        }

        // Compaction stats
        let total_compactions: usize = summaries.iter().map(|s| s.compaction_count).sum();
        let sessions_with_compaction = summaries.iter().filter(|s| s.compaction_count > 0).count();
        if total_compactions > 0 {
            writeln!(
                out,
                "  Compactions: {} total across {} sessions",
                total_compactions, sessions_with_compaction
            )
            .unwrap();
        }

        // Max context
        let max_ctx = summaries.iter().map(|s| s.max_context).max().unwrap_or(0);
        if max_ctx > 0 {
            writeln!(out, "  Peak context: {} tokens", format_number(max_ctx)).unwrap();
        }

        // Average session duration
        let durations: Vec<f64> = summaries
            .iter()
            .map(|s| s.duration_minutes)
            .filter(|d| *d > 0.0)
            .collect();
        if !durations.is_empty() {
            let avg_dur = durations.iter().sum::<f64>() / durations.len() as f64;
            writeln!(out, "  Avg session: {}", format_duration(avg_dur)).unwrap();
        }

        // Top 3 most expensive sessions
        let mut by_cost: Vec<&crate::analysis::SessionSummary> = summaries.iter().collect();
        by_cost.sort_by(|a, b| {
            b.cost
                .partial_cmp(&a.cost)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        writeln!(out).unwrap();
        writeln!(out, "  Most Expensive Sessions").unwrap();
        for s in by_cost.iter().take(3) {
            let dur = format_duration(s.duration_minutes);
            writeln!(
                out,
                "    {} {} {:>5} turns  {}  {}",
                &s.session_id[..s.session_id.len().min(8)],
                truncate_str(&s.project_display_name, 25),
                s.turn_count,
                dur,
                format_cost(s.cost),
            )
            .unwrap();
        }
    }

    // Data quality summary
    writeln!(out).unwrap();
    writeln!(
        out,
        "  Data: {} session files, {} agent files",
        result.quality.total_session_files, result.quality.total_agent_files
    )
    .unwrap();
    if result.quality.orphan_agents > 0 {
        writeln!(
            out,
            "  ({} orphan agents without parent session)",
            result.quality.orphan_agents
        )
        .unwrap();
    }
    // Surface orphan sessions (parent jsonl deleted, subagents still on disk).
    // Their cost / turns / tokens are already included in the totals above —
    // this line just makes the count visible.
    let orphan_session_count = result
        .session_summaries
        .iter()
        .filter(|s| s.is_orphan)
        .count();
    if orphan_session_count > 0 {
        writeln!(
            out,
            "  Orphaned subagents detected: {} (still counted in totals)",
            orphan_session_count
        )
        .unwrap();
    }

    // Pricing fallback warnings — surfaced last so they're not buried.
    if !result.pricing_warnings.is_empty() {
        writeln!(out).unwrap();
        writeln!(
            out,
            "! Pricing fallback ({} unknown model{})",
            result.pricing_warnings.len(),
            if result.pricing_warnings.len() == 1 {
                ""
            } else {
                "s"
            }
        )
        .unwrap();
        for w in &result.pricing_warnings {
            writeln!(
                out,
                "  \u{00b7} {}: {} turns, {} \u{2014} used {} pricing",
                w.unknown_model,
                format_number(w.turn_count),
                format_cost(w.fallback_cost),
                w.fallback_to
            )
            .unwrap();
        }
        writeln!(
            out,
            "  These costs are estimates. Update the pricing table when actual rates are known."
        )
        .unwrap();
    }

    writeln!(out).unwrap();

    out
}

fn short_model(name: &str) -> String {
    let s = name.strip_prefix("claude-").unwrap_or(name);
    if s.len() > 9 {
        let last_dash = s.rfind('-').unwrap_or(s.len());
        let suffix = &s[last_dash + 1..];
        if suffix.len() == 8 && suffix.chars().all(|c| c.is_ascii_digit()) {
            return s[..last_dash].to_string();
        }
    }
    s.to_string()
}

// ─── 2. Projects ────────────────────────────────────────────────────────────

pub fn render_projects(result: &ProjectResult) -> String {
    let mut out = String::new();
    let mut total_cost = 0.0f64;

    writeln!(out, "Projects by Cost").unwrap();
    writeln!(out).unwrap();
    writeln!(out, "  #   Project                          Sessions  Turns  Agent  $/Sess  Model          Cost").unwrap();
    writeln!(out, "  ─────────────────────────────────────────────────────────────────────────────────────────").unwrap();

    for (i, proj) in result.projects.iter().enumerate() {
        let avg_cost = if proj.session_count > 0 {
            proj.cost / proj.session_count as f64
        } else {
            0.0
        };
        let model_short = short_model(&proj.primary_model);
        writeln!(
            out,
            "  {:>2}. {:<30} {:>5}  {:>6}  {:>5}  {:>6}  {:<12}  {:>9}",
            i + 1,
            truncate_str(&proj.display_name, 30),
            proj.session_count,
            proj.total_turns,
            proj.agent_turns,
            format_cost(avg_cost),
            truncate_str(&model_short, 12),
            format_cost(proj.cost),
        )
        .unwrap();
        total_cost += proj.cost;
    }

    writeln!(out).unwrap();
    writeln!(
        out,
        "  Total: {} projects, {}",
        result.projects.len(),
        format_cost(total_cost)
    )
    .unwrap();
    out
}

fn truncate_str(s: &str, max: usize) -> String {
    if s.len() <= max {
        s.to_string()
    } else {
        format!("{}...", &s[..s.floor_char_boundary(max.saturating_sub(3))])
    }
}

// ─── 3. Session ─────────────────────────────────────────────────────────────

pub fn render_session(result: &SessionResult) -> String {
    let mut out = String::new();

    let main_turns = result.turn_details.iter().filter(|t| !t.is_agent).count();

    let orphan_tag = if result.is_orphan { " [orphan]" } else { "" };
    writeln!(
        out,
        "Session {}  {}{}",
        &result.session_id[..result.session_id.len().min(8)],
        result.project,
        orphan_tag
    )
    .unwrap();
    writeln!(out).unwrap();
    writeln!(
        out,
        "  Turns:     {:>6} (+ {} agent)   Duration: {}",
        main_turns,
        result.agent_summary.total_agent_turns,
        format_duration(result.duration_minutes)
    )
    .unwrap();
    writeln!(
        out,
        "  Model:     {:<20}  MaxCtx:   {}",
        result.model,
        format_number(result.max_context)
    )
    .unwrap();
    writeln!(
        out,
        "  CacheHit:  {:>5.1}%                Compacts: {}",
        result.total_tokens.cache_read_tokens as f64
            / result.total_tokens.context_tokens().max(1) as f64
            * 100.0,
        result.compaction_count
    )
    .unwrap();
    writeln!(out, "  Cost:      {}", format_cost(result.total_cost)).unwrap();

    // ── Metadata section ──
    let has_metadata = result.title.is_some()
        || !result.tags.is_empty()
        || result.mode.is_some()
        || !result.git_branches.is_empty()
        || !result.pr_links.is_empty();

    if has_metadata {
        writeln!(out).unwrap();
        writeln!(out, "  ── Metadata ──────────────────────────────────").unwrap();
        if let Some(ref title) = result.title {
            writeln!(out, "  Title:        {}", truncate_str(title, 60)).unwrap();
        }
        if !result.tags.is_empty() {
            writeln!(out, "  Tags:         {}", result.tags.join(", ")).unwrap();
        }
        if let Some(ref mode) = result.mode {
            writeln!(out, "  Mode:         {}", mode).unwrap();
        }
        if !result.git_branches.is_empty() {
            let mut branches: Vec<_> = result.git_branches.iter().collect();
            branches.sort_by(|a, b| b.1.cmp(a.1));
            let parts: Vec<String> = branches
                .iter()
                .map(|(name, count)| format!("{} ({} turns)", name, count))
                .collect();
            writeln!(out, "  Branch:       {}", parts.join(", ")).unwrap();
        }
        for pr in &result.pr_links {
            writeln!(out, "  PR:           {}#{}", pr.repository, pr.number).unwrap();
        }
    }

    // ── Performance section ──
    let has_performance = result.user_prompt_count > 0
        || result.truncated_count > 0
        || result.speculation_accepts > 0
        || !result.service_tiers.is_empty()
        || !result.speeds.is_empty()
        || !result.inference_geos.is_empty()
        || result.api_error_count > 0
        || result.tool_error_count > 0;

    if has_performance {
        writeln!(out).unwrap();
        writeln!(out, "  ── Performance ───────────────────────────────").unwrap();
        if result.user_prompt_count > 0 {
            let total_turns = result.turn_details.len();
            writeln!(
                out,
                "  Autonomy:     1:{:.1} ({} turns / {} user prompts)",
                result.autonomy_ratio, total_turns, result.user_prompt_count
            )
            .unwrap();
        }
        if result.truncated_count > 0 {
            writeln!(
                out,
                "  Truncated:    {} turns hit max_tokens",
                result.truncated_count
            )
            .unwrap();
        }
        if result.api_error_count > 0 || result.tool_error_count > 0 {
            let mut parts = Vec::new();
            if result.api_error_count > 0 {
                parts.push(format!("{} API errors", result.api_error_count));
            }
            if result.tool_error_count > 0 {
                parts.push(format!("{} tool errors", result.tool_error_count));
            }
            writeln!(out, "  Errors:       {}", parts.join(", ")).unwrap();
        }
        if result.speculation_accepts > 0 {
            let saved_secs = result.speculation_time_saved_ms / 1000.0;
            writeln!(
                out,
                "  Speculation:  saved {:.1}s across {} accepts",
                saved_secs, result.speculation_accepts
            )
            .unwrap();
        }
        if !result.service_tiers.is_empty() {
            let total: usize = result.service_tiers.values().sum();
            let mut tiers: Vec<_> = result.service_tiers.iter().collect();
            tiers.sort_by(|a, b| b.1.cmp(a.1));
            let parts: Vec<String> = tiers
                .iter()
                .map(|(name, count)| {
                    format!("{} ({:.0}%)", name, **count as f64 / total as f64 * 100.0)
                })
                .collect();
            writeln!(out, "  Service:      {}", parts.join(", ")).unwrap();
        }
        if !result.speeds.is_empty() {
            let total: usize = result.speeds.values().sum();
            let mut spds: Vec<_> = result.speeds.iter().collect();
            spds.sort_by(|a, b| b.1.cmp(a.1));
            let parts: Vec<String> = spds
                .iter()
                .map(|(name, count)| {
                    format!("{} ({:.0}%)", name, **count as f64 / total as f64 * 100.0)
                })
                .collect();
            writeln!(out, "  Speed:        {}", parts.join(", ")).unwrap();
        }
        if !result.inference_geos.is_empty() {
            let total: usize = result.inference_geos.values().sum();
            let mut geos: Vec<_> = result.inference_geos.iter().collect();
            geos.sort_by(|a, b| b.1.cmp(a.1));
            let parts: Vec<String> = geos
                .iter()
                .map(|(name, count)| {
                    format!("{} ({:.0}%)", name, **count as f64 / total as f64 * 100.0)
                })
                .collect();
            writeln!(out, "  Geo:          {}", parts.join(", ")).unwrap();
        }
    }

    // Per-agent breakdown
    if !result.agent_summary.agents.is_empty() {
        writeln!(out).unwrap();
        writeln!(out, "  Agent Breakdown").unwrap();
        writeln!(
            out,
            "  {:<14} {:<40} {:>6} {:>10} {:>9}",
            "Type", "Description", "Turns", "Output", "Cost"
        )
        .unwrap();
        writeln!(out, "  {}", "-".repeat(83)).unwrap();

        // Main agent line
        let main_turns = result.turn_details.iter().filter(|t| !t.is_agent).count();
        let main_output: u64 = result
            .turn_details
            .iter()
            .filter(|t| !t.is_agent)
            .map(|t| t.output_tokens)
            .sum();
        let main_cost = result.total_cost - result.agent_summary.agent_cost;
        writeln!(
            out,
            "  {:<14} {:<40} {:>6} {:>10} {:>9}",
            "main",
            "(this conversation)",
            main_turns,
            format_number(main_output),
            format_cost(main_cost)
        )
        .unwrap();

        for agent in &result.agent_summary.agents {
            let desc = if agent.description.len() > 40 {
                format!(
                    "{}...",
                    &agent.description[..agent.description.floor_char_boundary(37)]
                )
            } else {
                agent.description.clone()
            };
            writeln!(
                out,
                "  {:<14} {:<40} {:>6} {:>10} {:>9}",
                agent.agent_type,
                desc,
                agent.turns,
                format_number(agent.output_tokens),
                format_cost(agent.cost),
            )
            .unwrap();
        }
    }

    // ── Context Collapse section ──
    if result.collapse_count > 0 {
        writeln!(out).unwrap();
        writeln!(out, "  ── Context Collapse ──────────────────────────").unwrap();

        let risk_warning = if result.collapse_max_risk > 0.5 {
            " \u{26a0}"
        } else {
            ""
        };
        writeln!(
            out,
            "  Collapses:    {} (avg risk: {:.2}, max: {:.2}{})",
            result.collapse_count, result.collapse_avg_risk, result.collapse_max_risk, risk_warning
        )
        .unwrap();

        if !result.collapse_summaries.is_empty() {
            writeln!(out, "  Summaries:").unwrap();
            for (i, summary) in result.collapse_summaries.iter().enumerate() {
                // Determine per-summary risk from snapshot staged spans if available
                // We don't have per-commit risk, so just show the summary text
                // Mark if max_risk > 0.5 for the last entry (heuristic)
                let display = truncate_str(summary, 60);
                writeln!(out, "    {}. \"{}\"", i + 1, display).unwrap();
            }
        }
    }

    // ── Phase 2: session-level capability inventory ──
    // Each row only renders when its data is non-empty (mirrors how metadata
    // rows are gated). Old sessions (pre-2.1.104/2.1.138) emit nothing here.

    // Subagent chips: group by `agent_type` so a session with 7 builder calls
    // renders one chip `builder x 7 ($X.YY)` rather than seven per-agent_id
    // chips. `subagent_types` is empty exactly when `subagents` is.
    if !result.subagent_types.is_empty() {
        let parts: Vec<String> = result
            .subagent_types
            .iter()
            .map(|agg| {
                format!(
                    "{} x {} ({})",
                    agg.agent_type,
                    agg.count,
                    format_cost(agg.total_cost)
                )
            })
            .collect();
        writeln!(out).unwrap();
        writeln!(out, "  Subagents: {}", parts.join(" | ")).unwrap();
    }

    if !result.plugins.is_empty() {
        let parts: Vec<String> = result
            .plugins
            .iter()
            .map(|p| format!("{} ({} turns, {})", p.plugin, p.turns, format_cost(p.cost)))
            .collect();
        writeln!(out, "  Plugins:   {}", parts.join(" | ")).unwrap();
    }

    if !result.skills.is_empty() {
        let parts: Vec<String> = result
            .skills
            .iter()
            .map(|s| format!("{} ({} turns, {})", s.skill, s.turns, format_cost(s.cost)))
            .collect();
        writeln!(out, "  Skills:    {}", parts.join(" | ")).unwrap();
    }

    if !result.hooks.is_empty() {
        let parts: Vec<String> = result
            .hooks
            .iter()
            .map(|h| {
                format!(
                    "{} ({} invocations, {} ms total)",
                    h.command, h.invocations, h.total_duration_ms
                )
            })
            .collect();
        writeln!(out, "  Hooks:     {}", parts.join(" | ")).unwrap();
    }

    // ── Workflow runs section (Claude Code 2.1.159+) ──
    // One block per `agent()` orchestration run discovered for this session.
    // Shows the declared snapshot metadata alongside the measured (parsed)
    // token/cost/agent totals so any drift is visible at a glance.
    if !result.workflows.is_empty() {
        writeln!(out).unwrap();
        writeln!(out, "  ── Workflows ─────────────────────────────────").unwrap();
        for wf in &result.workflows {
            let name = wf.workflow_name.as_deref().unwrap_or(&wf.run_id);
            let status = wf.status.as_deref().unwrap_or("?");
            writeln!(out, "  {} [{}]", name, status).unwrap();
            writeln!(
                out,
                "    agents: {} | turns: {} | output: {} tok | cost: {}",
                wf.parsed_agent_count,
                wf.parsed_turns,
                format_number(wf.parsed_output_tokens),
                format_cost(wf.parsed_cost)
            )
            .unwrap();
            if let Some(snap_tokens) = wf.snapshot_total_tokens {
                writeln!(
                    out,
                    "    snapshot: {} tok reported{}",
                    format_number(snap_tokens),
                    wf.snapshot_duration_ms
                        .map(|d| format!(", {} ms", format_number(d)))
                        .unwrap_or_default()
                )
                .unwrap();
            }
            for phase in &wf.phases {
                if let Some(title) = phase.title.as_deref().filter(|t| !t.is_empty()) {
                    writeln!(out, "{}", title).unwrap();
                }
            }
        }
    }

    // ── Code Attribution section ──
    if let Some(ref attr) = result.attribution {
        writeln!(out).unwrap();
        writeln!(out, "  ── Code Attribution ──────────────────────────").unwrap();
        writeln!(out, "  Files touched:     {}", attr.file_count).unwrap();
        writeln!(
            out,
            "  Claude wrote:      {} chars",
            format_number(attr.total_claude_contribution)
        )
        .unwrap();
        if let Some(prompts) = attr.prompt_count {
            let escape_str = attr
                .escape_count
                .filter(|&e| e > 0)
                .map(|e| format!(" ({} escaped)", e))
                .unwrap_or_default();
            writeln!(out, "  Prompts:           {}{}", prompts, escape_str).unwrap();
        }
        if let Some(perms) = attr.permission_prompt_count {
            if perms > 0 {
                writeln!(out, "  Permissions:       {} prompts shown", perms).unwrap();
            }
        }
    }

    out
}

// ─── 4. Trend ───────────────────────────────────────────────────────────────

pub fn render_trend(result: &TrendResult) -> String {
    let mut out = String::new();
    let mut total_cost = 0.0f64;
    let mut total_turns = 0usize;

    // Find max cost for sparkline scaling
    let max_cost = result.entries.iter().map(|e| e.cost).fold(0.0f64, f64::max);

    writeln!(out, "Usage by {}", result.group_label).unwrap();
    writeln!(out).unwrap();

    for entry in &result.entries {
        // Sparkline bar
        let bar_len = if max_cost > 0.0 {
            (entry.cost / max_cost * 16.0).round() as usize
        } else {
            0
        };
        let bar = "▇".repeat(bar_len);

        // Primary model for this period
        let top_model = entry
            .models
            .iter()
            .max_by_key(|(_, tokens)| *tokens)
            .map(|(m, _)| short_model(m))
            .unwrap_or_default();

        // Cost per turn
        let cpt = if entry.turn_count > 0 {
            entry.cost / entry.turn_count as f64
        } else {
            0.0
        };

        writeln!(
            out,
            "  {:<10}  {:>4} sess  {:>6} turns  {:>9}  ${:.3}/t  {:<12} {}",
            entry.label,
            entry.session_count,
            entry.turn_count,
            format_cost(entry.cost),
            cpt,
            truncate_str(&top_model, 12),
            bar,
        )
        .unwrap();
        total_cost += entry.cost;
        total_turns += entry.turn_count;
    }

    writeln!(out).unwrap();
    let avg_cpt = if total_turns > 0 {
        total_cost / total_turns as f64
    } else {
        0.0
    };
    writeln!(
        out,
        "  Total: {}  ({} turns, avg ${:.3}/turn)",
        format_cost(total_cost),
        format_number(total_turns as u64),
        avg_cpt
    )
    .unwrap();
    out
}

pub fn render_validation(report: &ValidationReport, failures_only: bool) -> String {
    let mut out = String::new();

    writeln!(out, "Token Validation Report").unwrap();
    writeln!(out, "{}", "".repeat(60)).unwrap();
    writeln!(out).unwrap();

    // Structure checks
    writeln!(out, "Structure Checks:").unwrap();
    for check in &report.structure_checks {
        if failures_only && check.passed {
            continue;
        }
        let status = if check.passed { "OK" } else { "FAIL" };
        if check.passed {
            writeln!(out, "  [{:>4}] {}: {}", status, check.name, check.actual).unwrap();
        } else {
            writeln!(
                out,
                "  [{:>4}] {}: expected={}, actual={}",
                status, check.name, check.expected, check.actual
            )
            .unwrap();
        }
    }
    writeln!(out).unwrap();

    // Per-session results
    let mut fail_sessions = Vec::new();
    for sv in &report.session_results {
        let all_checks: Vec<_> = sv
            .token_checks
            .iter()
            .chain(sv.agent_checks.iter())
            .collect();
        let has_failures = all_checks.iter().any(|c| !c.passed);

        if failures_only && !has_failures {
            continue;
        }

        if has_failures {
            fail_sessions.push(sv);
        }
    }

    if !failures_only {
        writeln!(
            out,
            "Session Validation: {} sessions checked",
            report.session_results.len()
        )
        .unwrap();
        let sessions_ok = report.summary.sessions_passed;
        let sessions_fail = report.summary.sessions_validated - sessions_ok;
        writeln!(out, "  {} PASS, {} FAIL", sessions_ok, sessions_fail).unwrap();
        writeln!(out).unwrap();
    }

    // Show failed sessions in detail
    if !fail_sessions.is_empty() {
        writeln!(out, "Failed Sessions:").unwrap();
        writeln!(out).unwrap();
    }
    for sv in &fail_sessions {
        writeln!(
            out,
            "  Session {}  {}",
            &sv.session_id[..8.min(sv.session_id.len())],
            sv.project
        )
        .unwrap();
        for check in sv.token_checks.iter().chain(sv.agent_checks.iter()) {
            if !check.passed {
                writeln!(
                    out,
                    "    [FAIL] {}: expected={}, actual={}",
                    check.name, check.expected, check.actual
                )
                .unwrap();
            }
        }
        writeln!(out).unwrap();
    }

    // Summary
    writeln!(out, "{}", "".repeat(60)).unwrap();
    let result_text = if report.summary.failed == 0 {
        "PASS"
    } else {
        "FAIL"
    };
    writeln!(
        out,
        "Result: {} ({}/{} checks passed, {} sessions validated)",
        result_text,
        report.summary.passed,
        report.summary.total_checks,
        report.summary.sessions_validated,
    )
    .unwrap();

    out
}

// ─── 5. Wrapped ────────────────────────────────────────────────────────────

pub fn render_wrapped(result: &WrappedResult) -> String {
    let mut out = String::new();
    let w = 50; // inner width

    // Top border
    writeln!(out, "\u{2554}{}\u{2557}", "\u{2550}".repeat(w)).unwrap();
    let title = format!("Your {} Claude Code Wrapped", result.year);
    let pad = (w.saturating_sub(title.len())) / 2;
    writeln!(
        out,
        "\u{2551}{}{}{}\u{2551}",
        " ".repeat(pad),
        title,
        " ".repeat(w.saturating_sub(pad + title.len()))
    )
    .unwrap();
    writeln!(out, "\u{2560}{}\u{2563}", "\u{2550}".repeat(w)).unwrap();
    writeln!(out).unwrap();

    // Activity
    let active_pct = if result.total_days > 0 {
        result.active_days as f64 / result.total_days as f64 * 100.0
    } else {
        0.0
    };
    writeln!(
        out,
        "  Active Days:      {} / {} ({:.0}%)",
        result.active_days, result.total_days, active_pct
    )
    .unwrap();
    writeln!(out, "  Longest Streak:   {} days", result.longest_streak).unwrap();
    writeln!(out, "  Ghost Days:       {}", result.ghost_days).unwrap();
    writeln!(out).unwrap();

    // Volume
    writeln!(
        out,
        "  {} sessions, {} turns",
        format_number(result.total_sessions as u64),
        format_number(result.total_turns as u64)
    )
    .unwrap();
    if result.total_agent_turns > 0 {
        let agent_pct = result.total_agent_turns as f64 / result.total_turns.max(1) as f64 * 100.0;
        writeln!(
            out,
            "  {} agent turns ({:.0}% autonomous)",
            format_number(result.total_agent_turns as u64),
            agent_pct
        )
        .unwrap();
    }
    writeln!(out, "  {} API equivalent", format_cost(result.total_cost)).unwrap();
    writeln!(out).unwrap();

    // Archetype
    writeln!(
        out,
        "  Developer Archetype: \"{}\"",
        result.archetype.label()
    )
    .unwrap();
    writeln!(out, "  {}", result.archetype.description()).unwrap();
    writeln!(out).unwrap();

    // Peak patterns
    writeln!(
        out,
        "  Peak Hour:    {:02}:00-{:02}:00",
        result.peak_hour,
        (result.peak_hour + 1) % 24
    )
    .unwrap();
    writeln!(out, "  Peak Day:     {}", result.peak_weekday).unwrap();
    writeln!(out).unwrap();

    // Efficiency
    if result.autonomy_ratio > 0.0 {
        writeln!(
            out,
            "  Autonomy:     1:{:.1} (turns per user prompt)",
            result.autonomy_ratio
        )
        .unwrap();
    }
    if result.avg_session_duration_min > 0.0 {
        writeln!(
            out,
            "  Avg Session:  {}",
            format_duration(result.avg_session_duration_min)
        )
        .unwrap();
    }
    writeln!(
        out,
        "  Avg Cost:     {}/session",
        format_cost(result.avg_cost_per_session)
    )
    .unwrap();
    writeln!(out).unwrap();

    // Top Tools
    if !result.top_tools.is_empty() {
        writeln!(out, "  Top Tools").unwrap();
        let max_count = result.top_tools.first().map(|(_, c)| *c).unwrap_or(1);
        for (name, count) in &result.top_tools {
            let bar_len = (*count as f64 / max_count.max(1) as f64 * 20.0).round() as usize;
            writeln!(
                out,
                "    {:<18} {:>6}  {}",
                name,
                format_number(*count as u64),
                "\u{2588}".repeat(bar_len)
            )
            .unwrap();
        }
        writeln!(out).unwrap();
    }

    // Top Projects
    if !result.top_projects.is_empty() {
        writeln!(out, "  Top Projects").unwrap();
        for (name, cost) in &result.top_projects {
            writeln!(
                out,
                "    {:<30} {}",
                truncate_str(name, 30),
                format_cost(*cost)
            )
            .unwrap();
        }
        writeln!(out).unwrap();
    }

    // Most Expensive Session
    if let Some((ref id, cost, ref project)) = result.most_expensive_session {
        writeln!(out, "  Most Expensive Session").unwrap();
        let short_id = if id.len() > 8 { &id[..8] } else { id };
        writeln!(
            out,
            "    {}  {}  {}",
            short_id,
            truncate_str(project, 25),
            format_cost(cost)
        )
        .unwrap();
        writeln!(out).unwrap();
    }

    // Longest Session
    if let Some((ref id, dur_min, ref project)) = result.longest_session {
        if dur_min > 0.0 {
            writeln!(out, "  Longest Session").unwrap();
            let short_id = if id.len() > 8 { &id[..8] } else { id };
            writeln!(
                out,
                "    {}  {}  {}",
                short_id,
                truncate_str(project, 25),
                format_duration(dur_min)
            )
            .unwrap();
            writeln!(out).unwrap();
        }
    }

    // Model distribution
    if !result.model_distribution.is_empty() {
        writeln!(out, "  Models").unwrap();
        for (model, turns) in &result.model_distribution {
            let short = short_model(model);
            let pct = *turns as f64 / result.total_turns.max(1) as f64 * 100.0;
            writeln!(
                out,
                "    {:<25} {:>6} turns ({:.0}%)",
                short,
                format_number(*turns as u64),
                pct
            )
            .unwrap();
        }
        writeln!(out).unwrap();
    }

    // Metadata footer
    let mut meta_lines: Vec<String> = Vec::new();
    if result.total_speculation_time_saved_ms > 0.0 {
        let saved_sec = result.total_speculation_time_saved_ms / 1000.0;
        if saved_sec >= 60.0 {
            meta_lines.push(format!(
                "  Speculation saved you {:.1} minutes",
                saved_sec / 60.0
            ));
        } else {
            meta_lines.push(format!("  Speculation saved you {:.1} seconds", saved_sec));
        }
    }
    if result.total_pr_count > 0 {
        meta_lines.push(format!(
            "  {} PRs shipped via Claude Code",
            result.total_pr_count
        ));
    }
    if result.total_collapse_count > 0 {
        meta_lines.push(format!(
            "  {} context collapses",
            result.total_collapse_count
        ));
    }
    if !meta_lines.is_empty() {
        for line in &meta_lines {
            writeln!(out, "{}", line).unwrap();
        }
        writeln!(out).unwrap();
    }

    // Bottom border
    writeln!(out, "\u{255a}{}\u{255d}", "\u{2550}".repeat(w)).unwrap();

    out
}

// ─── 6. Heatmap ────────────────────────────────────────────────────────────

pub fn render_heatmap(result: &HeatmapResult) -> String {
    let mut out = String::new();
    let (p25, p50, p75) = result.thresholds;

    writeln!(out, "Activity Heatmap").unwrap();
    writeln!(
        out,
        "{}  ~  {}",
        result.start_date.format("%Y-%m-%d"),
        result.end_date.format("%Y-%m-%d")
    )
    .unwrap();
    writeln!(out).unwrap();

    // Map turns to glyph
    let glyph = |turns: usize| -> char {
        if turns == 0 {
            '\u{00B7}' // middle dot for zero
        } else if turns < p25 {
            '\u{2591}' // light shade
        } else if turns < p50 {
            '\u{2592}' // medium shade
        } else if turns < p75 {
            '\u{2593}' // dark shade
        } else {
            '\u{2588}' // full block
        }
    };

    // Build the calendar grid.
    // Columns = weeks, rows = weekdays (Mon=0 .. Sun=6).
    // Find the Monday on or before start_date to align the grid.
    let start_weekday = result.start_date.weekday().num_days_from_monday(); // 0=Mon
    let grid_start = result.start_date - chrono::Duration::days(start_weekday as i64);

    // End at the Sunday on or after end_date
    let end_weekday = result.end_date.weekday().num_days_from_monday();
    let grid_end = result.end_date + chrono::Duration::days((6 - end_weekday) as i64);

    let total_days = (grid_end - grid_start).num_days() as usize + 1;
    let num_weeks = total_days.div_ceil(7);

    // Build a lookup from date -> turns
    let mut turns_by_date: std::collections::HashMap<NaiveDate, usize> =
        std::collections::HashMap::new();
    for d in &result.daily {
        turns_by_date.insert(d.date, d.turns);
    }

    // Render month labels on top.
    // Each week column is 1 char wide. Month labels ("Jan", etc.) are 3 chars.
    // A label is placed at the week column containing the 1st of that month.
    // Labels that would overlap a previous label are skipped.
    let label_width = 5; // "Mon  " prefix width

    // Collect (week_index, month_abbr) for each month that has its 1st within the grid
    let mut month_marks: Vec<(usize, &str)> = Vec::new();
    {
        // Walk from the first month that starts on or after grid_start
        let mut d = if grid_start.day() == 1 {
            grid_start
        } else {
            // Advance to the 1st of the next month
            let (y, m) = if grid_start.month() == 12 {
                (grid_start.year() + 1, 1)
            } else {
                (grid_start.year(), grid_start.month() + 1)
            };
            NaiveDate::from_ymd_opt(y, m, 1).unwrap_or(grid_start)
        };

        while d <= grid_end {
            let week_idx = ((d - grid_start).num_days() / 7) as usize;
            month_marks.push((week_idx, month_abbr(d.month())));
            // Advance to the 1st of the next month
            d = if d.month() == 12 {
                NaiveDate::from_ymd_opt(d.year() + 1, 1, 1).unwrap()
            } else {
                NaiveDate::from_ymd_opt(d.year(), d.month() + 1, 1).unwrap()
            };
        }
    }

    // Build the header string by placing labels at correct column positions
    let mut month_header = " ".repeat(label_width);
    let mut cursor = 0usize; // tracks how many week-columns we have filled
    for (col, name) in &month_marks {
        if *col >= cursor {
            // Pad with spaces from cursor to this column
            for _ in cursor..*col {
                month_header.push(' ');
            }
            month_header.push_str(name);
            cursor = col + name.len(); // name takes 3 column slots
        }
        // else: skip this label (overlaps with previous)
    }
    writeln!(out, "{}", month_header.trim_end()).unwrap();

    // Render each weekday row (show Mon, Wed, Fri, Sun labels; blank for others)
    let weekday_labels = ["Mon", "   ", "Wed", "   ", "Fri", "   ", "Sun"];

    for row in 0..7u32 {
        let label = weekday_labels[row as usize];
        write!(out, "{:<5}", label).unwrap();

        for week_idx in 0..num_weeks {
            let day = grid_start + chrono::Duration::days((week_idx * 7 + row as usize) as i64);
            if day < result.start_date || day > result.end_date {
                write!(out, " ").unwrap();
            } else {
                let turns = turns_by_date.get(&day).copied().unwrap_or(0);
                write!(out, "{}", glyph(turns)).unwrap();
            }
        }
        writeln!(out).unwrap();
    }

    // Legend
    writeln!(out).unwrap();
    writeln!(
        out,
        "     \u{00B7}=0  \u{2591}<P25({})  \u{2592}<P50({})  \u{2593}<P75({})  \u{2588}\u{2265}P75",
        p25, p50, p75
    )
    .unwrap();

    // Stats
    writeln!(out).unwrap();
    writeln!(
        out,
        "  Active days:     {}/{}",
        result.stats.active_days, result.stats.total_days
    )
    .unwrap();
    writeln!(
        out,
        "  Current streak:  {} days",
        result.stats.current_streak
    )
    .unwrap();
    writeln!(
        out,
        "  Longest streak:  {} days",
        result.stats.longest_streak
    )
    .unwrap();

    if let Some((date, turns)) = result.stats.busiest_day {
        writeln!(
            out,
            "  Busiest day:     {} ({} turns)",
            date.format("%Y-%m-%d"),
            turns
        )
        .unwrap();
    }

    writeln!(out).unwrap();

    out
}

fn month_abbr(m: u32) -> &'static str {
    match m {
        1 => "Jan",
        2 => "Feb",
        3 => "Mar",
        4 => "Apr",
        5 => "May",
        6 => "Jun",
        7 => "Jul",
        8 => "Aug",
        9 => "Sep",
        10 => "Oct",
        11 => "Nov",
        12 => "Dec",
        _ => "???",
    }
}

// ─── Tests ──────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_format_number() {
        assert_eq!(format_number(0), "0");
        assert_eq!(format_number(999), "999");
        assert_eq!(format_number(1_000), "1,000");
        assert_eq!(format_number(1_234_567), "1,234,567");
    }

    #[test]
    fn test_format_cost() {
        assert_eq!(format_cost(0.0), "$0.00");
        assert_eq!(format_cost(1.5), "$1.50");
        assert_eq!(format_cost(1234.56), "$1,234.56");
    }
}