claude-dashboard 0.2.0

A terminal TUI dashboard that renders Claude Code usage reports with token stats, project breakdowns, and language distribution.
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
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;

/// Locate the .claude directory.
/// Checks: CLI override, then env var CLAUDE_DATA_DIR, then ~/.claude.
pub fn find_claude_dir(override_path: Option<&Path>) -> Option<PathBuf> {
    if let Some(p) = override_path {
        if p.exists() {
            return Some(p.to_path_buf());
        }
    }
    if let Ok(val) = std::env::var("CLAUDE_DATA_DIR") {
        let p = PathBuf::from(val);
        if p.exists() {
            return Some(p);
        }
    }
    let home = dirs::home_dir()?;
    let default = home.join(".claude");
    if default.exists() {
        Some(default)
    } else {
        None
    }
}

/// Which tab to start on (from --month / --year CLI flags).
#[derive(Debug, Clone)]
pub enum StartTab {
    Monthly(i32, u32),
    Yearly(i32),
}

/// Parsed CLI arguments.
#[derive(Debug, Default)]
pub struct CliArgs {
    pub data_dir: Option<PathBuf>,
    pub start_tab: Option<StartTab>,
}

/// Parse CLI arguments.
///
///   --data-dir <PATH>     Override .claude directory
///   --month YYYY-MM       Start in monthly view (e.g. --month 2026-05)
///   --year YYYY           Start in yearly view (e.g. --year 2026)
pub fn parse_cli_args() -> CliArgs {
    let args: Vec<String> = std::env::args().collect();
    let mut result = CliArgs::default();
    let mut i = 1;
    while i < args.len() {
        match args[i].as_str() {
            "--data-dir" if i + 1 < args.len() => {
                result.data_dir = Some(PathBuf::from(&args[i + 1]));
                i += 1;
            }
            "--month" if i + 1 < args.len() => {
                if let Some((y, m)) = parse_year_month(&args[i + 1]) {
                    result.start_tab = Some(StartTab::Monthly(y, m));
                }
                i += 1;
            }
            "--year" if i + 1 < args.len() => {
                if let Ok(y) = args[i + 1].parse::<i32>() {
                    result.start_tab = Some(StartTab::Yearly(y));
                }
                i += 1;
            }
            _ => {}
        }
        i += 1;
    }
    result
}

fn parse_year_month(s: &str) -> Option<(i32, u32)> {
    let parts: Vec<&str> = s.split('-').collect();
    if parts.len() == 2 {
        let y = parts[0].parse::<i32>().ok()?;
        let m = parts[1].parse::<u32>().ok()?;
        if m >= 1 && m <= 12 {
            return Some((y, m));
        }
    }
    None
}

/// True when the encoded directory name contains patterns indicating non-ASCII
/// characters were irreversibly collapsed into dashes by Claude Code's encoding.
///
/// Claude Code maps each non-ASCII character to a single `-`. This produces 3+
/// consecutive dashes when a non-ASCII segment follows a path separator (also
/// `-`). Pure ASCII names never produce 3+ consecutive dashes.
pub fn is_lossy_encoded(encoded: &str) -> bool {
    if encoded.len() < 4 {
        return false;
    }
    encoded[3..].contains("---")
}

/// Attempt to decode project directory name to a plausible path.
///
/// Returns `None` when the encoded name shows non-ASCII loss patterns (3+
/// consecutive dashes in the path body) that make reliable decoding impossible.
/// Callers should fall back to showing the encoded name as-is.
///
/// Encoding rules (from Claude Code): `:` → `-`, `\` → `-`, `_` → `-`,
/// and each non-ASCII character → `-`.
pub fn decode_project_name(encoded: &str) -> Option<(String, String)> {
    if encoded.len() < 3 {
        return Some((encoded.to_string(), encoded.to_string()));
    }

    if is_lossy_encoded(encoded) {
        return None;
    }

    let chars: Vec<char> = encoded.chars().collect();
    let drive = chars[0];
    let rest: String = chars[3..].iter().collect();

    if drive.is_ascii_alphabetic() && encoded.chars().nth(1) == Some('-') && encoded.chars().nth(2) == Some('-') {
        let full_path = format!("{}:\\{}", drive, rest.replace('-', "\\"));
        let display = Path::new(&full_path)
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_else(|| encoded.to_string());
        Some((display, full_path))
    } else if encoded.starts_with("d--") {
        let full_path = format!("/{}", rest.replace('-', "/"));
        let display = Path::new(&full_path)
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_else(|| encoded.to_string());
        Some((display, full_path))
    } else {
        let full_path = rest.replace('-', "/");
        let display = Path::new(&full_path)
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_else(|| encoded.to_string());
        Some((display, full_path))
    }
}

