debtmap 0.16.6

Code complexity and technical debt analyzer
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
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
//! Pure aggregation functions for god object metrics.
//!
//! This module provides composable functions to aggregate metrics from
//! member functions into god object-level metrics.
//!
//! # Aggregation Strategies
//!
//! - **Complexity**: SUM of all functions (total burden)
//! - **Coverage**: Weighted average by function length
//! - **Dependencies**: Aggregated from ALL raw FunctionMetrics (complete architectural view)
//! - **Contextual Risk**: Average across member functions
//!
//! ## Dependency Aggregation
//!
//! Dependencies are aggregated from raw FunctionMetrics to provide a complete
//! architectural view of god object dependencies. This ensures that even if
//! individual functions don't exceed complexity thresholds, the god object
//! still shows all its cross-file dependencies for proper assessment.
//!
//! ## Complexity Distribution Analysis (Spec 268)
//!
//! For file-scope items, we now analyze how complexity is distributed:
//! - **Concentrated**: Max complexity > 50% of total → likely god function
//! - **Distributed**: Max complexity < 20% of total → well-structured file
//! - **Mixed**: Between 20-50% → needs investigation
//!
//! This helps distinguish "many simple functions" from "one god function".
//!
//! # Examples
//!
//! ```rust,ignore
//! let members = extract_member_functions(items.iter(), &file_path);
//! let metrics = aggregate_god_object_metrics(&members);
//!
//! assert!(metrics.total_cyclomatic > 0);
//! assert!(metrics.weighted_coverage.is_some());
//! ```

use crate::complexity::entropy_core::{EntropyConfig, EntropyScore, UniversalEntropyCalculator};
use crate::complexity::EntropyAnalysis;
use crate::core::FunctionMetrics;
use crate::priority::{TransitiveCoverage, UnifiedDebtItem};
use crate::risk::context::ContextualRisk;
use crate::risk::lcov::LcovData;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::path::Path;

/// Default threshold for flagging individual functions as complex (Spec 268).
pub const FUNCTION_COMPLEXITY_THRESHOLD: u32 = 15;

/// Classification of how complexity is distributed across functions in a file.
///
/// Used to distinguish between:
/// - Files with one dominant god function (Concentrated)
/// - Files with many small, well-structured functions (Distributed)
/// - Files that need further investigation (Mixed)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ComplexityDistribution {
    /// Max complexity > 50% of total - likely contains god function(s)
    Concentrated,
    /// Max complexity 20-50% of total - needs investigation
    Mixed,
    /// Max complexity < 20% of total - well-structured file
    Distributed,
}

impl ComplexityDistribution {
    /// Human-readable name for display
    pub fn display_name(&self) -> &'static str {
        match self {
            Self::Concentrated => "Concentrated",
            Self::Mixed => "Mixed",
            Self::Distributed => "Distributed",
        }
    }

    /// Explanation of what the classification means for refactoring
    pub fn classification_explanation(&self) -> &'static str {
        match self {
            Self::Concentrated => "Contains god function(s) - refactoring recommended",
            Self::Mixed => "Some complexity concentration - review recommended",
            Self::Distributed => "Well-Structured File - complexity evenly distributed",
        }
    }
}

/// Distribution metrics for file-scope complexity analysis (Spec 268).
///
/// These metrics help distinguish between:
/// - A file with many simple functions (low max, distributed complexity)
/// - A file with one or more god functions (high max, concentrated complexity)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DistributionMetrics {
    /// Number of functions in the file
    pub function_count: usize,
    /// Highest cyclomatic complexity among all functions
    pub max_complexity: u32,
    /// Average cyclomatic complexity per function
    pub avg_complexity: f64,
    /// Median cyclomatic complexity (robust to outliers)
    pub median_complexity: u32,
    /// Number of functions exceeding the complexity threshold
    pub exceeding_threshold: usize,
    /// Classification based on complexity distribution
    pub distribution: ComplexityDistribution,
    /// Production code lines (excluding test modules)
    pub production_loc: usize,
    /// Test code lines (inside #[cfg(test)] modules)
    pub test_loc: usize,
}

/// Aggregated metrics from member functions.
#[derive(Debug, Clone)]
pub struct GodObjectAggregatedMetrics {
    pub total_cyclomatic: u32,
    pub total_cognitive: u32,
    pub max_nesting_depth: u32,
    pub weighted_coverage: Option<TransitiveCoverage>,
    pub unique_upstream_callers: Vec<String>,
    pub unique_downstream_callees: Vec<String>,
    pub upstream_dependencies: usize,
    pub downstream_dependencies: usize,
    pub aggregated_contextual_risk: Option<ContextualRisk>,
    /// Total count of error swallowing patterns across all functions
    pub total_error_swallowing_count: u32,
    /// Unique error swallowing pattern types found
    pub error_swallowing_patterns: Vec<String>,
    /// Aggregated entropy analysis from member functions (Spec 218)
    pub aggregated_entropy: Option<EntropyAnalysis>,
    /// Distribution metrics for file-scope analysis (Spec 268)
    pub distribution_metrics: Option<DistributionMetrics>,
}

/// Extract member functions for a file.
///
/// Pure function that filters items by file path.
#[inline]
pub fn extract_member_functions<'a>(
    items: impl Iterator<Item = &'a UnifiedDebtItem>,
    file_path: &Path,
) -> Vec<&'a UnifiedDebtItem> {
    items
        .filter(|item| item.location.file == file_path)
        .collect()
}

/// Aggregate complexity: sum cyclomatic/cognitive, max nesting.
pub fn aggregate_complexity_metrics(members: &[&UnifiedDebtItem]) -> (u32, u32, u32) {
    let total_cyclomatic = members.iter().map(|m| m.cyclomatic_complexity).sum();
    let total_cognitive = members.iter().map(|m| m.cognitive_complexity).sum();
    let max_nesting = members.iter().map(|m| m.nesting_depth).max().unwrap_or(0);

    (total_cyclomatic, total_cognitive, max_nesting)
}

/// Aggregate coverage: weighted average by function length.
pub fn aggregate_coverage_metrics(members: &[&UnifiedDebtItem]) -> Option<TransitiveCoverage> {
    let coverages: Vec<_> = members
        .iter()
        .filter_map(|m| {
            m.transitive_coverage
                .as_ref()
                .map(|c| (c, m.function_length))
        })
        .collect();

    if coverages.is_empty() {
        return None;
    }

    let total_length: usize = coverages.iter().map(|(_, len)| len).sum();
    if total_length == 0 {
        return None;
    }

    let weighted_direct = coverages
        .iter()
        .map(|(cov, len)| cov.direct * (*len as f64))
        .sum::<f64>()
        / total_length as f64;

    let weighted_transitive = coverages
        .iter()
        .map(|(cov, len)| cov.transitive * (*len as f64))
        .sum::<f64>()
        / total_length as f64;

    // Collect all unique uncovered lines
    let uncovered_lines: Vec<usize> = coverages
        .iter()
        .flat_map(|(cov, _)| &cov.uncovered_lines)
        .copied()
        .collect::<HashSet<_>>()
        .into_iter()
        .collect();

    // Collect all unique propagated_from function IDs
    let propagated_from = coverages
        .iter()
        .flat_map(|(cov, _)| &cov.propagated_from)
        .cloned()
        .collect::<HashSet<_>>()
        .into_iter()
        .collect();

    Some(TransitiveCoverage {
        direct: weighted_direct,
        transitive: weighted_transitive,
        propagated_from,
        uncovered_lines,
    })
}

// =============================================================================
// Distribution Metrics Functions (Spec 268)
// =============================================================================

/// Calculate the median of a slice of complexity values.
///
/// Pure function that computes the median without modifying input.
/// Returns 0 for empty slices.
pub fn calculate_median(values: &[u32]) -> u32 {
    if values.is_empty() {
        return 0;
    }

    let mut sorted: Vec<u32> = values.to_vec();
    sorted.sort_unstable();

    let mid = sorted.len() / 2;
    if sorted.len() % 2 == 0 {
        // Even number of elements: average of two middle values
        (sorted[mid - 1] + sorted[mid]) / 2
    } else {
        // Odd number of elements: middle value
        sorted[mid]
    }
}

