gitstack 5.3.0

Git history viewer with insights - Author stats, file heatmap, code ownership
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
//! File statistics, heatmap, timeline, and ownership analysis

use chrono::{DateTime, Local};
use std::collections::HashMap;

use crate::event::GitEvent;

use super::AggregationLevel;

/// Per-author statistics
#[derive(Debug, Clone)]
pub struct AuthorStats {
    /// Author name
    pub name: String,
    /// Commit count
    pub commit_count: usize,
    /// Lines added
    pub insertions: usize,
    /// Lines deleted
    pub deletions: usize,
    /// Last commit date
    pub last_commit: DateTime<Local>,
}

impl AuthorStats {
    /// Calculate commit percentage
    pub fn commit_percentage(&self, total: usize) -> f64 {
        if total == 0 {
            0.0
        } else {
            (self.commit_count as f64 / total as f64) * 100.0
        }
    }
}

/// Repository-wide statistics
#[derive(Debug, Clone, Default)]
pub struct RepoStats {
    /// Per-author statistics (sorted by commit count descending)
    pub authors: Vec<AuthorStats>,
    /// Total commit count
    pub total_commits: usize,
    /// Total lines added
    pub total_insertions: usize,
    /// Total lines deleted
    pub total_deletions: usize,
}

impl RepoStats {
    /// Get author count
    pub fn author_count(&self) -> usize {
        self.authors.len()
    }
}

/// File change frequency entry
#[derive(Debug, Clone)]
pub struct FileHeatmapEntry {
    /// File path
    pub path: String,
    /// Change count
    pub change_count: usize,
    /// Maximum change count (for normalization)
    pub max_changes: usize,
}

impl FileHeatmapEntry {
    /// Calculate heat level (0.0-1.0)
    pub fn heat_level(&self) -> f64 {
        if self.max_changes == 0 {
            0.0
        } else {
            self.change_count as f64 / self.max_changes as f64
        }
    }

    /// Generate heat bar (5 levels)
    pub fn heat_bar(&self) -> &'static str {
        let level = self.heat_level();
        if level >= 0.8 {
            "█████"
        } else if level >= 0.6 {
            "████ "
        } else if level >= 0.4 {
            "███  "
        } else if level >= 0.2 {
            "██   "
        } else {
            ""
        }
    }
}

/// File change heatmap
#[derive(Debug, Clone, Default)]
pub struct FileHeatmap {
    /// File list (sorted by change count descending)
    pub files: Vec<FileHeatmapEntry>,
    /// Total file count
    pub total_files: usize,
    /// Current aggregation level
    pub aggregation_level: AggregationLevel,
}

impl FileHeatmap {
    /// Get file count
    pub fn file_count(&self) -> usize {
        self.files.len()
    }

    /// Create a new heatmap with a different aggregation level
    pub fn with_aggregation(&self, level: AggregationLevel) -> FileHeatmap {
        if level == AggregationLevel::Files {
            // Return as-is for file level
            return FileHeatmap {
                files: self.files.clone(),
                total_files: self.total_files,
                aggregation_level: level,
            };
        }

        // Aggregate by directory
        let mut dir_counts: HashMap<String, usize> = HashMap::new();

        for entry in &self.files {
            let dir = extract_directory(&entry.path, level);
            *dir_counts.entry(dir).or_insert(0) += entry.change_count;
        }

        let max_changes = dir_counts.values().copied().max().unwrap_or(0);

        let mut files: Vec<FileHeatmapEntry> = dir_counts
            .into_iter()
            .map(|(path, change_count)| FileHeatmapEntry {
                path,
                change_count,
                max_changes,
            })
            .collect();

        // Sort by change count descending
        files.sort_by(|a, b| b.change_count.cmp(&a.change_count));

        FileHeatmap {
            total_files: self.total_files,
            files,
            aggregation_level: level,
        }
    }
}