/// Format a token count for human display.
pub fn format_tokens(n: u64) -> String {
    if n >= 1_000_000 {
        format!("{:.1}M", n as f64 / 1_000_000.0)
    } else if n >= 1_000 {
        format!("{}K", n / 1_000)
    } else {
        n.to_string()
    }
}

/// Parse timestamp strings from Claude Code data files.
/// Handles ISO 8601 (RFC 3339), ISO-like variants, and localized formats
/// like "MM/DD/YYYY HH:MM:SS" observed in Windows stats-cache.json.
pub fn parse_iso_timestamp(s: &str) -> Option<chrono::NaiveDateTime> {
    // Try full ISO format with timezone
    if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
        return Some(dt.naive_utc());
    }
    // Try ISO without timezone (with fractional seconds)
    if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.fZ") {
        return Some(dt);
    }
    // Try ISO without timezone (no fractional seconds)
    if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%SZ") {
        return Some(dt);
    }
    // Try localized format: "MM/DD/YYYY HH:MM:SS" (observed in Windows Claude Code)
    if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, "%m/%d/%Y %H:%M:%S") {
        return Some(dt);
    }
    // Try localized format with AM/PM
    if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, "%m/%d/%Y %I:%M:%S %p") {
        return Some(dt);
    }
    // Try just date
    if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
        return Some(d.and_hms_opt(0, 0, 0).unwrap());
    }
    None
}

/// Get the first and last day of a month.
pub fn month_bounds(year: i32, month: u32) -> (chrono::NaiveDate, chrono::NaiveDate) {
    let start = chrono::NaiveDate::from_ymd_opt(year, month, 1).unwrap();
    let end = if month == 12 {
        chrono::NaiveDate::from_ymd_opt(year + 1, 1, 1)
            .unwrap()
            .pred_opt()
            .unwrap()
    } else {
        chrono::NaiveDate::from_ymd_opt(year, month + 1, 1)
            .unwrap()
            .pred_opt()
            .unwrap()
    };
    (start, end)
}

/// Get the first and last day of a year.
pub fn year_bounds(year: i32) -> (chrono::NaiveDate, chrono::NaiveDate) {
    let start = chrono::NaiveDate::from_ymd_opt(year, 1, 1).unwrap();
    let end = chrono::NaiveDate::from_ymd_opt(year, 12, 31).unwrap();
    (start, end)
}

/// Check if a date string (YYYY-MM-DD) falls within [start, end] inclusive.
pub fn date_str_in_range(date_str: &str, start: chrono::NaiveDate, end: chrono::NaiveDate) -> bool {
    if let Ok(d) = chrono::NaiveDate::parse_from_str(date_str, "%Y-%m-%d") {
        d >= start && d <= end
    } else {
        false
    }
}

/// Fast timestamp range check on a raw JSONL line.
/// Looks for "timestamp":"YYYY-MM-DD or "timestamp": "YYYY-MM-DD pattern
/// without full deserialization.
pub fn timestamp_in_range_fast(line: &str, start: chrono::NaiveDate, end: chrono::NaiveDate) -> bool {
    // Try exact "timestamp":" (no space)
    if let Some(idx) = line.find("\"timestamp\":\"") {
        let after = &line[idx + 13..];
        if after.len() >= 10 {
            let date_str = &after[..10];
            return date_str_in_range(date_str, start, end);
        }
    }
    // Try "timestamp": " (with space)
    if let Some(idx) = line.find("\"timestamp\": \"") {
        let after = &line[idx + 14..];
        if after.len() >= 10 {
            let date_str = &after[..10];
            return date_str_in_range(date_str, start, end);
        }
    }
    false
}

// --- Language detection ---