/// Classify complexity distribution based on max/total ratio.
///
/// - Concentrated: max > 50% of total (one function dominates)
/// - Distributed: max < 20% of total (well-structured file)
/// - Mixed: 20-50% (needs investigation)
pub fn classify_distribution(max_complexity: u32, total_complexity: u32) -> ComplexityDistribution {
    if total_complexity == 0 {
        return ComplexityDistribution::Distributed;
    }

    let ratio = max_complexity as f64 / total_complexity as f64;

    if ratio > 0.5 {
        ComplexityDistribution::Concentrated
    } else if ratio > 0.2 {
        ComplexityDistribution::Mixed
    } else {
        ComplexityDistribution::Distributed
    }
}

/// Calculate distribution metrics from UnifiedDebtItem members (Spec 268).
///
/// Returns metrics describing how complexity is distributed across functions,
/// helping distinguish well-structured files from those with god functions.
pub fn aggregate_distribution_metrics(members: &[&UnifiedDebtItem]) -> DistributionMetrics {
    let complexities: Vec<u32> = members.iter().map(|m| m.cyclomatic_complexity).collect();

    let total: u32 = complexities.iter().sum();
    let max = complexities.iter().max().copied().unwrap_or(0);
    let count = complexities.len();

    let avg = if count > 0 {
        total as f64 / count as f64
    } else {
        0.0
    };

    let median = calculate_median(&complexities);

    let exceeding = complexities
        .iter()
        .filter(|&&c| c > FUNCTION_COMPLEXITY_THRESHOLD)
        .count();

    let distribution = classify_distribution(max, total);

    // Calculate LOC from function lengths
    let production_loc: usize = members.iter().map(|m| m.function_length).sum();

    DistributionMetrics {
        function_count: count,
        max_complexity: max,
        avg_complexity: avg,
        median_complexity: median,
        exceeding_threshold: exceeding,
        distribution,
        production_loc,
        test_loc: 0, // Updated separately via AST analysis
    }
}

/// Calculate distribution metrics from raw FunctionMetrics (Spec 268).
///
/// This version works with raw metrics before filtering, providing complete
/// distribution analysis including test code separation.
pub fn aggregate_distribution_metrics_from_raw(
    functions: &[FunctionMetrics],
) -> DistributionMetrics {
    // Separate production and test functions
    let production_functions: Vec<_> = functions.iter().filter(|f| !f.is_test).collect();
    let test_functions: Vec<_> = functions.iter().filter(|f| f.is_test).collect();

    let complexities: Vec<u32> = production_functions.iter().map(|f| f.cyclomatic).collect();

    let total: u32 = complexities.iter().sum();
    let max = complexities.iter().max().copied().unwrap_or(0);
    let count = complexities.len();

    let avg = if count > 0 {
        total as f64 / count as f64
    } else {
        0.0
    };

    let median = calculate_median(&complexities);

    let exceeding = complexities
        .iter()
        .filter(|&&c| c > FUNCTION_COMPLEXITY_THRESHOLD)
        .count();

    let distribution = classify_distribution(max, total);

    // Calculate LOC separately for production and test code
    let production_loc: usize = production_functions.iter().map(|f| f.length).sum();
    let test_loc: usize = test_functions.iter().map(|f| f.length).sum();

    DistributionMetrics {
        function_count: count,
        max_complexity: max,
        avg_complexity: avg,
        median_complexity: median,
        exceeding_threshold: exceeding,
        distribution,
        production_loc,
        test_loc,
    }
}

/// Aggregate dependencies: unique set deduplication.
pub fn aggregate_dependency_metrics(
    members: &[&UnifiedDebtItem],
) -> (Vec<String>, Vec<String>, usize, usize) {
    let mut unique_callers: HashSet<String> = HashSet::new();
    let mut unique_callees: HashSet<String> = HashSet::new();

    for item in members {
        unique_callers.extend(item.upstream_callers.iter().cloned());
        unique_callees.extend(item.downstream_callees.iter().cloned());
    }

    let upstream_count = unique_callers.len();
    let downstream_count = unique_callees.len();

    (
        unique_callers.into_iter().collect(),
        unique_callees.into_iter().collect(),
        upstream_count,
        downstream_count,
    )
}

/// Aggregate contextual risk: combine base and contextual risk from members.
pub fn aggregate_contextual_risk(members: &[&UnifiedDebtItem]) -> Option<ContextualRisk> {
    let risks: Vec<_> = members
        .iter()
        .filter_map(|m| m.contextual_risk.as_ref())
        .collect();

    if risks.is_empty() {
        return None;
    }

    // Average base risk
    let avg_base_risk = risks.iter().map(|r| r.base_risk).sum::<f64>() / risks.len() as f64;

    // Average contextual risk
    let avg_contextual_risk =
        risks.iter().map(|r| r.contextual_risk).sum::<f64>() / risks.len() as f64;

    // Collect all unique contexts
    let all_contexts: Vec<_> = risks.iter().flat_map(|r| &r.contexts).cloned().collect();

    let explanation = format!(
        "Aggregated from {} functions (avg base: {:.1}, avg contextual: {:.1})",
        risks.len(),
        avg_base_risk,
        avg_contextual_risk
    );

    Some(ContextualRisk {
        base_risk: avg_base_risk,
        contextual_risk: avg_contextual_risk,
        contexts: all_contexts,
        explanation,
    })
}

/// Aggregate error swallowing metrics from FunctionMetrics.
pub fn aggregate_error_swallowing(functions: &[FunctionMetrics]) -> (u32, Vec<String>) {
    let total_count = functions
        .iter()
        .filter_map(|f| f.error_swallowing_count)
        .sum();

    let mut unique_patterns: HashSet<String> = HashSet::new();
    for func in functions {
        if let Some(ref patterns) = func.error_swallowing_patterns {
            unique_patterns.extend(patterns.iter().cloned());
        }
    }

    (total_count, unique_patterns.into_iter().collect())
}

/// Aggregate dependency metrics from raw FunctionMetrics.
///
/// This provides a complete architectural view of dependencies by aggregating
/// from ALL functions in the file, not just those that became debt items.
/// This ensures god objects show their true blast radius.
pub fn aggregate_dependency_metrics_from_raw(
    functions: &[FunctionMetrics],
) -> (Vec<String>, Vec<String>, usize, usize) {
    let mut unique_callers: HashSet<String> = HashSet::new();
    let mut unique_callees: HashSet<String> = HashSet::new();

    for func in functions {
        if let Some(ref callers) = func.upstream_callers {
            unique_callers.extend(callers.iter().cloned());
        }
        if let Some(ref callees) = func.downstream_callees {
            unique_callees.extend(callees.iter().cloned());
        }
    }

    let upstream_count = unique_callers.len();
    let downstream_count = unique_callees.len();

    (
        unique_callers.into_iter().collect(),
        unique_callees.into_iter().collect(),
        upstream_count,
        downstream_count,
    )
}

/// Compute weighted average from (value, weight) pairs.
/// Pure function: returns None if total weight is zero.
fn compute_weighted_average<I>(iter: I) -> Option<f64>
where
    I: Iterator<Item = (f64, usize)>,
{
    let (sum, total_weight) = iter.fold((0.0, 0usize), |(sum, total), (value, weight)| {
        (sum + value * (weight as f64), total + weight)
    });
    (total_weight > 0).then(|| sum / total_weight as f64)
}

/// Sum complexity values from entropy data.
fn sum_complexity(entropy_data: &[(&EntropyAnalysis, usize)]) -> (u32, u32) {
    entropy_data.iter().fold((0, 0), |(orig, adj), (e, _)| {
        (orig + e.original_complexity, adj + e.adjusted_complexity)
    })
}

/// Aggregate reasoning strings, deduplicating and limiting to top 5.
fn aggregate_reasoning(entropy_data: &[(&EntropyAnalysis, usize)]) -> Vec<String> {
    let mut reasoning: Vec<String> = entropy_data
        .iter()
        .flat_map(|(e, _)| e.reasoning.iter().cloned())
        .collect();
    reasoning.dedup();
    reasoning.truncate(5);
    reasoning
}