/// Extract directory path
fn extract_directory(path: &str, level: AggregationLevel) -> String {
    let parts: Vec<&str> = path.split('/').collect();
    match level {
        AggregationLevel::Files => path.to_string(),
        AggregationLevel::Shallow => {
            // src/auth/login.rs → src/auth/
            if parts.len() > 2 {
                format!("{}/{}/", parts[0], parts[1])
            } else if parts.len() == 2 {
                format!("{}/", parts[0])
            } else {
                path.to_string()
            }
        }
        AggregationLevel::Deep => {
            // src/auth/login.rs → src/
            if parts.len() > 1 {
                format!("{}/", parts[0])
            } else {
                path.to_string()
            }
        }
    }
}

/// Calculate file change heatmap from events
pub fn calculate_file_heatmap(
    events: &[&GitEvent],
    get_files: impl Fn(&str) -> Option<Vec<String>>,
) -> FileHeatmap {
    let mut file_counts: HashMap<String, usize> = HashMap::new();

    for event in events {
        if let Some(files) = get_files(&event.short_hash) {
            for file in files {
                *file_counts.entry(file).or_insert(0) += 1;
            }
        }
    }

    let max_changes = file_counts.values().copied().max().unwrap_or(0);

    let mut files: Vec<FileHeatmapEntry> = file_counts
        .into_iter()
        .map(|(path, change_count)| FileHeatmapEntry {
            path,
            change_count,
            max_changes,
        })
        .collect();

    // Sort by change count descending
    files.sort_by(|a, b| b.change_count.cmp(&a.change_count));

    let total_files = files.len();
    FileHeatmap {
        files,
        total_files,
        aggregation_level: AggregationLevel::Files,
    }
}

/// Activity timeline (day-of-week x hour heatmap)
#[derive(Debug, Clone, Default)]
pub struct ActivityTimeline {
    /// 7x24 grid (day-of-week x hour)
    /// grid[day][hour] = commit count
    /// Day: 0=Mon, 1=Tue, 2=Wed, 3=Thu, 4=Fri, 5=Sat, 6=Sun
    pub grid: [[usize; 24]; 7],
    /// Total commit count
    pub total_commits: usize,
    /// Peak day (0-6)
    pub peak_day: usize,
    /// Peak hour (0-23)
    pub peak_hour: usize,
    /// Commit count at peak
    pub peak_count: usize,
    /// Maximum commit count (for normalization)
    pub max_count: usize,
}

impl ActivityTimeline {
    /// Get day name
    pub fn day_name(day: usize) -> &'static str {
        match day {
            0 => "Mon",
            1 => "Tue",
            2 => "Wed",
            3 => "Thu",
            4 => "Fri",
            5 => "Sat",
            6 => "Sun",
            _ => "???",
        }
    }

    /// Calculate heat level (0.0-1.0)
    pub fn heat_level(&self, day: usize, hour: usize) -> f64 {
        if self.max_count == 0 {
            0.0
        } else {
            self.grid[day][hour] as f64 / self.max_count as f64
        }
    }

    /// Get heatmap character
    pub fn heat_char(level: f64) -> &'static str {
        if level >= 0.8 {
            "██"
        } else if level >= 0.6 {
            "▓▓"
        } else if level >= 0.4 {
            "▒▒"
        } else if level >= 0.2 {
            "░░"
        } else if level > 0.0 {
            "··"
        } else {
            "  "
        }
    }

    /// Get peak time summary string
    pub fn peak_summary(&self) -> String {
        if self.peak_count == 0 {
            "No activity".to_string()
        } else {
            format!(
                "{} {:02}:00-{:02}:00 ({} commits)",
                Self::day_name(self.peak_day),
                self.peak_hour,
                (self.peak_hour + 1) % 24,
                self.peak_count
            )
        }
    }
}