/// Map file extension to language name.
fn ext_to_lang(ext: &str) -> Option<&'static str> {
    let ext = ext.to_lowercase();
    match ext.as_str() {
        "rs" => Some("Rust"),
        "c" => Some("C"),
        "cpp" | "cc" | "cxx" => Some("C++"),
        "h" | "hpp" | "hxx" => Some("C/C++ Header"),
        "go" => Some("Go"),
        "zig" => Some("Zig"),
        "java" => Some("Java"),
        "kt" | "kts" => Some("Kotlin"),
        "scala" => Some("Scala"),
        "cs" => Some("C#"),
        "fs" | "fsx" => Some("F#"),
        "py" | "pyw" => Some("Python"),
        "rb" => Some("Ruby"),
        "pl" => Some("Perl"),
        "php" => Some("PHP"),
        "lua" => Some("Lua"),
        "r" => Some("R"),
        "js" | "mjs" | "cjs" => Some("JavaScript"),
        "ts" => Some("TypeScript"),
        "jsx" => Some("JSX"),
        "tsx" => Some("TSX"),
        "html" | "htm" => Some("HTML"),
        "css" => Some("CSS"),
        "scss" | "sass" => Some("SCSS"),
        "less" => Some("Less"),
        "vue" => Some("Vue"),
        "svelte" => Some("Svelte"),
        "sh" | "bash" | "zsh" => Some("Shell"),
        "ps1" | "psm1" | "psd1" => Some("PowerShell"),
        "bat" | "cmd" => Some("Batch"),
        "toml" => Some("TOML"),
        "yaml" | "yml" => Some("YAML"),
        "xml" => Some("XML"),
        "json" => Some("JSON"),
        "md" | "mdx" => Some("Markdown"),
        "rst" => Some("reST"),
        "tex" => Some("LaTeX"),
        "typ" => Some("Typst"),
        "sql" => Some("SQL"),
        "proto" => Some("Protobuf"),
        "graphql" | "gql" => Some("GraphQL"),
        "dockerfile" => Some("Docker"),
        "nix" => Some("Nix"),
        "jl" => Some("Julia"),
        "swift" => Some("Swift"),
        "dart" => Some("Dart"),
        "ex" | "exs" => Some("Elixir"),
        "erl" | "hrl" => Some("Erlang"),
        "hs" => Some("Haskell"),
        "ml" | "mli" => Some("OCaml"),
        "elm" => Some("Elm"),
        "clj" | "cljs" | "edn" => Some("Clojure"),
        "tf" | "tfvars" => Some("Terraform"),
        "cmake" | "CMakeLists.txt" => Some("CMake"),
        "Makefile" | "makefile" => Some("Makefile"),
        "ipynb" => Some("Jupyter"),
        _ => None,
    }
}

/// Directories to skip when scanning.
const SKIP_DIRS: &[&str] = &[
    ".git", ".claude", "node_modules", "target", "__pycache__",
    "venv", ".venv", "dist", "build", ".next", ".nuxt",
    "vendor", "bower_components", ".tox", ".eggs", ".mypy_cache",
    ".pytest_cache", ".ruff_cache", "coverage", "htmlcov",
];

/// Extensions to skip (non-code).
const SKIP_EXTS: &[&str] = &[
    "lock", "txt", "log", "png", "jpg", "jpeg", "gif", "svg", "ico",
    "pdf", "exe", "dll", "so", "dylib", "o", "a", "class",
    "jar", "war", "zip", "tar", "gz", "bz2", "7z", "rar",
    "mp3", "mp4", "avi", "mov", "wav", "flac",
    "ttf", "otf", "woff", "woff2", "eot",
    "db", "sqlite", "sqlite3",
    "pem", "crt", "key", "keystore",
    "bin", "dat", "pkl", "pickle",
    "pyc", "pyo", "rlib", "rmeta",
];