/// Aggregate entropy analysis from member UnifiedDebtItems (Spec 218).
///
/// Returns weighted average entropy metrics based on function length.
/// Uses original (undampened) complexity values for the aggregate summary.
pub fn aggregate_entropy_metrics(members: &[&UnifiedDebtItem]) -> Option<EntropyAnalysis> {
    let entropy_data: Vec<_> = members
        .iter()
        .filter_map(|m| m.entropy_analysis.as_ref().map(|e| (e, m.function_length)))
        .collect();

    if entropy_data.is_empty() {
        return None;
    }

    let weighted_entropy =
        compute_weighted_average(entropy_data.iter().map(|(e, len)| (e.entropy_score, *len)))?;
    let weighted_repetition = compute_weighted_average(
        entropy_data
            .iter()
            .map(|(e, len)| (e.pattern_repetition, *len)),
    )?;
    let weighted_branch_similarity = compute_weighted_average(
        entropy_data
            .iter()
            .map(|(e, len)| (e.branch_similarity, *len)),
    )?;
    let weighted_dampening = compute_weighted_average(
        entropy_data
            .iter()
            .map(|(e, len)| (e.dampening_factor, *len)),
    )?;

    let (total_original, total_adjusted) = sum_complexity(&entropy_data);
    let reasoning = aggregate_reasoning(&entropy_data);

    Some(EntropyAnalysis {
        entropy_score: weighted_entropy,
        pattern_repetition: weighted_repetition,
        branch_similarity: weighted_branch_similarity,
        dampening_factor: weighted_dampening,
        dampening_was_applied: weighted_dampening < 1.0,
        original_complexity: total_original,
        adjusted_complexity: total_adjusted,
        reasoning,
    })
}

/// Aggregate all metrics (composition of above functions).
pub fn aggregate_god_object_metrics(members: &[&UnifiedDebtItem]) -> GodObjectAggregatedMetrics {
    let (total_cyc, total_cog, max_nest) = aggregate_complexity_metrics(members);
    let weighted_cov = aggregate_coverage_metrics(members);
    let (callers, callees, up_count, down_count) = aggregate_dependency_metrics(members);
    let contextual_risk = aggregate_contextual_risk(members);
    let entropy = aggregate_entropy_metrics(members);
    let distribution = aggregate_distribution_metrics(members);

    // Note: Error swallowing is aggregated from raw FunctionMetrics, not UnifiedDebtItem
    // This function sets defaults; use aggregate_from_raw_metrics for full error swallowing data
    GodObjectAggregatedMetrics {
        total_cyclomatic: total_cyc,
        total_cognitive: total_cog,
        max_nesting_depth: max_nest,
        weighted_coverage: weighted_cov,
        unique_upstream_callers: callers,
        unique_downstream_callees: callees,
        upstream_dependencies: up_count,
        downstream_dependencies: down_count,
        aggregated_contextual_risk: contextual_risk,
        total_error_swallowing_count: 0,
        error_swallowing_patterns: Vec::new(),
        aggregated_entropy: entropy,
        distribution_metrics: Some(distribution),
    }
}

// =============================================================================
// Pure helper functions for entropy aggregation (Stillwater principles)
// =============================================================================

/// Extracts entropy data tuples from function metrics.
///
/// Pure function - filters functions that have entropy scores and returns
/// tuples of (entropy_score, length, cognitive_complexity).
fn extract_entropy_data(functions: &[FunctionMetrics]) -> Vec<(&EntropyScore, usize, u32)> {
    functions
        .iter()
        .filter_map(|f| f.entropy_score.as_ref().map(|e| (e, f.length, f.cognitive)))
        .collect()
}

/// Calculates weighted average of a metric from entropy data.
///
/// Pure function that computes a length-weighted average using the provided
/// extractor function.
fn weighted_average<F>(data: &[(&EntropyScore, usize, u32)], total_length: usize, f: F) -> f64
where
    F: Fn(&EntropyScore) -> f64,
{
    data.iter()
        .map(|(e, len, _)| f(e) * (*len as f64))
        .sum::<f64>()
        / total_length as f64
}

/// Sums a u32 field from entropy data tuples.
///
/// Pure function for aggregating cognitive complexity values.
fn sum_cognitive(data: &[(&EntropyScore, usize, u32)]) -> u32 {
    data.iter().map(|(_, _, cog)| cog).sum()
}

/// Calculates total length from entropy data tuples.
fn total_length(data: &[(&EntropyScore, usize, u32)]) -> usize {
    data.iter().map(|(_, len, _)| *len).sum()
}

/// Aggregate entropy from raw FunctionMetrics (Spec 218).
///
/// Returns weighted average entropy based on function length from ALL functions,
/// not just those that became debt items.
///
/// Composed from pure helper functions following Stillwater principles.
pub fn aggregate_entropy_from_raw(functions: &[FunctionMetrics]) -> Option<EntropyAnalysis> {
    let data = extract_entropy_data(functions);
    let len = total_length(&data);

    if data.is_empty() || len == 0 {
        return None;
    }

    let entropy = weighted_average(&data, len, |e| e.token_entropy);
    let repetition = weighted_average(&data, len, |e| e.pattern_repetition);
    let branch_similarity = weighted_average(&data, len, |e| e.branch_similarity);
    let total_cognitive = sum_cognitive(&data);

    let calculator = UniversalEntropyCalculator::new(EntropyConfig::default());
    let dampening_factor = calculator.calculate_dampening_factor(entropy, repetition);
    let adjusted_complexity = (total_cognitive as f64 * dampening_factor) as u32;

    Some(EntropyAnalysis {
        entropy_score: entropy,
        pattern_repetition: repetition,
        branch_similarity,
        dampening_factor,
        dampening_was_applied: dampening_factor < 1.0,
        original_complexity: total_cognitive,
        adjusted_complexity,
        reasoning: vec![format!("Aggregated from {} functions", functions.len())],
    })
}

/// Aggregate coverage from raw FunctionMetrics using LCOV data.
///
/// This function looks up coverage for ALL functions in the file from LCOV data,
/// not just those that became UnifiedDebtItems. This ensures god objects show
/// accurate coverage metrics even when member functions are filtered out by
/// complexity thresholds.
///
/// Returns a weighted average coverage based on function length.
pub fn aggregate_coverage_from_raw_metrics(
    functions: &[FunctionMetrics],
    coverage: &LcovData,
) -> Option<TransitiveCoverage> {
    if functions.is_empty() {
        return None;
    }

    // Collect coverage data for each function
    let mut coverage_data: Vec<(f64, usize, Vec<usize>)> = Vec::with_capacity(functions.len());

    for func in functions {
        let end_line = func.line + func.length.saturating_sub(1);
        // Use get_function_coverage_with_bounds for accurate AST-based matching
        let direct_coverage = coverage
            .get_function_coverage_with_bounds(&func.file, &func.name, func.line, end_line)
            .unwrap_or(0.0);

        let uncovered = coverage
            .get_function_uncovered_lines(&func.file, &func.name, func.line)
            .unwrap_or_default();

        coverage_data.push((direct_coverage, func.length, uncovered));
    }

    let total_length: usize = coverage_data.iter().map(|(_, len, _)| len).sum();
    if total_length == 0 {
        return None;
    }

    // Calculate weighted average coverage
    let weighted_direct = coverage_data
        .iter()
        .map(|(cov, len, _)| cov * (*len as f64))
        .sum::<f64>()
        / total_length as f64;

    // Collect all uncovered lines (deduplicated)
    let all_uncovered: Vec<usize> = coverage_data
        .iter()
        .flat_map(|(_, _, uncovered)| uncovered.iter().copied())
        .collect::<HashSet<_>>()
        .into_iter()
        .collect();

    Some(TransitiveCoverage {
        direct: weighted_direct,
        transitive: weighted_direct, // For god objects, transitive == direct
        propagated_from: vec![],
        uncovered_lines: all_uncovered,
    })
}