/// Calculate activity timeline from events
pub fn calculate_activity_timeline(events: &[&GitEvent]) -> ActivityTimeline {
    use chrono::Datelike;
    use chrono::Timelike;

    let mut timeline = ActivityTimeline {
        total_commits: events.len(),
        ..Default::default()
    };

    for event in events {
        // chrono::Weekday: Monday=0...Sunday=6
        let day = event.timestamp.weekday().num_days_from_monday() as usize;
        let hour = event.timestamp.hour() as usize;

        timeline.grid[day][hour] += 1;
    }

    // Calculate peak
    let mut max_count = 0usize;
    for (day, hours) in timeline.grid.iter().enumerate() {
        for (hour, &count) in hours.iter().enumerate() {
            if count > max_count {
                max_count = count;
                timeline.peak_day = day;
                timeline.peak_hour = hour;
                timeline.peak_count = count;
            }
        }
    }
    timeline.max_count = max_count;

    timeline
}

/// Code ownership entry
#[derive(Debug, Clone)]
pub struct CodeOwnershipEntry {
    /// Path (directory or file)
    pub path: String,
    /// Primary author
    pub primary_author: String,
    /// Commit count of the primary author
    pub primary_commits: usize,
    /// Total commit count
    pub total_commits: usize,
    /// Depth (for indentation)
    pub depth: usize,
    /// Whether this is a directory
    pub is_directory: bool,
}

impl CodeOwnershipEntry {
    /// Calculate primary author ownership percentage
    pub fn ownership_percentage(&self) -> f64 {
        if self.total_commits == 0 {
            0.0
        } else {
            (self.primary_commits as f64 / self.total_commits as f64) * 100.0
        }
    }
}

/// Code ownership analysis result
#[derive(Debug, Clone, Default)]
pub struct CodeOwnership {
    /// Entry list (in hierarchical order)
    pub entries: Vec<CodeOwnershipEntry>,
    /// Total file count
    pub total_files: usize,
}

impl CodeOwnership {
    /// Get entry count
    pub fn entry_count(&self) -> usize {
        self.entries.len()
    }
}

/// Calculate code ownership from events
pub fn calculate_ownership(
    events: &[&GitEvent],
    get_files: impl Fn(&str) -> Option<Vec<String>>,
) -> CodeOwnership {
    // Aggregate author commit counts per file
    let mut file_author_counts: HashMap<String, HashMap<String, usize>> = HashMap::new();

    for event in events {
        if let Some(files) = get_files(&event.short_hash) {
            for file in files {
                let author_counts = file_author_counts.entry(file).or_default();
                *author_counts.entry(event.author.clone()).or_insert(0) += 1;
            }
        }
    }

    // Aggregate author commit counts per directory
    let mut dir_author_counts: HashMap<String, HashMap<String, usize>> = HashMap::new();

    for (file_path, author_counts) in &file_author_counts {
        // Extract directory paths from file paths
        let parts: Vec<&str> = file_path.split('/').collect();
        for i in 1..parts.len() {
            let dir_path = parts[..i].join("/");
            let dir_counts = dir_author_counts.entry(dir_path).or_default();
            for (author, count) in author_counts {
                *dir_counts.entry(author.clone()).or_insert(0) += count;
            }
        }
    }

    // Generate entries
    let mut entries = Vec::new();

    // Sort directories in hierarchical order
    let mut dir_paths: Vec<String> = dir_author_counts.keys().cloned().collect();
    dir_paths.sort();

    for dir_path in dir_paths {
        let author_counts = &dir_author_counts[&dir_path];
        let (primary_author, primary_commits) = author_counts
            .iter()
            .max_by_key(|(_, c)| *c)
            .map(|(a, c)| (a.clone(), *c))
            .unwrap_or_default();
        let total_commits: usize = author_counts.values().sum();
        let depth = dir_path.matches('/').count();

        entries.push(CodeOwnershipEntry {
            path: dir_path,
            primary_author,
            primary_commits,
            total_commits,
            depth,
            is_directory: true,
        });
    }

    // Also add files (after directories)
    let mut file_paths: Vec<String> = file_author_counts.keys().cloned().collect();
    file_paths.sort();

    for file_path in file_paths {
        let author_counts = &file_author_counts[&file_path];
        let (primary_author, primary_commits) = author_counts
            .iter()
            .max_by_key(|(_, c)| *c)
            .map(|(a, c)| (a.clone(), *c))
            .unwrap_or_default();
        let total_commits: usize = author_counts.values().sum();
        let depth = file_path.matches('/').count();

        entries.push(CodeOwnershipEntry {
            path: file_path,
            primary_author,
            primary_commits,
            total_commits,
            depth,
            is_directory: false,
        });
    }

    // Sort by path to interleave directories and files
    entries.sort_by(|a, b| a.path.cmp(&b.path));

    let total_files = file_author_counts.len();
    CodeOwnership {
        entries,
        total_files,
    }
}