/// Detect programming languages in a project directory.
/// Runs on a background thread and sends results via channel.
pub fn detect_languages(project_paths: &[(String, String, bool)]) -> HashMap<String, f64> {
    let mut lang_counts: HashMap<String, u64> = HashMap::new();
    let mut total = 0u64;

    for (_display_name, full_path, path_resolved) in project_paths {
        if !path_resolved || full_path.is_empty() {
            continue;
        }
        let path = Path::new(full_path);
        if !path.exists() {
            continue;
        }

        let walker = WalkDir::new(path)
            .max_depth(3)
            .into_iter()
            .filter_entry(|e| {
                if let Some(name) = e.file_name().to_str() {
                    !SKIP_DIRS.contains(&name)
                } else {
                    false
                }
            });

        let mut count = 0u64;
        for entry in walker {
            if count >= 10_000 {
                break;
            }
            if let Ok(entry) = entry {
                if !entry.file_type().is_file() {
                    continue;
                }
                if let Some(ext) = entry.path().extension() {
                    let ext_str = ext.to_string_lossy();
                    if SKIP_EXTS.contains(&ext_str.as_ref()) {
                        continue;
                    }
                    if let Some(lang) = ext_to_lang(&ext_str) {
                        *lang_counts.entry(lang.to_string()).or_insert(0) += 1;
                        total += 1;
                    }
                } else if let Some(name) = entry.path().file_name().and_then(|n| n.to_str()) {
                    // Handle special filenames like Dockerfile, Makefile, CMakeLists.txt
                    if let Some(lang) = ext_to_lang(name) {
                        *lang_counts.entry(lang.to_string()).or_insert(0) += 1;
                        total += 1;
                    }
                }
                count += 1;
            }
        }
    }

    if total == 0 {
        return HashMap::new();
    }

    let mut result: HashMap<String, f64> = HashMap::new();
    for (lang, count) in &lang_counts {
        result.insert(lang.clone(), (*count as f64 / total as f64) * 100.0);
    }
    result
}

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

    #[test]
    fn test_decode_windows_path() {
        let result = decode_project_name("D--dev-rust-my-crate");
        assert!(result.is_some());
        let (display, full) = result.unwrap();
        assert_eq!(display, "crate");
        assert_eq!(full, "D:\\dev\\rust\\my\\crate");
    }

    #[test]
    fn test_decode_windows_path_dash_in_name() {
        let result = decode_project_name("D--dev-foo-bar-baz");
        assert!(result.is_some());
        let (display, _full) = result.unwrap();
        assert_eq!(display, "baz");
    }

    #[test]
    fn test_decode_unix_path() {
        let result = decode_project_name("d--opt-shared-lib");
        assert!(result.is_some());
        let (_display, full) = result.unwrap();
        assert!(full.contains("opt"));
        assert!(full.contains("shared"));
    }

    #[test]
    fn test_decode_short_name() {
        let result = decode_project_name("ab");
        assert!(result.is_some());
        let (display, full) = result.unwrap();
        assert_eq!(display, "ab");
        assert_eq!(full, "ab");
    }

    #[test]
    fn test_decode_chinese_path_rejected() {
        // 3+ consecutive dashes in body = non-ASCII loss → reject
        assert_eq!(decode_project_name("D--dev-foo---bar"), None);
    }

    #[test]
    fn test_decode_pure_chinese_rejected() {
        // All dashes after prefix = pure non-ASCII name → reject
        assert_eq!(decode_project_name("D--dev------"), None);
    }

    // --- is_lossy_encoded ---

    #[test]
    fn test_is_lossy_encoded_chinese_path() {
        assert!(is_lossy_encoded("D--dev-foo---bar"));
    }

    #[test]
    fn test_is_lossy_encoded_pure_chinese_name() {
        assert!(is_lossy_encoded("D--dev------"));
    }

    #[test]
    fn test_is_lossy_encoded_normal_ascii() {
        assert!(!is_lossy_encoded("D--dev-my-app"));
    }

    #[test]
    fn test_is_lossy_encoded_short_names() {
        assert!(!is_lossy_encoded("ab"));
        assert!(!is_lossy_encoded("D--"));
        assert!(!is_lossy_encoded("D--a"));
    }

    #[test]
    fn test_is_lossy_encoded_dash_in_project_name() {
        // Two consecutive dashes (--) is fine — not a non-ASCII fingerprint
        assert!(!is_lossy_encoded("D--dev-my-app"));
    }

    #[test]
    fn test_is_lossy_encoded_triple_dash_edge() {
        // Triple dashes from 3+ underscores in original name: safe false positive
        assert!(is_lossy_encoded("D--dev-my---app"));
    }

    #[test]
    fn test_format_tokens_millions() {
        assert_eq!(format_tokens(5_200_000), "5.2M");
        assert_eq!(format_tokens(1_000_000), "1.0M");
        assert_eq!(format_tokens(12_500_000), "12.5M");
    }

    #[test]
    fn test_format_tokens_kilo() {
        assert_eq!(format_tokens(123_000), "123K");
        assert_eq!(format_tokens(1_000), "1K");
        assert_eq!(format_tokens(999), "999");
    }

    #[test]
    fn test_format_tokens_small() {
        assert_eq!(format_tokens(500), "500");
        assert_eq!(format_tokens(0), "0");
    }

    #[test]
    fn test_parse_iso_timestamp_full() {
        let dt = parse_iso_timestamp("2025-11-04T08:34:16.259Z");
        assert!(dt.is_some());
        let dt = dt.unwrap();
        assert_eq!(dt.date().to_string(), "2025-11-04");
        assert_eq!(dt.time().hour(), 8);
    }

    #[test]
    fn test_parse_iso_timestamp_date_only() {
        let dt = parse_iso_timestamp("2024-03-15");
        assert!(dt.is_some());
        let dt = dt.unwrap();
        assert_eq!(dt.date().to_string(), "2024-03-15");
    }

    #[test]
    fn test_parse_iso_timestamp_invalid() {
        assert!(parse_iso_timestamp("not-a-date").is_none());
        assert!(parse_iso_timestamp("").is_none());
    }

    #[test]
    fn test_parse_iso_timestamp_without_ms() {
        // Timestamps without milliseconds (common in session JSONL)
        let dt = parse_iso_timestamp("2026-04-15T10:30:00Z");
        assert!(dt.is_some());
        let dt = dt.unwrap();
        assert_eq!(dt.date().to_string(), "2026-04-15");
        assert_eq!(dt.time().hour(), 10);
    }

    #[test]
    fn test_parse_iso_timestamp_with_timezone_offset() {
        let dt = parse_iso_timestamp("2026-04-15T10:30:00+08:00");
        assert!(dt.is_some());
        let dt = dt.unwrap();
        assert_eq!(dt.date().to_string(), "2026-04-15");
    }

    #[test]
    fn test_parse_localized_timestamp() {
        // Format observed in Windows Claude Code stats-cache.json firstSessionDate
        let dt = parse_iso_timestamp("03/09/2026 14:00:30");
        assert!(dt.is_some());
        let dt = dt.unwrap();
        assert_eq!(dt.date().to_string(), "2026-03-09");
        assert_eq!(dt.time().hour(), 14);
        assert_eq!(dt.time().minute(), 0);
        assert_eq!(dt.time().second(), 30);
    }

    #[test]
    fn test_parse_localized_timestamp_invalid() {
        assert!(parse_iso_timestamp("13/32/2026 25:00:00").is_none());
    }

    #[test]
    fn test_month_bounds() {
        let (start, end) = month_bounds(2026, 1);
        assert_eq!(start.to_string(), "2026-01-01");
        assert_eq!(end.to_string(), "2026-01-31");

        let (start, end) = month_bounds(2026, 2);
        assert_eq!(start.to_string(), "2026-02-01");
        assert_eq!(end.to_string(), "2026-02-28");

        let (_start, end) = month_bounds(2024, 2); // leap year
        assert_eq!(end.to_string(), "2024-02-29");
    }

    #[test]
    fn test_month_bounds_december() {
        let (start, end) = month_bounds(2026, 12);
        assert_eq!(start.to_string(), "2026-12-01");
        assert_eq!(end.to_string(), "2026-12-31");
    }

    #[test]
    fn test_year_bounds() {
        let (start, end) = year_bounds(2026);
        assert_eq!(start.to_string(), "2026-01-01");
        assert_eq!(end.to_string(), "2026-12-31");
    }

    #[test]
    fn test_year_bounds_leap_year() {
        let (start, end) = year_bounds(2024);
        assert_eq!(start.to_string(), "2024-01-01");
        assert_eq!(end.to_string(), "2024-12-31");
    }

    #[test]
    fn test_date_str_in_range() {
        let start = chrono::NaiveDate::from_ymd_opt(2026, 4, 1).unwrap();
        let end = chrono::NaiveDate::from_ymd_opt(2026, 4, 30).unwrap();

        assert!(date_str_in_range("2026-04-15", start, end));
        assert!(date_str_in_range("2026-04-01", start, end));
        assert!(date_str_in_range("2026-04-30", start, end));
        assert!(!date_str_in_range("2026-03-31", start, end));
        assert!(!date_str_in_range("2026-05-01", start, end));
        assert!(!date_str_in_range("bad-date", start, end));
    }

    #[test]
    fn test_date_str_in_range_boundary() {
        let start = chrono::NaiveDate::from_ymd_opt(2026, 1, 1).unwrap();
        let end = chrono::NaiveDate::from_ymd_opt(2026, 1, 31).unwrap();

        assert!(date_str_in_range("2026-01-01", start, end));
        assert!(date_str_in_range("2026-01-31", start, end));
        assert!(!date_str_in_range("2025-12-31", start, end));
        assert!(!date_str_in_range("2026-02-01", start, end));
    }

    #[test]
    fn test_timestamp_in_range_fast() {
        let start = chrono::NaiveDate::from_ymd_opt(2026, 4, 1).unwrap();
        let end = chrono::NaiveDate::from_ymd_opt(2026, 4, 30).unwrap();

        let line = r#"{"type":"assistant","timestamp":"2026-04-15T10:30:00Z","message":{}}"#;
        assert!(timestamp_in_range_fast(line, start, end));

        let line = r#"{"type":"assistant","timestamp":"2026-03-01T10:30:00Z","message":{}}"#;
        assert!(!timestamp_in_range_fast(line, start, end));

        let line = r#"{"type":"assistant","no_timestamp":"here"}"#;
        assert!(!timestamp_in_range_fast(line, start, end));
    }

    #[test]
    fn test_timestamp_in_range_fast_boundary() {
        let start = chrono::NaiveDate::from_ymd_opt(2026, 4, 1).unwrap();
        let end = chrono::NaiveDate::from_ymd_opt(2026, 4, 30).unwrap();

        // First day of range
        let line = r#"{"timestamp":"2026-04-01T00:00:00Z","type":"assistant"}"#;
        assert!(timestamp_in_range_fast(line, start, end));

        // Last day of range
        let line = r#"{"timestamp":"2026-04-30T23:59:59Z","type":"assistant"}"#;
        assert!(timestamp_in_range_fast(line, start, end));

        // Day before range
        let line = r#"{"timestamp":"2026-03-31T23:59:59Z","type":"assistant"}"#;
        assert!(!timestamp_in_range_fast(line, start, end));
    }

    #[test]
    fn test_timestamp_in_range_fast_with_space_after_colon() {
        let start = chrono::NaiveDate::from_ymd_opt(2026, 4, 1).unwrap();
        let end = chrono::NaiveDate::from_ymd_opt(2026, 4, 30).unwrap();

        // JSON with space after colon — now correctly handled
        let line = r#"{"timestamp": "2026-04-15T10:30:00Z", "type": "assistant"}"#;
        assert!(timestamp_in_range_fast(line, start, end));
    }

    #[test]
    fn test_timestamp_in_range_fast_line_without_date() {
        let start = chrono::NaiveDate::from_ymd_opt(2026, 4, 1).unwrap();
        let end = chrono::NaiveDate::from_ymd_opt(2026, 4, 30).unwrap();

        // Line that doesn't have 10 chars after the timestamp prefix
        let line = r#"{"timestamp":"bad"}"#;
        assert!(!timestamp_in_range_fast(line, start, end));
    }

    // --- ext_to_lang ---

    #[test]
    fn test_ext_to_lang_common_languages() {
        assert_eq!(ext_to_lang("rs"), Some("Rust"));
        assert_eq!(ext_to_lang("py"), Some("Python"));
        assert_eq!(ext_to_lang("js"), Some("JavaScript"));
        assert_eq!(ext_to_lang("ts"), Some("TypeScript"));
        assert_eq!(ext_to_lang("go"), Some("Go"));
        assert_eq!(ext_to_lang("java"), Some("Java"));
        assert_eq!(ext_to_lang("rb"), Some("Ruby"));
        assert_eq!(ext_to_lang("c"), Some("C"));
        assert_eq!(ext_to_lang("cpp"), Some("C++"));
        assert_eq!(ext_to_lang("cc"), Some("C++"));
    }

    #[test]
    fn test_ext_to_lang_case_insensitive() {
        assert_eq!(ext_to_lang("RS"), Some("Rust"));
        assert_eq!(ext_to_lang("Py"), Some("Python"));
        assert_eq!(ext_to_lang("JS"), Some("JavaScript"));
        assert_eq!(ext_to_lang("Ts"), Some("TypeScript"));
    }

    #[test]
    fn test_ext_to_lang_web_extensions() {
        assert_eq!(ext_to_lang("tsx"), Some("TSX"));
        assert_eq!(ext_to_lang("jsx"), Some("JSX"));
        assert_eq!(ext_to_lang("vue"), Some("Vue"));
        assert_eq!(ext_to_lang("svelte"), Some("Svelte"));
        assert_eq!(ext_to_lang("html"), Some("HTML"));
        assert_eq!(ext_to_lang("htm"), Some("HTML"));
        assert_eq!(ext_to_lang("css"), Some("CSS"));
        assert_eq!(ext_to_lang("scss"), Some("SCSS"));
    }

    #[test]
    fn test_ext_to_lang_shell_and_config() {
        assert_eq!(ext_to_lang("sh"), Some("Shell"));
        assert_eq!(ext_to_lang("bash"), Some("Shell"));
        assert_eq!(ext_to_lang("zsh"), Some("Shell"));
        assert_eq!(ext_to_lang("toml"), Some("TOML"));
        assert_eq!(ext_to_lang("yaml"), Some("YAML"));
        assert_eq!(ext_to_lang("yml"), Some("YAML"));
        assert_eq!(ext_to_lang("json"), Some("JSON"));
    }

    #[test]
    fn test_ext_to_lang_special_filenames() {
        assert_eq!(ext_to_lang("dockerfile"), Some("Docker"));
        assert_eq!(ext_to_lang("Makefile"), Some("Makefile"));
        assert_eq!(ext_to_lang("makefile"), Some("Makefile"));
    }

    #[test]
    fn test_ext_to_lang_unknown() {
        assert_eq!(ext_to_lang("xyz"), None);
        assert_eq!(ext_to_lang(""), None);
        assert_eq!(ext_to_lang("foobar"), None);
    }

    #[test]
    fn test_ext_to_lang_functional_languages() {
        assert_eq!(ext_to_lang("hs"), Some("Haskell"));
        assert_eq!(ext_to_lang("ml"), Some("OCaml"));
        assert_eq!(ext_to_lang("elm"), Some("Elm"));
        assert_eq!(ext_to_lang("clj"), Some("Clojure"));
        assert_eq!(ext_to_lang("ex"), Some("Elixir"));
        assert_eq!(ext_to_lang("erl"), Some("Erlang"));
    }

    #[test]
    fn test_ext_to_lang_microsoft_languages() {
        assert_eq!(ext_to_lang("cs"), Some("C#"));
        assert_eq!(ext_to_lang("fs"), Some("F#"));
        assert_eq!(ext_to_lang("ps1"), Some("PowerShell"));
        assert_eq!(ext_to_lang("bat"), Some("Batch"));
        assert_eq!(ext_to_lang("cmd"), Some("Batch"));
    }

    // --- format_tokens boundary ---

    #[test]
    fn test_format_tokens_boundary_values() {
        // Exactly at boundaries
        assert_eq!(format_tokens(999), "999");
        assert_eq!(format_tokens(1_000), "1K");
        assert_eq!(format_tokens(999_999), "999K");
        assert_eq!(format_tokens(1_000_000), "1.0M");

        // One less than boundary
        assert_eq!(format_tokens(999), "999");
        assert_eq!(format_tokens(999_999), "999K");

        // One more than boundary
        assert_eq!(format_tokens(1_001), "1K"); // integer division
        assert_eq!(format_tokens(1_000_001), "1.0M");
    }

    #[test]
    fn test_format_tokens_large_values() {
        assert_eq!(format_tokens(100_000_000), "100.0M");
        assert_eq!(format_tokens(1_500_000_000), "1500.0M");
    }

    // --- parse_year_month ---

    #[test]
    fn test_parse_year_month_valid() {
        assert_eq!(parse_year_month("2026-05"), Some((2026, 5)));
        assert_eq!(parse_year_month("2024-01"), Some((2024, 1)));
        assert_eq!(parse_year_month("2024-12"), Some((2024, 12)));
        assert_eq!(parse_year_month("2000-06"), Some((2000, 6)));
    }

    #[test]
    fn test_parse_year_month_invalid() {
        assert_eq!(parse_year_month(""), None);
        assert_eq!(parse_year_month("2026"), None);
        assert_eq!(parse_year_month("2026-00"), None); // month 0
        assert_eq!(parse_year_month("2026-13"), None); // month 13
        assert_eq!(parse_year_month("abc-def"), None);
        assert_eq!(parse_year_month("2026-5-extra"), None); // too many parts
    }

    #[test]
    fn test_parse_year_month_edge_cases() {
        assert_eq!(parse_year_month("0-1"), Some((0, 1)));
        assert_eq!(parse_year_month("9999-12"), Some((9999, 12)));
        // Negative year has two dashes → splits into 3 parts → None
        assert_eq!(parse_year_month("-1-6"), None);
    }

    // --- detect_languages ---

    #[test]
    fn test_detect_languages_empty_input() {
        let result = detect_languages(&[]);
        assert!(result.is_empty());
    }

    #[test]
    fn test_detect_languages_unresolved_path_skipped() {
        let projects = vec![
            ("test".to_string(), "/some/path".to_string(), false),
        ];
        let result = detect_languages(&projects);
        assert!(result.is_empty());
    }

    #[test]
    fn test_detect_languages_nonexistent_path() {
        let projects = vec![
            ("test".to_string(), "/nonexistent/path/xyz".to_string(), true),
        ];
        let result = detect_languages(&projects);
        assert!(result.is_empty());
    }

    #[test]
    fn test_detect_languages_with_real_files() {
        let dir = std::env::temp_dir().join("claude-dash-test-lang-detect");
        let _ = std::fs::create_dir_all(&dir);
        // Create some test files
        let _ = std::fs::write(dir.join("main.rs"), "fn main() {}");
        let _ = std::fs::write(dir.join("lib.py"), "pass");
        let _ = std::fs::write(dir.join("app.js"), "");

        let projects = vec![
            ("test".to_string(), dir.to_string_lossy().to_string(), true),
        ];
        let result = detect_languages(&projects);

        assert!(!result.is_empty());
        assert!(result.contains_key("Rust"));
        assert!(result.contains_key("Python"));
        assert!(result.contains_key("JavaScript"));

        // Total should be 100%
        let total: f64 = result.values().sum();
        assert!((total - 100.0).abs() < 0.01);

        // Cleanup
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_detect_languages_skips_node_modules() {
        let dir = std::env::temp_dir().join("claude-dash-test-lang-skip");
        let _ = std::fs::remove_dir_all(&dir);
        let nm_dir = dir.join("node_modules");
        let _ = std::fs::create_dir_all(&nm_dir);
        let _ = std::fs::write(dir.join("index.ts"), "");
        // Files inside node_modules should be skipped
        let _ = std::fs::write(nm_dir.join("dep.js"), "");

        let projects = vec![
            ("test".to_string(), dir.to_string_lossy().to_string(), true),
        ];
        let result = detect_languages(&projects);

        // Should only have TypeScript, not JavaScript from node_modules
        assert!(result.contains_key("TypeScript"));
        // JavaScript might still appear if walkdir visits it at depth ≤ 3,
        // but the node_modules dir itself should be filtered
        // At minimum, TypeScript should be present
        assert!(result.get("TypeScript").unwrap() > &0.0);

        let _ = std::fs::remove_dir_all(&dir);
    }

    // --- is_lossy_encoded more edge cases ---

    #[test]
    fn test_is_lossy_encoded_exactly_three_dashes() {
        // Exactly "---" at position 3+ triggers lossy detection
        assert!(is_lossy_encoded("D------")); // 4 dashes after "D--"
        assert!(is_lossy_encoded("D--a---b")); // "---" in body
    }

    #[test]
    fn test_is_lossy_encoded_minimum_length() {
        // len < 4 → always false
        assert!(!is_lossy_encoded(""));
        assert!(!is_lossy_encoded("D"));
        assert!(!is_lossy_encoded("D-"));
        assert!(!is_lossy_encoded("D--"));
    }

    // --- decode_project_name more edge cases ---

    #[test]
    fn test_decode_project_name_single_segment() {
        // Short names (< 3 chars) return as-is
        let result = decode_project_name("x");
        assert!(result.is_some());
        let (display, full) = result.unwrap();
        assert_eq!(display, "x");
        assert_eq!(full, "x");
    }

    #[test]
    fn test_decode_project_name_unix_style() {
        // 'd' is alphabetic + chars[1]=chars[2]='-' → treated as Windows drive letter
        let result = decode_project_name("d--home-user-project");
        assert!(result.is_some());
        let (display, full) = result.unwrap();
        assert_eq!(display, "project");
        assert_eq!(full, "d:\\home\\user\\project");
    }

    #[test]
    fn test_decode_project_name_non_drive_prefix() {
        // 'a' is alphabetic but chars[1]='b' != '-' → falls to else branch
        // rest = chars[3..] = "-def-ghi" → full_path = "/def/ghi"
        let result = decode_project_name("abc-def-ghi");
        assert!(result.is_some());
        let (display, full) = result.unwrap();
        assert_eq!(display, "ghi");
        assert_eq!(full, "/def/ghi");
    }

    // --- timestamp_in_range_fast more edge cases ---

    #[test]
    fn test_timestamp_in_range_fast_empty_line() {
        let start = chrono::NaiveDate::from_ymd_opt(2026, 1, 1).unwrap();
        let end = chrono::NaiveDate::from_ymd_opt(2026, 12, 31).unwrap();
        assert!(!timestamp_in_range_fast("", start, end));
    }

    #[test]
    fn test_timestamp_in_range_fast_short_timestamp() {
        let start = chrono::NaiveDate::from_ymd_opt(2026, 1, 1).unwrap();
        let end = chrono::NaiveDate::from_ymd_opt(2026, 12, 31).unwrap();
        // Timestamp field exists but value is too short (< 10 chars)
        let line = r#"{"timestamp":"2026-0"}"#;
        assert!(!timestamp_in_range_fast(line, start, end));
    }
}