/// Aggregate metrics directly from raw FunctionMetrics (for ALL functions including tests).
///
/// This function aggregates complexity and dependencies from raw function metrics
/// before any filtering, ensuring god objects show:
/// - TRUE complexity of all their functions
/// - TRUE architectural dependencies (complete blast radius)
/// - Distribution metrics with production/test LOC separation (Spec 268)
///
/// Note: Coverage is NOT aggregated here. Use `aggregate_coverage_from_raw_metrics`
/// separately with LCOV data for coverage metrics.
pub fn aggregate_from_raw_metrics(functions: &[FunctionMetrics]) -> GodObjectAggregatedMetrics {
    let total_cyclomatic = functions.iter().map(|f| f.cyclomatic).sum();
    let total_cognitive = functions.iter().map(|f| f.cognitive).sum();
    let max_nesting = functions.iter().map(|f| f.nesting).max().unwrap_or(0);

    // Aggregate error swallowing from raw metrics
    let (total_error_swallowing, error_patterns) = aggregate_error_swallowing(functions);

    // Aggregate entropy from raw metrics (available for all functions)
    let aggregated_entropy = aggregate_entropy_from_raw(functions);

    // Aggregate dependencies from raw metrics (complete architectural view)
    let (
        unique_upstream_callers,
        unique_downstream_callees,
        upstream_dependencies,
        downstream_dependencies,
    ) = aggregate_dependency_metrics_from_raw(functions);

    // Aggregate distribution metrics with production/test LOC separation (Spec 268)
    let distribution_metrics = aggregate_distribution_metrics_from_raw(functions);

    GodObjectAggregatedMetrics {
        total_cyclomatic,
        total_cognitive,
        max_nesting_depth: max_nesting,
        weighted_coverage: None,
        unique_upstream_callers,
        unique_downstream_callees,
        upstream_dependencies,
        downstream_dependencies,
        aggregated_contextual_risk: None,
        total_error_swallowing_count: total_error_swallowing,
        error_swallowing_patterns: error_patterns,
        aggregated_entropy,
        distribution_metrics: Some(distribution_metrics),
    }
}

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

    use crate::complexity::EntropyAnalysis;
    use crate::priority::{
        ActionableRecommendation, DebtType, FunctionRole, ImpactMetrics, Location, UnifiedScore,
    };
    use std::path::PathBuf;

    fn create_test_item(
        file: &str,
        cyc: u32,
        cog: u32,
        nest: u32,
        length: usize,
    ) -> UnifiedDebtItem {
        UnifiedDebtItem {
            location: Location {
                file: PathBuf::from(file),
                function: "test_fn".to_string(),
                line: 1,
            },
            debt_type: DebtType::Complexity {
                cyclomatic: cyc,
                cognitive: cog,
            },
            unified_score: UnifiedScore {
                final_score: 50.0,
                complexity_factor: 5.0,
                coverage_factor: 0.0,
                dependency_factor: 0.0,
                role_multiplier: 1.0,
                base_score: None,
                exponential_factor: None,
                risk_boost: None,
                pre_adjustment_score: None,
                adjustment_applied: None,
                purity_factor: None,
                refactorability_factor: None,
                pattern_factor: None,
                // Spec 260: Score transparency fields
                debt_adjustment: None,
                pre_normalization_score: None,
                structural_multiplier: Some(1.0),
                has_coverage_data: false,
                contextual_risk_multiplier: None,
                pre_contextual_score: None,
                debt_type_multiplier: None,
            },
            function_role: FunctionRole::Unknown,
            recommendation: ActionableRecommendation {
                primary_action: "Refactor".to_string(),
                rationale: "Test".to_string(),
                implementation_steps: Vec::new(),
                related_items: Vec::new(),
                steps: None,
                estimated_effort_hours: None,
            },
            expected_impact: ImpactMetrics {
                coverage_improvement: 0.0,
                lines_reduction: 0,
                complexity_reduction: 0.0,
                risk_reduction: 0.0,
            },
            transitive_coverage: None,
            upstream_dependencies: 0,
            downstream_dependencies: 0,
            upstream_callers: Vec::new(),
            downstream_callees: Vec::new(),
            upstream_production_callers: Vec::new(),
            upstream_test_callers: Vec::new(),
            production_blast_radius: 0,
            nesting_depth: nest,
            function_length: length,
            cyclomatic_complexity: cyc,
            cognitive_complexity: cog,
            is_pure: None,
            purity_confidence: None,
            purity_level: None,
            god_object_indicators: None,
            tier: None,
            function_context: None,
            context_confidence: None,
            contextual_recommendation: None,
            pattern_analysis: None,
            file_context: None,
            context_multiplier: None,
            context_type: None,
            language_specific: None,
            detected_pattern: None,
            contextual_risk: None,
            file_line_count: None,
            responsibility_category: None,
            error_swallowing_count: None,
            error_swallowing_patterns: None,
            entropy_analysis: None,
            context_suggestion: None,
        }
    }

    #[test]
    fn test_complexity_aggregation_sums_and_maxes() {
        let members = vec![
            create_test_item("file.rs", 5, 10, 2, 50),
            create_test_item("file.rs", 10, 15, 5, 100),
            create_test_item("file.rs", 15, 20, 3, 75),
        ];
        let member_refs: Vec<_> = members.iter().collect();

        let (total_cyc, total_cog, max_nest) = aggregate_complexity_metrics(&member_refs);

        assert_eq!(total_cyc, 30); // 5 + 10 + 15
        assert_eq!(total_cog, 45); // 10 + 15 + 20
        assert_eq!(max_nest, 5); // max(2, 5, 3)
    }

    #[test]
    fn test_coverage_weighted_average() {
        let mut members = vec![
            create_test_item("file.rs", 0, 0, 0, 10),
            create_test_item("file.rs", 0, 0, 0, 50),
            create_test_item("file.rs", 0, 0, 0, 40),
        ];

        // Add coverage data
        members[0].transitive_coverage = Some(TransitiveCoverage {
            direct: 0.8,
            transitive: 0.9,
            propagated_from: vec![],
            uncovered_lines: vec![],
        });
        members[1].transitive_coverage = Some(TransitiveCoverage {
            direct: 0.2,
            transitive: 0.3,
            propagated_from: vec![],
            uncovered_lines: vec![],
        });
        members[2].transitive_coverage = Some(TransitiveCoverage {
            direct: 0.5,
            transitive: 0.6,
            propagated_from: vec![],
            uncovered_lines: vec![],
        });

        let member_refs: Vec<_> = members.iter().collect();
        let cov = aggregate_coverage_metrics(&member_refs).unwrap();

        // (10*0.8 + 50*0.2 + 40*0.5) / 100 = 38/100 = 0.38
        assert!((cov.direct - 0.38).abs() < 0.01);
        assert!((cov.transitive - 0.48).abs() < 0.01); // (10*0.9 + 50*0.3 + 40*0.6) / 100
    }

    #[test]
    fn test_dependencies_deduplicate() {
        let mut members = vec![
            create_test_item("file.rs", 0, 0, 0, 10),
            create_test_item("file.rs", 0, 0, 0, 20),
        ];

        members[0].upstream_callers = vec!["main".to_string(), "init".to_string()];
        members[0].downstream_callees = vec!["log".to_string()];
        members[1].upstream_callers = vec!["main".to_string(), "process".to_string()]; // "main" is duplicate
        members[1].downstream_callees = vec!["log".to_string(), "db".to_string()]; // "log" is duplicate

        let member_refs: Vec<_> = members.iter().collect();
        let (callers, _callees, up_count, down_count) = aggregate_dependency_metrics(&member_refs);

        assert_eq!(up_count, 3); // main, init, process (deduplicated)
        assert_eq!(down_count, 2); // log, db (deduplicated)
        assert!(callers.contains(&"main".to_string()));
        assert!(callers.contains(&"init".to_string()));
        assert!(callers.contains(&"process".to_string()));
    }

    #[test]
    fn test_extract_member_functions() {
        let items = vec![
            create_test_item("file1.rs", 5, 10, 2, 50),
            create_test_item("file2.rs", 10, 15, 3, 100),
            create_test_item("file1.rs", 15, 20, 4, 75),
        ];

        let members = extract_member_functions(items.iter(), Path::new("file1.rs"));

        assert_eq!(members.len(), 2);
        assert!(members
            .iter()
            .all(|m| m.location.file == Path::new("file1.rs")));
    }

    #[test]
    fn test_aggregate_god_object_metrics_composition() {
        let members = vec![
            create_test_item("file.rs", 5, 10, 2, 50),
            create_test_item("file.rs", 10, 15, 5, 100),
        ];
        let member_refs: Vec<_> = members.iter().collect();

        let metrics = aggregate_god_object_metrics(&member_refs);

        assert_eq!(metrics.total_cyclomatic, 15);
        assert_eq!(metrics.total_cognitive, 25);
        assert_eq!(metrics.max_nesting_depth, 5);
        assert!(metrics.weighted_coverage.is_none()); // No coverage data
    }

    #[test]
    fn test_aggregate_error_swallowing() {
        let functions = vec![
            FunctionMetrics {
                name: "func1".to_string(),
                file: PathBuf::from("test.rs"),
                line: 1,
                cyclomatic: 5,
                cognitive: 5,
                nesting: 1,
                length: 20,
                is_test: false,
                visibility: None,
                is_trait_method: false,
                in_test_module: false,
                entropy_score: None,
                is_pure: None,
                purity_confidence: None,
                purity_reason: None,
                call_dependencies: None,
                detected_patterns: None,
                upstream_callers: None,
                downstream_callees: None,
                mapping_pattern_result: None,
                adjusted_complexity: None,
                composition_metrics: None,
                language_specific: None,
                purity_level: None,
                error_swallowing_count: Some(2),
                error_swallowing_patterns: Some(vec![
                    "if let Ok(...) without else branch".to_string()
                ]),
                entropy_analysis: None,
            },
            FunctionMetrics {
                name: "func2".to_string(),
                file: PathBuf::from("test.rs"),
                line: 25,
                cyclomatic: 3,
                cognitive: 3,
                nesting: 1,
                length: 15,
                is_test: false,
                visibility: None,
                is_trait_method: false,
                in_test_module: false,
                entropy_score: None,
                is_pure: None,
                purity_confidence: None,
                purity_reason: None,
                call_dependencies: None,
                detected_patterns: None,
                upstream_callers: None,
                downstream_callees: None,
                mapping_pattern_result: None,
                adjusted_complexity: None,
                composition_metrics: None,
                language_specific: None,
                purity_level: None,
                error_swallowing_count: Some(3),
                error_swallowing_patterns: Some(vec![
                    "if let Ok(...) without else branch".to_string(),
                    "let _ = discarding Result".to_string(),
                ]),
                entropy_analysis: None,
            },
            FunctionMetrics {
                name: "func3".to_string(),
                file: PathBuf::from("test.rs"),
                line: 50,
                cyclomatic: 2,
                cognitive: 2,
                nesting: 1,
                length: 10,
                is_test: false,
                visibility: None,
                is_trait_method: false,
                in_test_module: false,
                entropy_score: None,
                is_pure: None,
                purity_confidence: None,
                purity_reason: None,
                call_dependencies: None,
                detected_patterns: None,
                upstream_callers: None,
                downstream_callees: None,
                mapping_pattern_result: None,
                adjusted_complexity: None,
                composition_metrics: None,
                language_specific: None,
                purity_level: None,
                error_swallowing_count: None, // No error swallowing
                error_swallowing_patterns: None,
                entropy_analysis: None,
            },
        ];

        let (total, patterns) = aggregate_error_swallowing(&functions);

        assert_eq!(total, 5); // 2 + 3 = 5
        assert_eq!(patterns.len(), 2); // 2 unique patterns
        assert!(patterns.contains(&"if let Ok(...) without else branch".to_string()));
        assert!(patterns.contains(&"let _ = discarding Result".to_string()));
    }

    #[test]
    fn test_aggregate_entropy_metrics_weighted_average() {
        // Create items with different entropy details and lengths
        let mut item1 = create_test_item("file.rs", 10, 20, 2, 100); // length 100
        item1.entropy_analysis = Some(EntropyAnalysis {
            entropy_score: 0.4,
            pattern_repetition: 0.6,
            branch_similarity: 0.3,
            original_complexity: 20,
            adjusted_complexity: 16,
            dampening_factor: 0.8,
            dampening_was_applied: true,
            reasoning: vec![],
        });

        let mut item2 = create_test_item("file.rs", 15, 30, 3, 200); // length 200
        item2.entropy_analysis = Some(EntropyAnalysis {
            entropy_score: 0.5,
            pattern_repetition: 0.3,
            branch_similarity: 0.2,
            original_complexity: 30,
            adjusted_complexity: 27,
            dampening_factor: 0.9,
            dampening_was_applied: true,
            reasoning: vec![],
        });

        let members = vec![&item1, &item2];
        let result = aggregate_entropy_metrics(&members).expect("should have entropy");

        // Weighted average: (100*0.4 + 200*0.5) / 300 = 140/300 ≈ 0.467
        assert!((result.entropy_score - 0.467).abs() < 0.01);

        // Weighted repetition: (100*0.6 + 200*0.3) / 300 = 120/300 = 0.4
        assert!((result.pattern_repetition - 0.4).abs() < 0.01);

        // Weighted dampening: (100*0.8 + 200*0.9) / 300 = 260/300 ≈ 0.867
        assert!((result.dampening_factor - 0.867).abs() < 0.01);

        // Sums: 20 + 30 = 50, 16 + 27 = 43
        assert_eq!(result.original_complexity, 50);
        assert_eq!(result.adjusted_complexity, 43);
    }

    #[test]
    fn test_aggregate_entropy_metrics_empty() {
        let item1 = create_test_item("file.rs", 10, 20, 2, 100);
        let item2 = create_test_item("file.rs", 15, 30, 3, 200);
        // Neither has entropy_details

        let members = vec![&item1, &item2];
        let result = aggregate_entropy_metrics(&members);

        assert!(result.is_none());
    }

    #[test]
    fn test_aggregate_entropy_metrics_partial() {
        // Only one item has entropy
        let mut item1 = create_test_item("file.rs", 10, 20, 2, 100);
        item1.entropy_analysis = Some(EntropyAnalysis {
            entropy_score: 0.4,
            pattern_repetition: 0.6,
            branch_similarity: 0.3,
            original_complexity: 20,
            adjusted_complexity: 16,
            dampening_factor: 0.8,
            dampening_was_applied: true,
            reasoning: vec![],
        });

        let item2 = create_test_item("file.rs", 15, 30, 3, 200); // No entropy

        let members = vec![&item1, &item2];
        let result = aggregate_entropy_metrics(&members).expect("should have entropy from item1");

        // Only item1 contributes, so values are from item1 only
        assert!((result.entropy_score - 0.4).abs() < 0.001);
        assert_eq!(result.original_complexity, 20);
    }

    #[test]
    fn test_aggregate_god_object_metrics_includes_entropy() {
        let mut item1 = create_test_item("file.rs", 10, 20, 2, 100);
        item1.entropy_analysis = Some(EntropyAnalysis {
            entropy_score: 0.4,
            pattern_repetition: 0.6,
            branch_similarity: 0.3,
            original_complexity: 20,
            adjusted_complexity: 16,
            dampening_factor: 0.8,
            dampening_was_applied: true,
            reasoning: vec![],
        });

        let members = vec![&item1];
        let metrics = aggregate_god_object_metrics(&members);

        assert!(metrics.aggregated_entropy.is_some());
        let entropy = metrics.aggregated_entropy.unwrap();
        assert!((entropy.entropy_score - 0.4).abs() < 0.001);
    }

    #[test]
    fn test_aggregate_from_raw_metrics_includes_error_swallowing() {
        let functions = vec![FunctionMetrics {
            name: "func1".to_string(),
            file: PathBuf::from("test.rs"),
            line: 1,
            cyclomatic: 10,
            cognitive: 15,
            nesting: 3,
            length: 50,
            is_test: false,
            visibility: None,
            is_trait_method: false,
            in_test_module: false,
            entropy_score: None,
            is_pure: None,
            purity_confidence: None,
            purity_reason: None,
            call_dependencies: None,
            detected_patterns: None,
            upstream_callers: None,
            downstream_callees: None,
            mapping_pattern_result: None,
            adjusted_complexity: None,
            composition_metrics: None,
            language_specific: None,
            purity_level: None,
            error_swallowing_count: Some(4),
            error_swallowing_patterns: Some(vec!["match with ignored Err variant".to_string()]),
            entropy_analysis: None,
        }];

        let metrics = aggregate_from_raw_metrics(&functions);

        assert_eq!(metrics.total_cyclomatic, 10);
        assert_eq!(metrics.total_cognitive, 15);
        assert_eq!(metrics.total_error_swallowing_count, 4);
        assert_eq!(metrics.error_swallowing_patterns.len(), 1);
        assert!(metrics
            .error_swallowing_patterns
            .contains(&"match with ignored Err variant".to_string()));
    }

    #[test]
    fn test_aggregate_entropy_from_raw() {
        use crate::complexity::entropy_core::EntropyScore as RawEntropyScore;

        let functions = vec![
            FunctionMetrics {
                name: "func1".to_string(),
                file: PathBuf::from("test.rs"),
                line: 1,
                cyclomatic: 10,
                cognitive: 20,
                nesting: 2,
                length: 100,
                is_test: false,
                visibility: None,
                is_trait_method: false,
                in_test_module: false,
                entropy_score: Some(RawEntropyScore {
                    token_entropy: 0.4,
                    pattern_repetition: 0.6,
                    branch_similarity: 0.0,
                    effective_complexity: 5.0,
                    unique_variables: 0,
                    max_nesting: 0,
                    dampening_applied: 0.0,
                }),
                is_pure: None,
                purity_confidence: None,
                purity_reason: None,
                call_dependencies: None,
                detected_patterns: None,
                upstream_callers: None,
                downstream_callees: None,
                mapping_pattern_result: None,
                adjusted_complexity: None,
                composition_metrics: None,
                language_specific: None,
                purity_level: None,
                error_swallowing_count: None,
                error_swallowing_patterns: None,
                entropy_analysis: None,
            },
            FunctionMetrics {
                name: "func2".to_string(),
                file: PathBuf::from("test.rs"),
                line: 50,
                cyclomatic: 5,
                cognitive: 10,
                nesting: 1,
                length: 50,
                is_test: false,
                visibility: None,
                is_trait_method: false,
                in_test_module: false,
                entropy_score: Some(RawEntropyScore {
                    token_entropy: 0.5,
                    pattern_repetition: 0.3,
                    branch_similarity: 0.0,
                    effective_complexity: 3.0,
                    unique_variables: 0,
                    max_nesting: 0,
                    dampening_applied: 0.0,
                }),
                is_pure: None,
                purity_confidence: None,
                purity_reason: None,
                call_dependencies: None,
                detected_patterns: None,
                upstream_callers: None,
                downstream_callees: None,
                mapping_pattern_result: None,
                adjusted_complexity: None,
                composition_metrics: None,
                language_specific: None,
                purity_level: None,
                error_swallowing_count: None,
                error_swallowing_patterns: None,
                entropy_analysis: None,
            },
        ];

        let result = aggregate_entropy_from_raw(&functions).expect("should have entropy");

        // Weighted average: (100*0.4 + 50*0.5) / 150 = 65/150 ≈ 0.433
        assert!((result.entropy_score - 0.433).abs() < 0.01);

        // Weighted repetition: (100*0.6 + 50*0.3) / 150 = 75/150 = 0.5
        assert!((result.pattern_repetition - 0.5).abs() < 0.01);

        // Original complexity: 20 + 10 = 30
        assert_eq!(result.original_complexity, 30);
    }

    #[test]
    fn test_aggregate_from_raw_metrics_includes_entropy() {
        use crate::complexity::entropy_core::EntropyScore as RawEntropyScore;

        let functions = vec![FunctionMetrics {
            name: "func1".to_string(),
            file: PathBuf::from("test.rs"),
            line: 1,
            cyclomatic: 10,
            cognitive: 20,
            nesting: 2,
            length: 100,
            is_test: false,
            visibility: None,
            is_trait_method: false,
            in_test_module: false,
            entropy_score: Some(RawEntropyScore {
                token_entropy: 0.4,
                pattern_repetition: 0.6,
                branch_similarity: 0.0,
                effective_complexity: 5.0,
                unique_variables: 0,
                max_nesting: 0,
                dampening_applied: 0.0,
            }),
            is_pure: None,
            purity_confidence: None,
            purity_reason: None,
            call_dependencies: None,
            detected_patterns: None,
            upstream_callers: None,
            downstream_callees: None,
            mapping_pattern_result: None,
            adjusted_complexity: None,
            composition_metrics: None,
            language_specific: None,
            purity_level: None,
            error_swallowing_count: None,
            error_swallowing_patterns: None,
            entropy_analysis: None,
        }];

        let metrics = aggregate_from_raw_metrics(&functions);

        assert!(metrics.aggregated_entropy.is_some());
        let entropy = metrics.aggregated_entropy.unwrap();
        assert!((entropy.entropy_score - 0.4).abs() < 0.001);
        assert_eq!(entropy.original_complexity, 20);
    }

    // =========================================================================
    // Tests for pure helper functions (Stillwater refactoring)
    // =========================================================================

    #[test]
    fn test_extract_entropy_data_filters_correctly() {
        use crate::complexity::entropy_core::EntropyScore as RawEntropyScore;

        let functions = vec![
            FunctionMetrics {
                name: "with_entropy".to_string(),
                file: PathBuf::from("test.rs"),
                line: 1,
                cyclomatic: 5,
                cognitive: 10,
                nesting: 1,
                length: 50,
                is_test: false,
                visibility: None,
                is_trait_method: false,
                in_test_module: false,
                entropy_score: Some(RawEntropyScore {
                    token_entropy: 0.4,
                    pattern_repetition: 0.6,
                    branch_similarity: 0.0,
                    effective_complexity: 5.0,
                    unique_variables: 0,
                    max_nesting: 0,
                    dampening_applied: 0.0,
                }),
                is_pure: None,
                purity_confidence: None,
                purity_reason: None,
                call_dependencies: None,
                detected_patterns: None,
                upstream_callers: None,
                downstream_callees: None,
                mapping_pattern_result: None,
                adjusted_complexity: None,
                composition_metrics: None,
                language_specific: None,
                purity_level: None,
                error_swallowing_count: None,
                error_swallowing_patterns: None,
                entropy_analysis: None,
            },
            FunctionMetrics {
                name: "without_entropy".to_string(),
                file: PathBuf::from("test.rs"),
                line: 50,
                cyclomatic: 3,
                cognitive: 5,
                nesting: 1,
                length: 25,
                is_test: false,
                visibility: None,
                is_trait_method: false,
                in_test_module: false,
                entropy_score: None, // No entropy
                is_pure: None,
                purity_confidence: None,
                purity_reason: None,
                call_dependencies: None,
                detected_patterns: None,
                upstream_callers: None,
                downstream_callees: None,
                mapping_pattern_result: None,
                adjusted_complexity: None,
                composition_metrics: None,
                language_specific: None,
                purity_level: None,
                error_swallowing_count: None,
                error_swallowing_patterns: None,
                entropy_analysis: None,
            },
        ];

        let data = extract_entropy_data(&functions);
        assert_eq!(data.len(), 1); // Only one function has entropy
        assert_eq!(data[0].1, 50); // Length of function with entropy
        assert_eq!(data[0].2, 10); // Cognitive of function with entropy
    }

    #[test]
    fn test_weighted_average_calculation() {
        use crate::complexity::entropy_core::EntropyScore as RawEntropyScore;

        let e1 = RawEntropyScore {
            token_entropy: 0.4,
            pattern_repetition: 0.6,
            branch_similarity: 0.0,
            effective_complexity: 5.0,
            unique_variables: 0,
            max_nesting: 0,
            dampening_applied: 0.0,
        };
        let e2 = RawEntropyScore {
            token_entropy: 0.6,
            pattern_repetition: 0.2,
            branch_similarity: 0.0,
            effective_complexity: 3.0,
            unique_variables: 0,
            max_nesting: 0,
            dampening_applied: 0.0,
        };

        // length 100, cognitive 20 and length 50, cognitive 10
        let data: Vec<(&RawEntropyScore, usize, u32)> = vec![(&e1, 100, 20), (&e2, 50, 10)];

        // (100*0.4 + 50*0.6) / 150 = 70/150 ≈ 0.467
        let avg = weighted_average(&data, 150, |e| e.token_entropy);
        assert!((avg - 0.467).abs() < 0.01);

        // (100*0.6 + 50*0.2) / 150 = 70/150 ≈ 0.467
        let rep = weighted_average(&data, 150, |e| e.pattern_repetition);
        assert!((rep - 0.467).abs() < 0.01);
    }

    #[test]
    fn test_sum_cognitive() {
        use crate::complexity::entropy_core::EntropyScore as RawEntropyScore;

        let e = RawEntropyScore {
            token_entropy: 0.4,
            pattern_repetition: 0.6,
            branch_similarity: 0.0,
            effective_complexity: 5.0,
            unique_variables: 0,
            max_nesting: 0,
            dampening_applied: 0.0,
        };

        let data: Vec<(&RawEntropyScore, usize, u32)> =
            vec![(&e, 100, 20), (&e, 50, 15), (&e, 25, 5)];

        let total = sum_cognitive(&data);
        assert_eq!(total, 40); // 20 + 15 + 5
    }

    #[test]
    fn test_total_length() {
        use crate::complexity::entropy_core::EntropyScore as RawEntropyScore;

        let e = RawEntropyScore {
            token_entropy: 0.4,
            pattern_repetition: 0.6,
            branch_similarity: 0.0,
            effective_complexity: 5.0,
            unique_variables: 0,
            max_nesting: 0,
            dampening_applied: 0.0,
        };

        let data: Vec<(&RawEntropyScore, usize, u32)> = vec![(&e, 100, 20), (&e, 50, 15)];

        let total = total_length(&data);
        assert_eq!(total, 150); // 100 + 50
    }

    #[test]
    fn test_calculate_dampening_factor_direct() {
        use crate::complexity::entropy_core::{EntropyConfig, UniversalEntropyCalculator};

        let calculator = UniversalEntropyCalculator::new(EntropyConfig::default());

        // Test with various entropy/repetition combinations
        let dampening = calculator.calculate_dampening_factor(0.4, 0.6);
        assert!((0.5..=1.0).contains(&dampening));

        // Low entropy, high repetition should result in lower effective complexity
        let low_dampening = calculator.calculate_dampening_factor(0.2, 0.8);
        assert!(low_dampening >= 0.5);

        // High entropy, low repetition should result in higher effective complexity
        let high_dampening = calculator.calculate_dampening_factor(0.8, 0.2);
        assert!(high_dampening <= 1.0);
    }

    #[test]
    fn test_aggregate_dependency_metrics_from_raw() {
        let functions = vec![
            FunctionMetrics {
                name: "func1".to_string(),
                file: PathBuf::from("test.rs"),
                line: 1,
                cyclomatic: 5,
                cognitive: 10,
                nesting: 1,
                length: 50,
                is_test: false,
                visibility: None,
                is_trait_method: false,
                in_test_module: false,
                entropy_score: None,
                is_pure: None,
                purity_confidence: None,
                purity_reason: None,
                call_dependencies: None,
                detected_patterns: None,
                upstream_callers: Some(vec!["caller1".to_string(), "caller2".to_string()]),
                downstream_callees: Some(vec!["callee1".to_string()]),
                mapping_pattern_result: None,
                adjusted_complexity: None,
                composition_metrics: None,
                language_specific: None,
                purity_level: None,
                error_swallowing_count: None,
                error_swallowing_patterns: None,
                entropy_analysis: None,
            },
            FunctionMetrics {
                name: "func2".to_string(),
                file: PathBuf::from("test.rs"),
                line: 10,
                cyclomatic: 3,
                cognitive: 5,
                nesting: 1,
                length: 30,
                is_test: false,
                visibility: None,
                is_trait_method: false,
                in_test_module: false,
                entropy_score: None,
                is_pure: None,
                purity_confidence: None,
                purity_reason: None,
                call_dependencies: None,
                detected_patterns: None,
                upstream_callers: Some(vec!["caller2".to_string(), "caller3".to_string()]), // caller2 is duplicate
                downstream_callees: Some(vec!["callee2".to_string(), "callee3".to_string()]),
                mapping_pattern_result: None,
                adjusted_complexity: None,
                composition_metrics: None,
                language_specific: None,
                purity_level: None,
                error_swallowing_count: None,
                error_swallowing_patterns: None,
                entropy_analysis: None,
            },
        ];

        let (callers, callees, upstream_count, downstream_count) =
            aggregate_dependency_metrics_from_raw(&functions);

        // Should deduplicate: caller1, caller2, caller3 = 3 unique
        assert_eq!(upstream_count, 3);
        // Should deduplicate: callee1, callee2, callee3 = 3 unique
        assert_eq!(downstream_count, 3);

        assert!(callers.contains(&"caller1".to_string()));
        assert!(callers.contains(&"caller2".to_string()));
        assert!(callers.contains(&"caller3".to_string()));

        assert!(callees.contains(&"callee1".to_string()));
        assert!(callees.contains(&"callee2".to_string()));
        assert!(callees.contains(&"callee3".to_string()));
    }

    #[test]
    fn test_aggregate_from_raw_metrics_includes_dependencies() {
        let functions = vec![FunctionMetrics {
            name: "func1".to_string(),
            file: PathBuf::from("test.rs"),
            line: 1,
            cyclomatic: 5,
            cognitive: 10,
            nesting: 1,
            length: 50,
            is_test: false,
            visibility: None,
            is_trait_method: false,
            in_test_module: false,
            entropy_score: None,
            is_pure: None,
            purity_confidence: None,
            purity_reason: None,
            call_dependencies: None,
            detected_patterns: None,
            upstream_callers: Some(vec!["caller1".to_string(), "caller2".to_string()]),
            downstream_callees: Some(vec!["callee1".to_string()]),
            mapping_pattern_result: None,
            adjusted_complexity: None,
            composition_metrics: None,
            language_specific: None,
            purity_level: None,
            error_swallowing_count: None,
            error_swallowing_patterns: None,
            entropy_analysis: None,
        }];

        let metrics = aggregate_from_raw_metrics(&functions);

        // Dependencies should be populated from raw metrics
        assert_eq!(metrics.upstream_dependencies, 2);
        assert_eq!(metrics.downstream_dependencies, 1);
        assert_eq!(metrics.unique_upstream_callers.len(), 2);
        assert_eq!(metrics.unique_downstream_callees.len(), 1);
    }

    // =========================================================================
    // Tests for Distribution Metrics (Spec 268)
    // =========================================================================

    #[test]
    fn test_calculate_median_odd_count() {
        assert_eq!(calculate_median(&[1, 2, 3, 4, 5]), 3);
        assert_eq!(calculate_median(&[5, 1, 3]), 3); // Tests sorting
        assert_eq!(calculate_median(&[100]), 100);
    }

    #[test]
    fn test_calculate_median_even_count() {
        // For even count, returns average of two middle values
        assert_eq!(calculate_median(&[1, 2, 3, 4]), 2); // (2+3)/2 = 2 (integer division)
        assert_eq!(calculate_median(&[1, 3, 5, 7]), 4); // (3+5)/2 = 4
    }

    #[test]
    fn test_calculate_median_empty() {
        assert_eq!(calculate_median(&[]), 0);
    }

    #[test]
    fn test_classify_distribution_concentrated() {
        // Single function has 60% of complexity
        assert_eq!(
            classify_distribution(60, 100),
            ComplexityDistribution::Concentrated
        );
        // Edge case: exactly 51%
        assert_eq!(
            classify_distribution(51, 100),
            ComplexityDistribution::Concentrated
        );
    }

    #[test]
    fn test_classify_distribution_mixed() {
        // Max function has 30% of complexity
        assert_eq!(
            classify_distribution(30, 100),
            ComplexityDistribution::Mixed
        );
        // Edge case: exactly 50%
        assert_eq!(
            classify_distribution(50, 100),
            ComplexityDistribution::Mixed
        );
        // Edge case: just above 20%
        assert_eq!(
            classify_distribution(21, 100),
            ComplexityDistribution::Mixed
        );
    }

    #[test]
    fn test_classify_distribution_distributed() {
        // Max function has only 10% of complexity
        assert_eq!(
            classify_distribution(10, 100),
            ComplexityDistribution::Distributed
        );
        // Edge case: exactly 20%
        assert_eq!(
            classify_distribution(20, 100),
            ComplexityDistribution::Distributed
        );
        // Zero total should be Distributed
        assert_eq!(
            classify_distribution(0, 0),
            ComplexityDistribution::Distributed
        );
    }

    #[test]
    fn test_aggregate_distribution_metrics() {
        // Create items with varied complexity to test distribution calculation
        let members = vec![
            create_test_item("file.rs", 5, 10, 2, 50), // Low complexity
            create_test_item("file.rs", 8, 15, 3, 100), // Medium complexity
            create_test_item("file.rs", 12, 20, 4, 75), // Medium complexity
            create_test_item("file.rs", 6, 12, 2, 60), // Low complexity
            create_test_item("file.rs", 7, 14, 3, 80), // Low complexity
        ];
        let member_refs: Vec<_> = members.iter().collect();

        let dist = aggregate_distribution_metrics(&member_refs);

        // Total: 5+8+12+6+7 = 38, max = 12
        // Ratio: 12/38 = 0.316 -> Mixed
        assert_eq!(dist.function_count, 5);
        assert_eq!(dist.max_complexity, 12);
        assert!((dist.avg_complexity - 7.6).abs() < 0.01); // 38/5 = 7.6
        assert_eq!(dist.median_complexity, 7); // sorted: 5,6,7,8,12 -> median = 7
        assert_eq!(dist.exceeding_threshold, 0); // none exceed 15
        assert_eq!(dist.distribution, ComplexityDistribution::Mixed);
        assert_eq!(dist.production_loc, 365); // 50+100+75+60+80
    }

    #[test]
    fn test_aggregate_distribution_metrics_distributed_file() {
        // Create items simulating a well-structured file with many small functions
        let mut members = Vec::new();
        for i in 0..30 {
            // 30 functions with complexity 3-7 (average 5)
            members.push(create_test_item("file.rs", 3 + (i % 5), 10, 2, 20));
        }
        let member_refs: Vec<_> = members.iter().collect();

        let dist = aggregate_distribution_metrics(&member_refs);

        // Total: 30 functions with avg complexity 5 = total ~150
        // Max complexity = 7 (3 + 4)
        // Ratio: 7/~150 = ~0.047 -> Distributed
        assert_eq!(dist.function_count, 30);
        assert_eq!(dist.max_complexity, 7); // max of 3,4,5,6,7
        assert_eq!(dist.exceeding_threshold, 0);
        assert_eq!(dist.distribution, ComplexityDistribution::Distributed);
    }

    #[test]
    fn test_aggregate_distribution_metrics_concentrated_file() {
        // Create items simulating a god function dominating the file
        let members = vec![
            create_test_item("file.rs", 60, 100, 5, 500), // God function
            create_test_item("file.rs", 5, 10, 2, 30),    // Small helper
            create_test_item("file.rs", 5, 10, 2, 30),    // Small helper
        ];
        let member_refs: Vec<_> = members.iter().collect();

        let dist = aggregate_distribution_metrics(&member_refs);

        // Total: 60+5+5 = 70, max = 60
        // Ratio: 60/70 = 0.857 -> Concentrated
        assert_eq!(dist.function_count, 3);
        assert_eq!(dist.max_complexity, 60);
        assert_eq!(dist.exceeding_threshold, 1); // 60 exceeds 15
        assert_eq!(dist.distribution, ComplexityDistribution::Concentrated);
    }

    #[test]
    fn test_aggregate_distribution_metrics_from_raw() {
        let functions = vec![
            FunctionMetrics {
                name: "prod_func1".to_string(),
                file: PathBuf::from("test.rs"),
                line: 1,
                cyclomatic: 10,
                cognitive: 15,
                nesting: 2,
                length: 100,
                is_test: false,
                visibility: None,
                is_trait_method: false,
                in_test_module: false,
                entropy_score: None,
                is_pure: None,
                purity_confidence: None,
                purity_reason: None,
                call_dependencies: None,
                detected_patterns: None,
                upstream_callers: None,
                downstream_callees: None,
                mapping_pattern_result: None,
                adjusted_complexity: None,
                composition_metrics: None,
                language_specific: None,
                purity_level: None,
                error_swallowing_count: None,
                error_swallowing_patterns: None,
                entropy_analysis: None,
            },
            FunctionMetrics {
                name: "prod_func2".to_string(),
                file: PathBuf::from("test.rs"),
                line: 50,
                cyclomatic: 8,
                cognitive: 12,
                nesting: 1,
                length: 50,
                is_test: false,
                visibility: None,
                is_trait_method: false,
                in_test_module: false,
                entropy_score: None,
                is_pure: None,
                purity_confidence: None,
                purity_reason: None,
                call_dependencies: None,
                detected_patterns: None,
                upstream_callers: None,
                downstream_callees: None,
                mapping_pattern_result: None,
                adjusted_complexity: None,
                composition_metrics: None,
                language_specific: None,
                purity_level: None,
                error_swallowing_count: None,
                error_swallowing_patterns: None,
                entropy_analysis: None,
            },
            FunctionMetrics {
                name: "test_something".to_string(),
                file: PathBuf::from("test.rs"),
                line: 100,
                cyclomatic: 5,
                cognitive: 8,
                nesting: 1,
                length: 200, // Test function with more LOC
                is_test: true,
                visibility: None,
                is_trait_method: false,
                in_test_module: true,
                entropy_score: None,
                is_pure: None,
                purity_confidence: None,
                purity_reason: None,
                call_dependencies: None,
                detected_patterns: None,
                upstream_callers: None,
                downstream_callees: None,
                mapping_pattern_result: None,
                adjusted_complexity: None,
                composition_metrics: None,
                language_specific: None,
                purity_level: None,
                error_swallowing_count: None,
                error_swallowing_patterns: None,
                entropy_analysis: None,
            },
        ];

        let dist = aggregate_distribution_metrics_from_raw(&functions);

        // Should only count production functions (2 functions)
        assert_eq!(dist.function_count, 2);
        // Total complexity from production: 10+8 = 18, max = 10
        assert_eq!(dist.max_complexity, 10);
        assert!((dist.avg_complexity - 9.0).abs() < 0.01); // 18/2 = 9.0
                                                           // Production LOC: 100 + 50 = 150
        assert_eq!(dist.production_loc, 150);
        // Test LOC: 200
        assert_eq!(dist.test_loc, 200);
        // Ratio: 10/18 = 0.556 -> Concentrated
        assert_eq!(dist.distribution, ComplexityDistribution::Concentrated);
    }

    #[test]
    fn test_distributed_file_gets_correct_classification() {
        // Real-world scenario: 30 small functions (like overflow.rs example)
        let mut functions = Vec::new();
        for i in 0..30 {
            functions.push(FunctionMetrics {
                name: format!("func_{}", i),
                file: PathBuf::from("overflow.rs"),
                line: i * 20 + 1,
                cyclomatic: 5 + (i as u32 % 4), // 5, 6, 7, 8, 5, 6, ...
                cognitive: 4 + (i as u32 % 3),
                nesting: 2,
                length: 20, // ~20 lines each
                is_test: false,
                visibility: None,
                is_trait_method: false,
                in_test_module: false,
                entropy_score: None,
                is_pure: None,
                purity_confidence: None,
                purity_reason: None,
                call_dependencies: None,
                detected_patterns: None,
                upstream_callers: None,
                downstream_callees: None,
                mapping_pattern_result: None,
                adjusted_complexity: None,
                composition_metrics: None,
                language_specific: None,
                purity_level: None,
                error_swallowing_count: None,
                error_swallowing_patterns: None,
                entropy_analysis: None,
            });
        }

        let dist = aggregate_distribution_metrics_from_raw(&functions);

        // Should be classified as Distributed (well-structured file)
        assert_eq!(dist.function_count, 30);
        assert_eq!(dist.max_complexity, 8); // max of 5,6,7,8
        assert_eq!(dist.distribution, ComplexityDistribution::Distributed);
        assert_eq!(dist.production_loc, 600); // 30 * 20
    }

    #[test]
    fn test_complexity_distribution_display_names() {
        assert_eq!(
            ComplexityDistribution::Concentrated.display_name(),
            "Concentrated"
        );
        assert_eq!(ComplexityDistribution::Mixed.display_name(), "Mixed");
        assert_eq!(
            ComplexityDistribution::Distributed.display_name(),
            "Distributed"
        );
    }

    #[test]
    fn test_complexity_distribution_explanations() {
        assert!(ComplexityDistribution::Concentrated
            .classification_explanation()
            .contains("god function"));
        assert!(ComplexityDistribution::Mixed
            .classification_explanation()
            .contains("review"));
        assert!(ComplexityDistribution::Distributed
            .classification_explanation()
            .contains("Well-Structured"));
    }

    #[test]
    fn test_aggregate_god_object_metrics_includes_distribution() {
        let members = vec![
            create_test_item("file.rs", 10, 20, 2, 100),
            create_test_item("file.rs", 8, 15, 3, 80),
        ];
        let member_refs: Vec<_> = members.iter().collect();

        let metrics = aggregate_god_object_metrics(&member_refs);

        assert!(metrics.distribution_metrics.is_some());
        let dist = metrics.distribution_metrics.unwrap();
        assert_eq!(dist.function_count, 2);
        assert_eq!(dist.max_complexity, 10);
    }

    #[test]
    fn test_aggregate_from_raw_metrics_includes_distribution() {
        let functions = vec![FunctionMetrics {
            name: "func1".to_string(),
            file: PathBuf::from("test.rs"),
            line: 1,
            cyclomatic: 10,
            cognitive: 15,
            nesting: 2,
            length: 100,
            is_test: false,
            visibility: None,
            is_trait_method: false,
            in_test_module: false,
            entropy_score: None,
            is_pure: None,
            purity_confidence: None,
            purity_reason: None,
            call_dependencies: None,
            detected_patterns: None,
            upstream_callers: None,
            downstream_callees: None,
            mapping_pattern_result: None,
            adjusted_complexity: None,
            composition_metrics: None,
            language_specific: None,
            purity_level: None,
            error_swallowing_count: None,
            error_swallowing_patterns: None,
            entropy_analysis: None,
        }];

        let metrics = aggregate_from_raw_metrics(&functions);

        assert!(metrics.distribution_metrics.is_some());
        let dist = metrics.distribution_metrics.unwrap();
        assert_eq!(dist.function_count, 1);
        assert_eq!(dist.max_complexity, 10);
        assert_eq!(dist.production_loc, 100);
    }
}