/// Calculate statistics from events
pub fn calculate_stats(events: &[&GitEvent]) -> RepoStats {
    let mut author_map: HashMap<String, AuthorStats> = HashMap::new();
    let mut total_insertions = 0usize;
    let mut total_deletions = 0usize;

    for event in events {
        total_insertions += event.files_added;
        total_deletions += event.files_deleted;

        let entry = author_map
            .entry(event.author.clone())
            .or_insert(AuthorStats {
                name: event.author.clone(),
                commit_count: 0,
                insertions: 0,
                deletions: 0,
                last_commit: event.timestamp,
            });

        entry.commit_count += 1;
        entry.insertions += event.files_added;
        entry.deletions += event.files_deleted;

        // Update to the latest commit date
        if event.timestamp > entry.last_commit {
            entry.last_commit = event.timestamp;
        }
    }

    // Sort by commit count descending
    let mut authors: Vec<AuthorStats> = author_map.into_values().collect();
    authors.sort_by(|a, b| b.commit_count.cmp(&a.commit_count));

    RepoStats {
        authors,
        total_commits: events.len(),
        total_insertions,
        total_deletions,
    }
}

#[cfg(test)]
#[allow(clippy::useless_vec)]
mod tests {
    use super::*;
    use chrono::Local;

    fn create_test_event(author: &str, insertions: usize, deletions: usize) -> GitEvent {
        GitEvent::commit(
            "abc1234".to_string(),
            "test commit".to_string(),
            author.to_string(),
            Local::now(),
            insertions,
            deletions,
        )
    }

    fn create_test_event_with_hash(hash: &str) -> GitEvent {
        GitEvent::commit(
            hash.to_string(),
            "test commit".to_string(),
            "author".to_string(),
            Local::now(),
            10,
            5,
        )
    }

    #[test]
    fn test_calculate_stats_empty() {
        let stats = calculate_stats(&[]);
        assert_eq!(stats.total_commits, 0);
        assert_eq!(stats.authors.len(), 0);
    }

    #[test]
    fn test_calculate_stats_single_author() {
        let events = vec![
            create_test_event("Alice", 10, 5),
            create_test_event("Alice", 20, 10),
        ];
        let refs: Vec<&GitEvent> = events.iter().collect();
        let stats = calculate_stats(&refs);

        assert_eq!(stats.total_commits, 2);
        assert_eq!(stats.authors.len(), 1);
        assert_eq!(stats.authors[0].name, "Alice");
        assert_eq!(stats.authors[0].commit_count, 2);
        assert_eq!(stats.authors[0].insertions, 30);
        assert_eq!(stats.authors[0].deletions, 15);
    }

    #[test]
    fn test_calculate_stats_multiple_authors() {
        let events = vec![
            create_test_event("Alice", 10, 5),
            create_test_event("Bob", 5, 2),
            create_test_event("Alice", 20, 10),
            create_test_event("Bob", 15, 8),
            create_test_event("Bob", 10, 5),
        ];
        let refs: Vec<&GitEvent> = events.iter().collect();
        let stats = calculate_stats(&refs);

        assert_eq!(stats.total_commits, 5);
        assert_eq!(stats.authors.len(), 2);

        // Bob has the most commits (3) so comes first
        assert_eq!(stats.authors[0].name, "Bob");
        assert_eq!(stats.authors[0].commit_count, 3);

        // Alice has 2 commits
        assert_eq!(stats.authors[1].name, "Alice");
        assert_eq!(stats.authors[1].commit_count, 2);
    }

    #[test]
    fn test_calculate_stats_totals() {
        let events = vec![
            create_test_event("Alice", 10, 5),
            create_test_event("Bob", 20, 10),
        ];
        let refs: Vec<&GitEvent> = events.iter().collect();
        let stats = calculate_stats(&refs);

        assert_eq!(stats.total_insertions, 30);
        assert_eq!(stats.total_deletions, 15);
    }

    #[test]
    fn test_author_stats_commit_percentage() {
        let author = AuthorStats {
            name: "Alice".to_string(),
            commit_count: 25,
            insertions: 0,
            deletions: 0,
            last_commit: Local::now(),
        };

        assert!((author.commit_percentage(100) - 25.0).abs() < 0.01);
        assert!((author.commit_percentage(50) - 50.0).abs() < 0.01);
    }

    #[test]
    fn test_author_stats_commit_percentage_zero() {
        let author = AuthorStats {
            name: "Alice".to_string(),
            commit_count: 10,
            insertions: 0,
            deletions: 0,
            last_commit: Local::now(),
        };

        assert_eq!(author.commit_percentage(0), 0.0);
    }

    #[test]
    fn test_repo_stats_author_count() {
        let events = vec![
            create_test_event("Alice", 10, 5),
            create_test_event("Bob", 5, 2),
            create_test_event("Charlie", 15, 8),
        ];
        let refs: Vec<&GitEvent> = events.iter().collect();
        let stats = calculate_stats(&refs);

        assert_eq!(stats.author_count(), 3);
    }

    // ===== Heatmap Tests =====

    #[test]
    fn test_calculate_file_heatmap_empty() {
        let events: Vec<&GitEvent> = vec![];
        let heatmap = calculate_file_heatmap(&events, |_| None);
        assert_eq!(heatmap.file_count(), 0);
    }

    #[test]
    fn test_calculate_file_heatmap_single_file() {
        let events = vec![
            create_test_event_with_hash("abc1234"),
            create_test_event_with_hash("def5678"),
        ];
        let refs: Vec<&GitEvent> = events.iter().collect();
        let heatmap = calculate_file_heatmap(&refs, |_| Some(vec!["src/main.rs".to_string()]));

        assert_eq!(heatmap.file_count(), 1);
        assert_eq!(heatmap.files[0].path, "src/main.rs");
        assert_eq!(heatmap.files[0].change_count, 2);
    }

    #[test]
    fn test_calculate_file_heatmap_multiple_files() {
        let events = vec![
            create_test_event_with_hash("abc1234"),
            create_test_event_with_hash("def5678"),
            create_test_event_with_hash("ghi9012"),
        ];
        let refs: Vec<&GitEvent> = events.iter().collect();
        let heatmap = calculate_file_heatmap(&refs, |hash| match hash {
            "abc1234" => Some(vec!["src/a.rs".to_string(), "src/b.rs".to_string()]),
            "def5678" => Some(vec!["src/a.rs".to_string()]),
            "ghi9012" => Some(vec!["src/a.rs".to_string(), "src/c.rs".to_string()]),
            _ => None,
        });

        assert_eq!(heatmap.file_count(), 3);
        // src/a.rs has the most changes (3)
        assert_eq!(heatmap.files[0].path, "src/a.rs");
        assert_eq!(heatmap.files[0].change_count, 3);
    }

    #[test]
    fn test_file_heatmap_entry_heat_level() {
        let entry = FileHeatmapEntry {
            path: "test.rs".to_string(),
            change_count: 5,
            max_changes: 10,
        };
        assert!((entry.heat_level() - 0.5).abs() < 0.01);
    }

    #[test]
    fn test_file_heatmap_entry_heat_bar() {
        let entry_high = FileHeatmapEntry {
            path: "test.rs".to_string(),
            change_count: 10,
            max_changes: 10,
        };
        assert_eq!(entry_high.heat_bar(), "█████");

        let entry_low = FileHeatmapEntry {
            path: "test.rs".to_string(),
            change_count: 1,
            max_changes: 10,
        };
        assert_eq!(entry_low.heat_bar(), "");
    }

    // ===== AggregationLevel Tests =====

    #[test]
    fn test_aggregation_level_next() {
        assert_eq!(AggregationLevel::Files.next(), AggregationLevel::Shallow);
        assert_eq!(AggregationLevel::Shallow.next(), AggregationLevel::Deep);
        assert_eq!(AggregationLevel::Deep.next(), AggregationLevel::Files);
    }

    #[test]
    fn test_aggregation_level_prev() {
        assert_eq!(AggregationLevel::Files.prev(), AggregationLevel::Deep);
        assert_eq!(AggregationLevel::Shallow.prev(), AggregationLevel::Files);
        assert_eq!(AggregationLevel::Deep.prev(), AggregationLevel::Shallow);
    }

    #[test]
    fn test_aggregation_level_display_name() {
        assert_eq!(AggregationLevel::Files.display_name(), "Files");
        assert!(AggregationLevel::Shallow
            .display_name()
            .contains("2 levels"));
        assert!(AggregationLevel::Deep.display_name().contains("top level"));
    }

    #[test]
    fn test_heatmap_with_aggregation_shallow() {
        let heatmap = FileHeatmap {
            files: vec![
                FileHeatmapEntry {
                    path: "src/auth/login.rs".to_string(),
                    change_count: 10,
                    max_changes: 10,
                },
                FileHeatmapEntry {
                    path: "src/auth/token.rs".to_string(),
                    change_count: 5,
                    max_changes: 10,
                },
                FileHeatmapEntry {
                    path: "src/api/user.rs".to_string(),
                    change_count: 3,
                    max_changes: 10,
                },
            ],
            total_files: 3,
            aggregation_level: AggregationLevel::Files,
        };

        let aggregated = heatmap.with_aggregation(AggregationLevel::Shallow);
        assert_eq!(aggregated.aggregation_level, AggregationLevel::Shallow);
        assert_eq!(aggregated.files.len(), 2); // src/auth/ and src/api/

        // src/auth/ has the most (10+5=15)
        assert_eq!(aggregated.files[0].path, "src/auth/");
        assert_eq!(aggregated.files[0].change_count, 15);
    }

    #[test]
    fn test_heatmap_with_aggregation_deep() {
        let heatmap = FileHeatmap {
            files: vec![
                FileHeatmapEntry {
                    path: "src/auth/login.rs".to_string(),
                    change_count: 10,
                    max_changes: 10,
                },
                FileHeatmapEntry {
                    path: "src/api/user.rs".to_string(),
                    change_count: 5,
                    max_changes: 10,
                },
                FileHeatmapEntry {
                    path: "tests/test.rs".to_string(),
                    change_count: 3,
                    max_changes: 10,
                },
            ],
            total_files: 3,
            aggregation_level: AggregationLevel::Files,
        };

        let aggregated = heatmap.with_aggregation(AggregationLevel::Deep);
        assert_eq!(aggregated.aggregation_level, AggregationLevel::Deep);
        assert_eq!(aggregated.files.len(), 2); // src/ and tests/

        // src/ has the most (10+5=15)
        assert_eq!(aggregated.files[0].path, "src/");
        assert_eq!(aggregated.files[0].change_count, 15);
    }
}