go-brrr 0.1.0

Token-efficient code analysis for LLMs - Rust implementation
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
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
//! Cognitive complexity calculation using SonarSource methodology.
//!
//! Cognitive complexity measures how difficult code is to understand (not test).
//! Unlike cyclomatic complexity which counts paths, cognitive complexity
//! accounts for nesting depth and penalizes deeply nested structures.
//!
//! # SonarSource Rules
//!
//! ## Increments (add 1 to complexity):
//! - Control flow: if, else if, switch/match, for, while, do-while
//! - Exception handling: catch
//! - Jump statements: goto, break-to-label, continue-to-label
//! - Logical operators: sequences like `a && b && c` count as 1 (not 2)
//! - Recursion: direct recursive calls
//!
//! ## Nesting Increments (add current nesting level):
//! - Control structures nested inside other control structures
//! - Lambda/closure increases nesting level
//!
//! ## No Increment:
//! - `else` clause (already counted with `if`)
//! - Simple ternary `?:` (exception: nested ternaries DO increment)
//!
//! # Risk Levels
//!
//! Cognitive complexity thresholds are typically more strict:
//! - Low (0-5): Simple, easy to understand
//! - Medium (6-10): Moderate complexity, consider simplifying
//! - High (11-15): Complex, hard to understand
//! - Critical (15+): Refactor immediately

use std::collections::HashSet;
use std::path::{Path, PathBuf};

use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use tracing::debug;
use tree_sitter::{Node, Tree};

use crate::ast::AstExtractor;
use crate::callgraph::scanner::{ProjectScanner, ScanConfig};
use crate::error::{Result, BrrrError};
use crate::lang::LanguageRegistry;

// =============================================================================
// TYPES
// =============================================================================

/// Risk level classification based on cognitive complexity.
///
/// Cognitive complexity uses stricter thresholds than cyclomatic because
/// it measures understandability, not testability.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CognitiveRiskLevel {
    /// Complexity 0-5: Simple, easy to understand
    Low,
    /// Complexity 6-10: Moderate complexity, consider simplifying
    Medium,
    /// Complexity 11-15: Complex, hard to understand
    High,
    /// Complexity 15+: Critical, refactor immediately
    Critical,
}

impl CognitiveRiskLevel {
    /// Classify cognitive complexity value into risk level.
    #[must_use]
    pub fn from_complexity(complexity: u32) -> Self {
        match complexity {
            0..=5 => Self::Low,
            6..=10 => Self::Medium,
            11..=15 => Self::High,
            _ => Self::Critical,
        }
    }

    /// Get human-readable description of the risk level.
    #[must_use]
    pub const fn description(&self) -> &'static str {
        match self {
            Self::Low => "Simple, easy to understand",
            Self::Medium => "Moderate complexity, consider simplifying",
            Self::High => "Complex, hard to understand",
            Self::Critical => "Critical complexity, refactor immediately",
        }
    }

    /// Get the color code for CLI output (ANSI).
    #[must_use]
    pub const fn color_code(&self) -> &'static str {
        match self {
            Self::Low => "\x1b[32m",       // Green
            Self::Medium => "\x1b[33m",    // Yellow
            Self::High => "\x1b[31m",      // Red
            Self::Critical => "\x1b[35m",  // Magenta
        }
    }
}

impl std::fmt::Display for CognitiveRiskLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Low => write!(f, "low"),
            Self::Medium => write!(f, "medium"),
            Self::High => write!(f, "high"),
            Self::Critical => write!(f, "critical"),
        }
    }
}

/// Type of construct contributing to cognitive complexity.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConstructType {
    /// if statement
    If,
    /// else if / elif clause
    ElseIf,
    /// else clause (no increment, just for breakdown visibility)
    Else,
    /// switch / match statement
    Switch,
    /// for loop
    For,
    /// while loop
    While,
    /// do-while loop
    DoWhile,
    /// catch / except clause
    Catch,
    /// goto statement
    Goto,
    /// break with label
    BreakToLabel,
    /// continue with label
    ContinueToLabel,
    /// Sequence of logical AND operators
    LogicalAndSequence,
    /// Sequence of logical OR operators
    LogicalOrSequence,
    /// Direct recursive call
    Recursion,
    /// Nested ternary operator
    NestedTernary,
    /// Lambda/closure (adds nesting, no base increment)
    Lambda,
    /// Guard clause (early return reduces nesting)
    GuardClause,
}

impl std::fmt::Display for ConstructType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::If => write!(f, "if"),
            Self::ElseIf => write!(f, "else if"),
            Self::Else => write!(f, "else"),
            Self::Switch => write!(f, "switch/match"),
            Self::For => write!(f, "for"),
            Self::While => write!(f, "while"),
            Self::DoWhile => write!(f, "do-while"),
            Self::Catch => write!(f, "catch"),
            Self::Goto => write!(f, "goto"),
            Self::BreakToLabel => write!(f, "break to label"),
            Self::ContinueToLabel => write!(f, "continue to label"),
            Self::LogicalAndSequence => write!(f, "&& sequence"),
            Self::LogicalOrSequence => write!(f, "|| sequence"),
            Self::Recursion => write!(f, "recursion"),
            Self::NestedTernary => write!(f, "nested ternary"),
            Self::Lambda => write!(f, "lambda/closure"),
            Self::GuardClause => write!(f, "guard clause"),
        }
    }
}

/// Individual contribution to cognitive complexity.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplexityContribution {
    /// Line number where construct appears
    pub line: usize,
    /// Type of construct
    pub construct: ConstructType,
    /// Base increment (1 for most constructs, 0 for else/lambda)
    pub base_increment: u32,
    /// Nesting increment (current nesting level)
    pub nesting_increment: u32,
    /// Total contribution (base + nesting)
    pub total: u32,
    /// Current nesting depth when this construct was encountered
    pub nesting_depth: u32,
}

/// Cognitive complexity result for a single function.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CognitiveComplexity {
    /// Function name (may include class prefix for methods)
    pub function_name: String,
    /// File path containing the function
    pub file: PathBuf,
    /// Starting line number (1-indexed)
    pub line: usize,
    /// Ending line number (1-indexed)
    pub end_line: usize,
    /// Total cognitive complexity score
    pub complexity: u32,
    /// Risk level classification
    pub risk_level: CognitiveRiskLevel,
    /// Breakdown of contributions to complexity
    pub breakdown: Vec<ComplexityContribution>,
    /// Maximum nesting depth reached
    pub max_nesting: u32,
    /// Number of recursive calls detected
    pub recursion_count: u32,
}

/// Simplified function complexity for summary output.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionCognitiveComplexity {
    /// Function name
    pub name: String,
    /// Starting line number
    pub line: usize,
    /// Cognitive complexity value
    pub complexity: u32,
    /// Risk level
    pub risk_level: CognitiveRiskLevel,
}

impl From<&CognitiveComplexity> for FunctionCognitiveComplexity {
    fn from(cc: &CognitiveComplexity) -> Self {
        Self {
            name: cc.function_name.clone(),
            line: cc.line,
            complexity: cc.complexity,
            risk_level: cc.risk_level,
        }
    }
}

/// Statistics for cognitive complexity analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CognitiveStats {
    /// Total functions analyzed
    pub total_functions: usize,
    /// Average complexity
    pub average_complexity: f64,
    /// Maximum complexity found
    pub max_complexity: u32,
    /// Minimum complexity found
    pub min_complexity: u32,
    /// Median complexity
    pub median_complexity: u32,
    /// Risk level distribution
    pub risk_distribution: std::collections::HashMap<String, usize>,
    /// Functions with recursion
    pub functions_with_recursion: usize,
    /// Average max nesting depth
    pub average_max_nesting: f64,
}

impl CognitiveStats {
    /// Calculate statistics from complexity values.
    fn from_complexities(results: &[CognitiveComplexity]) -> Self {
        if results.is_empty() {
            return Self {
                total_functions: 0,
                average_complexity: 0.0,
                max_complexity: 0,
                min_complexity: 0,
                median_complexity: 0,
                risk_distribution: std::collections::HashMap::new(),
                functions_with_recursion: 0,
                average_max_nesting: 0.0,
            };
        }

        let complexities: Vec<u32> = results.iter().map(|r| r.complexity).collect();
        let total = complexities.len();
        let sum: u64 = complexities.iter().map(|&c| u64::from(c)).sum();
        let average = sum as f64 / total as f64;

        let max = complexities.iter().copied().max().unwrap_or(0);
        let min = complexities.iter().copied().min().unwrap_or(0);

        let mut sorted = complexities.clone();
        sorted.sort_unstable();
        let median = if total % 2 == 0 {
            (sorted[total / 2 - 1] + sorted[total / 2]) / 2
        } else {
            sorted[total / 2]
        };

        let mut risk_distribution = std::collections::HashMap::new();
        for r in results {
            *risk_distribution
                .entry(r.risk_level.to_string())
                .or_insert(0) += 1;
        }

        let functions_with_recursion = results.iter().filter(|r| r.recursion_count > 0).count();

        let total_nesting: u32 = results.iter().map(|r| r.max_nesting).sum();
        let average_max_nesting = f64::from(total_nesting) / total as f64;

        Self {
            total_functions: total,
            average_complexity: average,
            max_complexity: max,
            min_complexity: min,
            median_complexity: median,
            risk_distribution,
            functions_with_recursion,
            average_max_nesting,
        }
    }
}

/// Complete cognitive complexity analysis result.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CognitiveAnalysis {
    /// Path that was analyzed
    pub path: PathBuf,
    /// Language filter applied
    pub language: Option<String>,
    /// Individual function complexities
    pub functions: Vec<CognitiveComplexity>,
    /// Functions exceeding threshold
    #[serde(skip_serializing_if = "Option::is_none")]
    pub violations: Option<Vec<CognitiveComplexity>>,
    /// Aggregate statistics
    pub stats: CognitiveStats,
    /// Threshold used for filtering
    #[serde(skip_serializing_if = "Option::is_none")]
    pub threshold: Option<u32>,
    /// Analysis errors
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub errors: Vec<CognitiveAnalysisError>,
}

/// Error during cognitive complexity analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CognitiveAnalysisError {
    /// File path
    pub file: PathBuf,
    /// Error message
    pub message: String,
}

// =============================================================================
// COGNITIVE COMPLEXITY CALCULATOR
// =============================================================================

/// Calculator for cognitive complexity with language-specific handling.
struct CognitiveCalculator<'a> {
    source: &'a [u8],
    function_name: String,
    nesting_level: u32,
    complexity: u32,
    breakdown: Vec<ComplexityContribution>,
    max_nesting: u32,
    recursion_count: u32,
    language: &'a str,
    /// Track positions of logical operators already counted
    counted_logical_sequences: HashSet<usize>,
}

impl<'a> CognitiveCalculator<'a> {
    fn new(source: &'a [u8], function_name: String, language: &'a str) -> Self {
        Self {
            source,
            function_name,
            nesting_level: 0,
            complexity: 0,
            breakdown: Vec::new(),
            max_nesting: 0,
            recursion_count: 0,
            language,
            counted_logical_sequences: HashSet::new(),
        }
    }

    /// Get text from a node.
    fn node_text(&self, node: Node) -> &str {
        std::str::from_utf8(&self.source[node.start_byte()..node.end_byte()]).unwrap_or("")
    }

    /// Add a complexity contribution.
    fn add_contribution(&mut self, line: usize, construct: ConstructType, with_nesting: bool) {
        let base_increment = match construct {
            // No base increment for else and lambda (lambda only adds nesting)
            // Guard clauses DO add +1 (they're still control flow), just no nesting penalty
            ConstructType::Else | ConstructType::Lambda => 0,
            _ => 1,
        };

        let nesting_increment = if with_nesting { self.nesting_level } else { 0 };
        let total = base_increment + nesting_increment;

        self.complexity += total;
        self.breakdown.push(ComplexityContribution {
            line,
            construct,
            base_increment,
            nesting_increment,
            total,
            nesting_depth: self.nesting_level,
        });
    }

    /// Enter a nesting context.
    fn enter_nesting(&mut self) {
        self.nesting_level += 1;
        self.max_nesting = self.max_nesting.max(self.nesting_level);
    }

    /// Exit a nesting context.
    fn exit_nesting(&mut self) {
        self.nesting_level = self.nesting_level.saturating_sub(1);
    }

    /// Check if a node represents a recursive call.
    fn is_recursive_call(&self, node: Node) -> bool {
        // Get the callee name
        let callee = match self.language {
            "python" => {
                if node.kind() == "call" {
                    node.child_by_field_name("function")
                        .map(|n| self.node_text(n).to_string())
                } else {
                    None
                }
            }
            "typescript" | "javascript" | "tsx" | "jsx" => {
                if node.kind() == "call_expression" {
                    node.child_by_field_name("function")
                        .map(|n| self.node_text(n).to_string())
                } else {
                    None
                }
            }
            "rust" => {
                if node.kind() == "call_expression" {
                    node.child_by_field_name("function")
                        .map(|n| self.node_text(n).to_string())
                } else {
                    None
                }
            }
            "go" => {
                if node.kind() == "call_expression" {
                    node.child_by_field_name("function")
                        .map(|n| self.node_text(n).to_string())
                } else {
                    None
                }
            }
            "java" | "c" | "cpp" => {
                if node.kind() == "call_expression" || node.kind() == "method_invocation" {
                    node.child_by_field_name("name")
                        .or_else(|| node.child_by_field_name("function"))
                        .map(|n| self.node_text(n).to_string())
                } else {
                    None
                }
            }
            _ => None,
        };

        // Check if callee matches function name (simple recursion detection)
        if let Some(callee_name) = callee {
            // Handle method names like "ClassName.method" -> compare "method" part
            let func_simple = self
                .function_name
                .rsplit('.')
                .next()
                .unwrap_or(&self.function_name);
            let callee_simple = callee_name.rsplit('.').next().unwrap_or(&callee_name);
            return func_simple == callee_simple;
        }
        false
    }

    /// Count logical operator sequence (a && b && c counts as 1).
    fn count_logical_sequence(&mut self, node: Node) {
        // Only count the sequence once at its root
        let start_byte = node.start_byte();
        if self.counted_logical_sequences.contains(&start_byte) {
            return;
        }

        // Check if this is a logical operator node
        let is_logical = match self.language {
            "python" => node.kind() == "boolean_operator",
            "typescript" | "javascript" | "tsx" | "jsx" => node.kind() == "binary_expression",
            "rust" => node.kind() == "binary_expression",
            "go" => node.kind() == "binary_expression",
            "java" | "c" | "cpp" => node.kind() == "binary_expression",
            _ => false,
        };

        if !is_logical {
            return;
        }

        // Get the operator
        let op = self.get_logical_operator(node);
        if op.is_none() {
            return;
        }
        let op = op.unwrap();

        // Check if parent is the same type of logical operator
        if let Some(parent) = node.parent() {
            let parent_op = self.get_logical_operator(parent);
            if parent_op == Some(op.clone()) {
                // This is part of a larger sequence, skip
                return;
            }
        }

        // Mark this position as counted
        self.counted_logical_sequences.insert(start_byte);

        // Add contribution
        let line = node.start_position().row + 1;
        let construct = if op == "and" || op == "&&" {
            ConstructType::LogicalAndSequence
        } else {
            ConstructType::LogicalOrSequence
        };

        self.add_contribution(line, construct, true);
    }

    /// Get logical operator from a binary expression.
    fn get_logical_operator(&self, node: Node) -> Option<String> {
        match self.language {
            "python" => {
                // Python uses boolean_operator with "and" or "or" as child
                if node.kind() == "boolean_operator" {
                    let mut cursor = node.walk();
                    for child in node.children(&mut cursor) {
                        let text = self.node_text(child);
                        if text == "and" || text == "or" {
                            return Some(text.to_string());
                        }
                    }
                }
                None
            }
            _ => {
                // C-style languages use binary_expression with operator
                if node.kind() == "binary_expression" {
                    // Find the operator child
                    let mut cursor = node.walk();
                    for child in node.children(&mut cursor) {
                        let text = self.node_text(child);
                        if text == "&&" || text == "||" {
                            return Some(text.to_string());
                        }
                    }
                }
                None
            }
        }
    }

    /// Check if this is a guard clause (early return that reduces complexity).
    fn is_guard_clause(&self, node: Node) -> bool {
        // A guard clause is an if statement at function level that:
        // 1. Is not nested (nesting_level == 0)
        // 2. Contains only a return/raise/throw in its body
        if self.nesting_level > 0 {
            return false;
        }

        // Check if the if body is a simple return
        let body = match self.language {
            "python" => {
                // Python if_statement has "consequence" field
                node.child_by_field_name("consequence")
            }
            "typescript" | "javascript" | "tsx" | "jsx" | "go" | "rust" | "java" | "c" | "cpp" => {
                // C-style languages have "consequence" field
                node.child_by_field_name("consequence")
            }
            _ => None,
        };

        if let Some(body) = body {
            // Check if body contains only a return statement
            let body_text = self.node_text(body);
            let is_simple_return = body_text.trim().starts_with("return")
                || body_text.trim().starts_with("raise")
                || body_text.trim().starts_with("throw")
                || body_text.trim().starts_with("panic");
            return is_simple_return && !body_text.contains('\n');
        }

        false
    }

    /// Process a node and its children for cognitive complexity.
    ///
    /// Returns `true` if the node was recognized as a control structure and
    /// its children were processed by the handler.
    fn process_node(&mut self, node: Node) {
        let line = node.start_position().row + 1;
        let kind = node.kind();

        // Check for recursion in call nodes BEFORE language-specific handling
        if self.is_recursive_call(node) {
            self.recursion_count += 1;
            self.add_contribution(line, ConstructType::Recursion, true);
        }

        // Check for logical operator sequences
        self.count_logical_sequence(node);

        // Match language-specific control flow constructs
        // These handlers return true if they processed the node's children
        let handled = match self.language {
            "python" => self.process_python_node(node, line, kind),
            "typescript" | "javascript" | "tsx" | "jsx" => {
                self.process_javascript_node(node, line, kind)
            }
            "rust" => self.process_rust_node(node, line, kind),
            "go" => self.process_go_node(node, line, kind),
            "java" => self.process_java_node(node, line, kind),
            "c" | "cpp" => self.process_c_node(node, line, kind),
            _ => self.process_generic_node(node, line, kind),
        };

        // Only recursively process children if the node wasn't handled by
        // a language-specific handler that already processed children
        if !handled {
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                self.process_node(child);
            }
        }
    }

    /// Process Python-specific nodes.
    /// Returns true if children were processed by this handler.
    fn process_python_node(&mut self, node: Node, line: usize, kind: &str) -> bool {
        match kind {
            "if_statement" => {
                // Check for guard clause
                if self.is_guard_clause(node) {
                    // Guard clauses still increment but don't add nesting penalty
                    self.add_contribution(line, ConstructType::GuardClause, false);
                    // Process children without nesting
                    self.process_children_flat(node);
                } else {
                    self.add_contribution(line, ConstructType::If, true);
                    self.process_python_if_children(node);
                }
                true
            }
            "elif_clause" => {
                self.add_contribution(line, ConstructType::ElseIf, true);
                self.process_children_with_nesting(node);
                true
            }
            "else_clause" => {
                // No base increment for else
                // Process children without extra nesting
                self.process_children_flat(node);
                true
            }
            "for_statement" => {
                self.add_contribution(line, ConstructType::For, true);
                self.process_children_with_nesting(node);
                true
            }
            "while_statement" => {
                self.add_contribution(line, ConstructType::While, true);
                self.process_children_with_nesting(node);
                true
            }
            "try_statement" => {
                // try itself doesn't add complexity, but process children to find except handlers
                self.process_children_flat(node);
                true
            }
            "except_clause" | "except_group_clause" => {
                self.add_contribution(line, ConstructType::Catch, true);
                self.process_children_with_nesting(node);
                true
            }
            "match_statement" => {
                self.add_contribution(line, ConstructType::Switch, true);
                self.process_children_with_nesting(node);
                true
            }
            "lambda" => {
                // Lambda adds nesting level but no base increment
                self.enter_nesting();
                self.process_children_flat(node);
                self.exit_nesting();
                true
            }
            "conditional_expression" => {
                // Python ternary: x if cond else y
                // Check if it's nested inside another ternary
                if self.is_nested_ternary(node) {
                    self.add_contribution(line, ConstructType::NestedTernary, true);
                }
                // Process children to detect nested ternaries
                self.process_children_flat(node);
                true
            }
            _ => false, // Node not handled, let caller process children
        }
    }

    /// Process Python if statement children specially.
    fn process_python_if_children(&mut self, node: Node) {
        self.enter_nesting();

        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            let child_kind = child.kind();
            // elif and else are siblings, process them without extra nesting
            if child_kind == "elif_clause" || child_kind == "else_clause" {
                // Exit nesting before processing elif/else
                self.exit_nesting();
                self.process_node(child);
                self.enter_nesting();
            } else {
                self.process_node(child);
            }
        }

        self.exit_nesting();
    }

    /// Process JavaScript/TypeScript-specific nodes.
    /// Returns true if children were processed by this handler.
    fn process_javascript_node(&mut self, node: Node, line: usize, kind: &str) -> bool {
        match kind {
            "if_statement" => {
                if self.is_guard_clause(node) {
                    self.add_contribution(line, ConstructType::GuardClause, false);
                    self.process_children_flat(node);
                } else {
                    self.add_contribution(line, ConstructType::If, true);
                    self.process_js_if_children(node);
                }
                true
            }
            "for_statement" | "for_in_statement" | "for_of_statement" => {
                self.add_contribution(line, ConstructType::For, true);
                self.process_children_with_nesting(node);
                true
            }
            "while_statement" => {
                self.add_contribution(line, ConstructType::While, true);
                self.process_children_with_nesting(node);
                true
            }
            "do_statement" => {
                self.add_contribution(line, ConstructType::DoWhile, true);
                self.process_children_with_nesting(node);
                true
            }
            "switch_statement" => {
                self.add_contribution(line, ConstructType::Switch, true);
                self.process_children_with_nesting(node);
                true
            }
            "catch_clause" => {
                self.add_contribution(line, ConstructType::Catch, true);
                self.process_children_with_nesting(node);
                true
            }
            "try_statement" => {
                // try itself doesn't add complexity
                self.process_children_flat(node);
                true
            }
            "arrow_function" | "function_expression" => {
                // Lambda/closure adds nesting
                self.enter_nesting();
                self.process_children_flat(node);
                self.exit_nesting();
                true
            }
            "ternary_expression" => {
                // Check for nested ternary
                if self.is_nested_ternary(node) {
                    self.add_contribution(line, ConstructType::NestedTernary, true);
                }
                self.process_children_flat(node);
                true
            }
            "labeled_statement" => {
                // Check for break/continue to label
                self.check_labeled_jumps(node, line);
                self.process_children_flat(node);
                true
            }
            _ => false
        }
    }

    /// Process JavaScript if statement children.
    fn process_js_if_children(&mut self, node: Node) {
        self.enter_nesting();

        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            let child_kind = child.kind();
            if child_kind == "else_clause" {
                self.exit_nesting();

                // Check if else contains another if (else if)
                let mut inner_cursor = child.walk();
                let mut has_else_if = false;
                for inner in child.children(&mut inner_cursor) {
                    if inner.kind() == "if_statement" {
                        // This is an else-if, add contribution
                        let inner_line = inner.start_position().row + 1;
                        self.add_contribution(inner_line, ConstructType::ElseIf, true);
                        has_else_if = true;
                        self.process_js_if_children(inner);
                    } else {
                        self.process_node(inner);
                    }
                }

                if !has_else_if {
                    // Plain else, no contribution but process children
                }

                self.enter_nesting();
            } else {
                self.process_node(child);
            }
        }

        self.exit_nesting();
    }

    /// Process Rust-specific nodes.
    /// Returns true if children were processed by this handler.
    fn process_rust_node(&mut self, node: Node, line: usize, kind: &str) -> bool {
        match kind {
            "if_expression" => {
                if self.is_guard_clause(node) {
                    self.add_contribution(line, ConstructType::GuardClause, false);
                    self.process_children_flat(node);
                } else {
                    self.add_contribution(line, ConstructType::If, true);
                    self.process_rust_if_children(node);
                }
                true
            }
            "if_let_expression" => {
                self.add_contribution(line, ConstructType::If, true);
                self.process_children_with_nesting(node);
                true
            }
            "for_expression" => {
                self.add_contribution(line, ConstructType::For, true);
                self.process_children_with_nesting(node);
                true
            }
            "while_expression" | "while_let_expression" => {
                self.add_contribution(line, ConstructType::While, true);
                self.process_children_with_nesting(node);
                true
            }
            "loop_expression" => {
                self.add_contribution(line, ConstructType::While, true);
                self.process_children_with_nesting(node);
                true
            }
            "match_expression" => {
                self.add_contribution(line, ConstructType::Switch, true);
                self.process_children_with_nesting(node);
                true
            }
            "closure_expression" => {
                self.enter_nesting();
                self.process_children_flat(node);
                self.exit_nesting();
                true
            }
            _ => false
        }
    }

    /// Process Rust if expression children.
    fn process_rust_if_children(&mut self, node: Node) {
        self.enter_nesting();

        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            let child_kind = child.kind();
            if child_kind == "else_clause" {
                self.exit_nesting();

                // Check for else if
                let mut inner_cursor = child.walk();
                for inner in child.children(&mut inner_cursor) {
                    if inner.kind() == "if_expression" {
                        let inner_line = inner.start_position().row + 1;
                        self.add_contribution(inner_line, ConstructType::ElseIf, true);
                        self.process_rust_if_children(inner);
                    } else {
                        self.process_node(inner);
                    }
                }

                self.enter_nesting();
            } else {
                self.process_node(child);
            }
        }

        self.exit_nesting();
    }

    /// Process Go-specific nodes.
    /// Returns true if children were processed by this handler.
    fn process_go_node(&mut self, node: Node, line: usize, kind: &str) -> bool {
        match kind {
            "if_statement" => {
                if self.is_guard_clause(node) {
                    self.add_contribution(line, ConstructType::GuardClause, false);
                    self.process_children_flat(node);
                } else {
                    self.add_contribution(line, ConstructType::If, true);
                    self.process_go_if_children(node);
                }
                true
            }
            "for_statement" | "range_clause" => {
                self.add_contribution(line, ConstructType::For, true);
                self.process_children_with_nesting(node);
                true
            }
            "expression_switch_statement" | "type_switch_statement" => {
                self.add_contribution(line, ConstructType::Switch, true);
                self.process_children_with_nesting(node);
                true
            }
            "select_statement" => {
                self.add_contribution(line, ConstructType::Switch, true);
                self.process_children_with_nesting(node);
                true
            }
            "func_literal" => {
                self.enter_nesting();
                self.process_children_flat(node);
                self.exit_nesting();
                true
            }
            "goto_statement" => {
                self.add_contribution(line, ConstructType::Goto, true);
                false // No children to process
            }
            "labeled_statement" => {
                self.check_labeled_jumps(node, line);
                self.process_children_flat(node);
                true
            }
            _ => false
        }
    }

    /// Process Go if statement children.
    fn process_go_if_children(&mut self, node: Node) {
        self.enter_nesting();

        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            let child_kind = child.kind();
            // Go uses "else" followed by "if_statement" or "block"
            if child_kind == "if_statement" {
                // This is an else if
                let inner_line = child.start_position().row + 1;
                self.exit_nesting();
                self.add_contribution(inner_line, ConstructType::ElseIf, true);
                self.process_go_if_children(child);
                self.enter_nesting();
            } else if child_kind == "block" && self.is_else_block(node, child) {
                // This is a plain else block
                self.process_node(child);
            } else {
                self.process_node(child);
            }
        }

        self.exit_nesting();
    }

    /// Check if a block is an else block.
    fn is_else_block(&self, _parent: Node, block: Node) -> bool {
        // Check if preceding sibling is "else" keyword
        if let Some(prev) = block.prev_sibling() {
            return self.node_text(prev) == "else";
        }
        false
    }

    /// Process Java-specific nodes.
    /// Returns true if children were processed by this handler.
    fn process_java_node(&mut self, node: Node, line: usize, kind: &str) -> bool {
        match kind {
            "if_statement" => {
                if self.is_guard_clause(node) {
                    self.add_contribution(line, ConstructType::GuardClause, false);
                    self.process_children_flat(node);
                } else {
                    self.add_contribution(line, ConstructType::If, true);
                    self.process_java_if_children(node);
                }
                true
            }
            "for_statement" | "enhanced_for_statement" => {
                self.add_contribution(line, ConstructType::For, true);
                self.process_children_with_nesting(node);
                true
            }
            "while_statement" => {
                self.add_contribution(line, ConstructType::While, true);
                self.process_children_with_nesting(node);
                true
            }
            "do_statement" => {
                self.add_contribution(line, ConstructType::DoWhile, true);
                self.process_children_with_nesting(node);
                true
            }
            "switch_expression" | "switch_statement" => {
                self.add_contribution(line, ConstructType::Switch, true);
                self.process_children_with_nesting(node);
                true
            }
            "catch_clause" => {
                self.add_contribution(line, ConstructType::Catch, true);
                self.process_children_with_nesting(node);
                true
            }
            "try_statement" => {
                self.process_children_flat(node);
                true
            }
            "lambda_expression" => {
                self.enter_nesting();
                self.process_children_flat(node);
                self.exit_nesting();
                true
            }
            "ternary_expression" => {
                if self.is_nested_ternary(node) {
                    self.add_contribution(line, ConstructType::NestedTernary, true);
                }
                self.process_children_flat(node);
                true
            }
            _ => false
        }
    }

    /// Process Java if statement children.
    fn process_java_if_children(&mut self, node: Node) {
        self.enter_nesting();

        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "if_statement" && self.is_else_if_child(node, child) {
                let inner_line = child.start_position().row + 1;
                self.exit_nesting();
                self.add_contribution(inner_line, ConstructType::ElseIf, true);
                self.process_java_if_children(child);
                self.enter_nesting();
            } else {
                self.process_node(child);
            }
        }

        self.exit_nesting();
    }

    /// Check if a node is an else-if child.
    fn is_else_if_child(&self, _parent: Node, _child: Node) -> bool {
        // Simplified: just return false for now
        // Full implementation would check if preceding sibling is "else"
        false
    }

    /// Process C/C++ specific nodes.
    /// Returns true if children were processed by this handler.
    fn process_c_node(&mut self, node: Node, line: usize, kind: &str) -> bool {
        match kind {
            "if_statement" => {
                if self.is_guard_clause(node) {
                    self.add_contribution(line, ConstructType::GuardClause, false);
                    self.process_children_flat(node);
                } else {
                    self.add_contribution(line, ConstructType::If, true);
                    self.process_c_if_children(node);
                }
                true
            }
            "for_statement" | "for_range_loop" => {
                self.add_contribution(line, ConstructType::For, true);
                self.process_children_with_nesting(node);
                true
            }
            "while_statement" => {
                self.add_contribution(line, ConstructType::While, true);
                self.process_children_with_nesting(node);
                true
            }
            "do_statement" => {
                self.add_contribution(line, ConstructType::DoWhile, true);
                self.process_children_with_nesting(node);
                true
            }
            "switch_statement" => {
                self.add_contribution(line, ConstructType::Switch, true);
                self.process_children_with_nesting(node);
                true
            }
            "catch_clause" => {
                self.add_contribution(line, ConstructType::Catch, true);
                self.process_children_with_nesting(node);
                true
            }
            "try_statement" => {
                self.process_children_flat(node);
                true
            }
            "lambda_expression" => {
                self.enter_nesting();
                self.process_children_flat(node);
                self.exit_nesting();
                true
            }
            "conditional_expression" => {
                if self.is_nested_ternary(node) {
                    self.add_contribution(line, ConstructType::NestedTernary, true);
                }
                self.process_children_flat(node);
                true
            }
            "goto_statement" => {
                self.add_contribution(line, ConstructType::Goto, true);
                false
            }
            _ => false
        }
    }

    /// Process C/C++ if statement children.
    fn process_c_if_children(&mut self, node: Node) {
        self.enter_nesting();

        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            // Look for else clause with nested if
            if child.kind() == "else_clause" {
                self.exit_nesting();

                let mut inner_cursor = child.walk();
                for inner in child.children(&mut inner_cursor) {
                    if inner.kind() == "if_statement" {
                        let inner_line = inner.start_position().row + 1;
                        self.add_contribution(inner_line, ConstructType::ElseIf, true);
                        self.process_c_if_children(inner);
                    } else {
                        self.process_node(inner);
                    }
                }

                self.enter_nesting();
            } else {
                self.process_node(child);
            }
        }

        self.exit_nesting();
    }

    /// Generic node processor for unknown languages.
    /// Returns false since it doesn't process children.
    fn process_generic_node(&mut self, _node: Node, line: usize, kind: &str) -> bool {
        // Basic pattern matching for common constructs
        if kind.contains("if") {
            self.add_contribution(line, ConstructType::If, true);
        } else if kind.contains("for") || kind.contains("while") {
            self.add_contribution(line, ConstructType::For, true);
        } else if kind.contains("switch") || kind.contains("match") {
            self.add_contribution(line, ConstructType::Switch, true);
        } else if kind.contains("catch") || kind.contains("except") {
            self.add_contribution(line, ConstructType::Catch, true);
        }
        // Generic handler doesn't know how to properly process children,
        // so return false to let the default recursive processing happen
        false
    }

    /// Process children with nesting level increment.
    fn process_children_with_nesting(&mut self, node: Node) {
        self.enter_nesting();
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            self.process_node(child);
        }
        self.exit_nesting();
    }

    /// Process children without changing nesting level (flat).
    fn process_children_flat(&mut self, node: Node) {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            self.process_node(child);
        }
    }

    /// Check if a ternary is nested inside another ternary.
    fn is_nested_ternary(&self, node: Node) -> bool {
        let ternary_kinds = [
            "conditional_expression",
            "ternary_expression",
        ];

        let mut current = node.parent();
        while let Some(parent) = current {
            if ternary_kinds.contains(&parent.kind()) {
                return true;
            }
            // Don't search beyond function boundaries
            if parent.kind().contains("function")
                || parent.kind().contains("method")
                || parent.kind() == "lambda"
            {
                break;
            }
            current = parent.parent();
        }
        false
    }

    /// Check for break/continue to label.
    fn check_labeled_jumps(&mut self, node: Node, _line: usize) {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            let child_kind = child.kind();
            if child_kind == "break_statement" || child_kind == "break_expression" {
                // Check if break has a label
                if self.node_text(child).contains(' ') {
                    let break_line = child.start_position().row + 1;
                    self.add_contribution(break_line, ConstructType::BreakToLabel, true);
                }
            } else if child_kind == "continue_statement" || child_kind == "continue_expression" {
                // Check if continue has a label
                if self.node_text(child).contains(' ') {
                    let cont_line = child.start_position().row + 1;
                    self.add_contribution(cont_line, ConstructType::ContinueToLabel, true);
                }
            }
        }
    }

    /// Process function body for cognitive complexity.
    ///
    /// This is the main entry point for analyzing a function's complexity.
    /// It processes all statements in the function body.
    fn process_function_body(&mut self, body: Node) {
        // For Python, body is a "block" containing statements
        // For other languages, body might be a "statement_block" or similar
        let mut cursor = body.walk();
        for child in body.children(&mut cursor) {
            self.process_node(child);
        }
    }
}

// =============================================================================
// PUBLIC API
// =============================================================================

/// Analyze cognitive complexity for a project or directory.
///
/// # Arguments
///
/// * `path` - Path to file or directory to analyze
/// * `language` - Optional language filter
/// * `threshold` - Optional complexity threshold for filtering
///
/// # Returns
///
/// Complete analysis result with individual complexities and statistics.
pub fn analyze_cognitive_complexity(
    path: impl AsRef<Path>,
    language: Option<&str>,
    threshold: Option<u32>,
) -> Result<CognitiveAnalysis> {
    let path = path.as_ref();

    if !path.exists() {
        return Err(BrrrError::Io(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!("Path not found: {}", path.display()),
        )));
    }

    if path.is_file() {
        return analyze_file_cognitive_complexity(path, threshold);
    }

    // Directory analysis
    let path_str = path.to_str().ok_or_else(|| {
        BrrrError::InvalidArgument("Invalid path encoding".to_string())
    })?;

    let scanner = ProjectScanner::new(path_str)?;

    let config = if let Some(lang) = language {
        ScanConfig::for_language(lang)
    } else {
        ScanConfig::default()
    };

    let scan_result = scanner.scan_with_config(&config)?;

    if scan_result.files.is_empty() {
        return Err(BrrrError::InvalidArgument(format!(
            "No source files found in {} (filter: {:?})",
            path.display(),
            language
        )));
    }

    debug!(
        "Analyzing {} files for cognitive complexity",
        scan_result.files.len()
    );

    // Analyze files in parallel
    let results: Vec<(Vec<CognitiveComplexity>, Vec<CognitiveAnalysisError>)> = scan_result
        .files
        .par_iter()
        .map(|file| analyze_file_functions_cognitive(file))
        .collect();

    // Aggregate results
    let mut all_functions = Vec::new();
    let mut all_errors = Vec::new();

    for (functions, errors) in results {
        all_functions.extend(functions);
        all_errors.extend(errors);
    }

    // Calculate statistics
    let stats = CognitiveStats::from_complexities(&all_functions);

    // Filter violations
    let violations = threshold.map(|t| {
        all_functions
            .iter()
            .filter(|f| f.complexity > t)
            .cloned()
            .collect::<Vec<_>>()
    });

    Ok(CognitiveAnalysis {
        path: path.to_path_buf(),
        language: language.map(String::from),
        functions: all_functions,
        violations,
        stats,
        threshold,
        errors: all_errors,
    })
}

/// Analyze cognitive complexity for a single file.
pub fn analyze_file_cognitive_complexity(
    file: impl AsRef<Path>,
    threshold: Option<u32>,
) -> Result<CognitiveAnalysis> {
    let file = file.as_ref();

    if !file.exists() {
        return Err(BrrrError::Io(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!("File not found: {}", file.display()),
        )));
    }

    if !file.is_file() {
        return Err(BrrrError::InvalidArgument(format!(
            "Expected a file, got directory: {}",
            file.display()
        )));
    }

    let (functions, errors) = analyze_file_functions_cognitive(file);

    let stats = CognitiveStats::from_complexities(&functions);

    let violations = threshold.map(|t| {
        functions
            .iter()
            .filter(|f| f.complexity > t)
            .cloned()
            .collect::<Vec<_>>()
    });

    let registry = LanguageRegistry::global();
    let language = registry
        .detect_language(file)
        .map(|l| l.name().to_string());

    Ok(CognitiveAnalysis {
        path: file.to_path_buf(),
        language,
        functions,
        violations,
        stats,
        threshold,
        errors,
    })
}

/// Internal function to analyze all functions in a file.
fn analyze_file_functions_cognitive(
    file: &Path,
) -> (Vec<CognitiveComplexity>, Vec<CognitiveAnalysisError>) {
    let mut results = Vec::new();
    let mut errors = Vec::new();

    // Read file content
    let source = match std::fs::read(file) {
        Ok(s) => s,
        Err(e) => {
            errors.push(CognitiveAnalysisError {
                file: file.to_path_buf(),
                message: format!("Failed to read file: {}", e),
            });
            return (results, errors);
        }
    };

    // Get language
    let registry = LanguageRegistry::global();
    let lang = match registry.detect_language(file) {
        Some(l) => l,
        None => {
            errors.push(CognitiveAnalysisError {
                file: file.to_path_buf(),
                message: "Unknown language".to_string(),
            });
            return (results, errors);
        }
    };

    // Parse file
    let mut parser = match lang.parser() {
        Ok(p) => p,
        Err(e) => {
            errors.push(CognitiveAnalysisError {
                file: file.to_path_buf(),
                message: format!("Failed to create parser: {}", e),
            });
            return (results, errors);
        }
    };

    let tree = match parser.parse(&source, None) {
        Some(t) => t,
        None => {
            errors.push(CognitiveAnalysisError {
                file: file.to_path_buf(),
                message: "Failed to parse file".to_string(),
            });
            return (results, errors);
        }
    };

    // Extract module info to get function list
    let module = match AstExtractor::extract_file(file) {
        Ok(m) => m,
        Err(e) => {
            errors.push(CognitiveAnalysisError {
                file: file.to_path_buf(),
                message: format!("Failed to extract AST: {}", e),
            });
            return (results, errors);
        }
    };

    let lang_name = lang.name();

    // Analyze top-level functions
    for func in &module.functions {
        let result = analyze_function_cognitive(
            &source,
            &tree,
            &func.name,
            func.line_number,
            func.end_line_number.unwrap_or(func.line_number),
            file,
            lang_name,
        );
        results.push(result);
    }

    // Analyze class methods
    for class in &module.classes {
        for method in &class.methods {
            let qualified_name = format!("{}.{}", class.name, method.name);
            let mut result = analyze_function_cognitive(
                &source,
                &tree,
                &qualified_name,
                method.line_number,
                method.end_line_number.unwrap_or(method.line_number),
                file,
                lang_name,
            );
            result.function_name = qualified_name;
            results.push(result);
        }

        // Analyze nested classes
        analyze_nested_classes_cognitive(
            &source,
            &tree,
            class,
            &class.name,
            file,
            lang_name,
            &mut results,
        );
    }

    (results, errors)
}

/// Recursively analyze nested class methods.
fn analyze_nested_classes_cognitive(
    source: &[u8],
    tree: &Tree,
    class: &crate::ast::types::ClassInfo,
    class_prefix: &str,
    file: &Path,
    lang_name: &str,
    results: &mut Vec<CognitiveComplexity>,
) {
    for nested in &class.inner_classes {
        let nested_prefix = format!("{}.{}", class_prefix, nested.name);

        for method in &nested.methods {
            let qualified_name = format!("{}.{}", nested_prefix, method.name);
            let mut result = analyze_function_cognitive(
                source,
                tree,
                &qualified_name,
                method.line_number,
                method.end_line_number.unwrap_or(method.line_number),
                file,
                lang_name,
            );
            result.function_name = qualified_name;
            results.push(result);
        }

        // Recurse into further nested classes
        analyze_nested_classes_cognitive(
            source,
            tree,
            nested,
            &nested_prefix,
            file,
            lang_name,
            results,
        );
    }
}

/// Analyze cognitive complexity for a single function.
fn analyze_function_cognitive(
    source: &[u8],
    tree: &Tree,
    function_name: &str,
    start_line: usize,
    end_line: usize,
    file: &Path,
    language: &str,
) -> CognitiveComplexity {
    // Find the function node in the tree
    let func_node = find_function_node(tree.root_node(), function_name, start_line, source, language);

    if let Some(node) = func_node {
        // Get the simple function name for recursion detection
        let simple_name = function_name
            .rsplit('.')
            .next()
            .unwrap_or(function_name)
            .to_string();

        // Analyze the function body directly from the original tree
        let mut calculator = CognitiveCalculator::new(source, simple_name, language);

        // Find and process the function body (skip the function signature)
        let body_node = find_function_body(node, language);
        if let Some(body) = body_node {
            calculator.process_function_body(body);
        } else {
            // Fallback: process all children of the function
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                // Skip non-body parts like parameters, return type, decorators
                if !is_function_signature_part(child.kind(), language) {
                    calculator.process_node(child);
                }
            }
        }

        return CognitiveComplexity {
            function_name: function_name.to_string(),
            file: file.to_path_buf(),
            line: start_line,
            end_line,
            complexity: calculator.complexity,
            risk_level: CognitiveRiskLevel::from_complexity(calculator.complexity),
            breakdown: calculator.breakdown,
            max_nesting: calculator.max_nesting,
            recursion_count: calculator.recursion_count,
        };
    }

    // Fallback: return minimal result
    CognitiveComplexity {
        function_name: function_name.to_string(),
        file: file.to_path_buf(),
        line: start_line,
        end_line,
        complexity: 0,
        risk_level: CognitiveRiskLevel::Low,
        breakdown: Vec::new(),
        max_nesting: 0,
        recursion_count: 0,
    }
}

/// Find the body node of a function.
fn find_function_body<'a>(node: Node<'a>, language: &str) -> Option<Node<'a>> {
    let body_field = match language {
        "python" => "body",
        "typescript" | "javascript" | "tsx" | "jsx" => "body",
        "rust" => "body",
        "go" => "body",
        "java" => "body",
        "c" | "cpp" => "body",
        _ => "body",
    };

    node.child_by_field_name(body_field)
}

/// Check if a node kind is part of the function signature (not body).
fn is_function_signature_part(kind: &str, _language: &str) -> bool {
    matches!(
        kind,
        "parameters"
            | "formal_parameters"
            | "parameter_list"
            | "type_parameters"
            | "return_type"
            | "type_annotation"
            | "type"
            | "decorator"
            | "modifiers"
            | "visibility_modifier"
            | "identifier"
            | "name"
            | "def"
            | "fn"
            | "func"
            | "function"
            | "async"
            | "("
            | ")"
            | "{"
            | "}"
            | ":"
            | "->"
    )
}

/// Find a function node by name and line number.
fn find_function_node<'a>(
    root: Node<'a>,
    function_name: &str,
    start_line: usize,
    source: &[u8],
    language: &str,
) -> Option<Node<'a>> {
    // Get the simple name (last part after dots)
    let simple_name = function_name.rsplit('.').next().unwrap_or(function_name);

    // Define function node kinds per language
    let function_kinds: &[&str] = match language {
        "python" => &["function_definition"],
        "typescript" | "javascript" | "tsx" | "jsx" => {
            &["function_declaration", "method_definition", "arrow_function"]
        }
        "rust" => &["function_item"],
        "go" => &["function_declaration", "method_declaration"],
        "java" => &["method_declaration", "constructor_declaration"],
        "c" | "cpp" => &["function_definition"],
        _ => &["function_definition", "function_declaration"],
    };

    find_node_recursive(root, simple_name, start_line, source, function_kinds)
}

/// Recursively find a function node.
fn find_node_recursive<'a>(
    node: Node<'a>,
    target_name: &str,
    target_line: usize,
    source: &[u8],
    function_kinds: &[&str],
) -> Option<Node<'a>> {
    let node_line = node.start_position().row + 1;

    if function_kinds.contains(&node.kind()) {
        // Check if this is the function we're looking for
        if node_line == target_line {
            // Verify name matches
            if let Some(name_node) = node.child_by_field_name("name") {
                let name =
                    std::str::from_utf8(&source[name_node.start_byte()..name_node.end_byte()])
                        .unwrap_or("");
                if name == target_name {
                    return Some(node);
                }
            }
        }
    }

    // Search children
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if let Some(found) = find_node_recursive(child, target_name, target_line, source, function_kinds) {
            return Some(found);
        }
    }

    None
}

// =============================================================================
// TESTS
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    fn create_temp_file(content: &str, extension: &str) -> NamedTempFile {
        let mut file = tempfile::Builder::new()
            .suffix(extension)
            .tempfile()
            .expect("Failed to create temp file");
        file.write_all(content.as_bytes())
            .expect("Failed to write to temp file");
        file
    }

    #[test]
    fn test_risk_level_classification() {
        assert_eq!(CognitiveRiskLevel::from_complexity(0), CognitiveRiskLevel::Low);
        assert_eq!(CognitiveRiskLevel::from_complexity(5), CognitiveRiskLevel::Low);
        assert_eq!(CognitiveRiskLevel::from_complexity(6), CognitiveRiskLevel::Medium);
        assert_eq!(CognitiveRiskLevel::from_complexity(10), CognitiveRiskLevel::Medium);
        assert_eq!(CognitiveRiskLevel::from_complexity(11), CognitiveRiskLevel::High);
        assert_eq!(CognitiveRiskLevel::from_complexity(15), CognitiveRiskLevel::High);
        assert_eq!(CognitiveRiskLevel::from_complexity(16), CognitiveRiskLevel::Critical);
    }

    #[test]
    fn test_simple_function_complexity() {
        let source = r#"
def simple():
    return 42
"#;
        let file = create_temp_file(source, ".py");
        let result = analyze_file_cognitive_complexity(file.path(), None);

        assert!(result.is_ok());
        let analysis = result.unwrap();

        assert_eq!(analysis.functions.len(), 1);
        assert_eq!(analysis.functions[0].function_name, "simple");
        assert_eq!(analysis.functions[0].complexity, 0);
    }

    #[test]
    fn test_if_statement_complexity() {
        let source = r#"
def with_if(x):
    if x > 0:
        return 1
    return 0
"#;
        let file = create_temp_file(source, ".py");
        let result = analyze_file_cognitive_complexity(file.path(), None);

        assert!(result.is_ok());
        let analysis = result.unwrap();

        assert_eq!(analysis.functions.len(), 1);
        // if at nesting level 0: +1 base, +0 nesting = 1
        assert_eq!(analysis.functions[0].complexity, 1);
    }

    #[test]
    fn test_nested_if_complexity() {
        let source = r#"
def nested_if(x, y):
    if x > 0:
        if y > 0:
            return "both positive"
    return "other"
"#;
        let file = create_temp_file(source, ".py");
        let result = analyze_file_cognitive_complexity(file.path(), None);

        assert!(result.is_ok());
        let analysis = result.unwrap();

        assert_eq!(analysis.functions.len(), 1);
        // outer if: +1 (base) + 0 (nesting) = 1
        // inner if: +1 (base) + 1 (nesting) = 2
        // Total: 3
        assert_eq!(analysis.functions[0].complexity, 3);
    }

    #[test]
    fn test_for_loop_complexity() {
        let source = r#"
def with_loop(items):
    total = 0
    for item in items:
        total += item
    return total
"#;
        let file = create_temp_file(source, ".py");
        let result = analyze_file_cognitive_complexity(file.path(), None);

        assert!(result.is_ok());
        let analysis = result.unwrap();

        assert_eq!(analysis.functions.len(), 1);
        // for: +1 base, +0 nesting = 1
        assert_eq!(analysis.functions[0].complexity, 1);
    }

    #[test]
    fn test_if_else_complexity() {
        let source = r#"
def with_else(x):
    if x > 0:
        return "positive"
    else:
        return "non-positive"
"#;
        let file = create_temp_file(source, ".py");
        let result = analyze_file_cognitive_complexity(file.path(), None);

        assert!(result.is_ok());
        let analysis = result.unwrap();

        assert_eq!(analysis.functions.len(), 1);
        // if: +1, else: +0 (no increment for else)
        // Total: 1
        assert_eq!(analysis.functions[0].complexity, 1);
    }

    #[test]
    fn test_elif_complexity() {
        let source = r#"
def with_elif(x):
    if x > 0:
        return "positive"
    elif x < 0:
        return "negative"
    else:
        return "zero"
"#;
        let file = create_temp_file(source, ".py");
        let result = analyze_file_cognitive_complexity(file.path(), None);

        assert!(result.is_ok());
        let analysis = result.unwrap();

        assert_eq!(analysis.functions.len(), 1);
        // if: +1, elif: +1, else: +0
        // Total: 2
        assert_eq!(analysis.functions[0].complexity, 2);
    }

    #[test]
    fn test_try_except_complexity() {
        let source = r#"
def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return 0
"#;
        let file = create_temp_file(source, ".py");
        let result = analyze_file_cognitive_complexity(file.path(), None);

        assert!(result.is_ok());
        let analysis = result.unwrap();

        assert_eq!(analysis.functions.len(), 1);
        // except: +1
        assert_eq!(analysis.functions[0].complexity, 1);
    }

    #[test]
    fn test_deeply_nested_complexity() {
        let source = r#"
def deeply_nested(a, b, c, d):
    if a:
        if b:
            if c:
                if d:
                    return "all true"
    return "not all true"
"#;
        let file = create_temp_file(source, ".py");
        let result = analyze_file_cognitive_complexity(file.path(), None);

        assert!(result.is_ok());
        let analysis = result.unwrap();

        assert_eq!(analysis.functions.len(), 1);
        // if a: +1 + 0 = 1
        // if b: +1 + 1 = 2
        // if c: +1 + 2 = 3
        // if d: +1 + 3 = 4
        // Total: 10
        assert_eq!(analysis.functions[0].complexity, 10);
        assert_eq!(analysis.functions[0].max_nesting, 4);
    }

    #[test]
    fn test_logical_operator_sequence() {
        let source = r#"
def check_all(a, b, c, d):
    if a and b and c and d:
        return True
    return False
"#;
        let file = create_temp_file(source, ".py");
        let result = analyze_file_cognitive_complexity(file.path(), None);

        assert!(result.is_ok());
        let analysis = result.unwrap();

        assert_eq!(analysis.functions.len(), 1);
        // if: +1
        // a and b and c and d: +1 (sequence counts as 1, not 3)
        // Total: 2
        assert!(analysis.functions[0].complexity <= 3);
    }

    #[test]
    fn test_class_method_complexity() {
        let source = r#"
class Calculator:
    def add(self, a, b):
        return a + b

    def smart_divide(self, a, b):
        if b == 0:
            return None
        return a / b
"#;
        let file = create_temp_file(source, ".py");
        let result = analyze_file_cognitive_complexity(file.path(), None);

        assert!(result.is_ok());
        let analysis = result.unwrap();

        assert_eq!(analysis.functions.len(), 2);

        let add = analysis
            .functions
            .iter()
            .find(|f| f.function_name == "Calculator.add");
        let divide = analysis
            .functions
            .iter()
            .find(|f| f.function_name == "Calculator.smart_divide");

        assert!(add.is_some());
        assert!(divide.is_some());

        assert_eq!(add.unwrap().complexity, 0);
        assert_eq!(divide.unwrap().complexity, 1);
    }

    #[test]
    fn test_threshold_filtering() {
        let source = r#"
def simple():
    return 1

def complex_func(a, b, c):
    if a:
        if b:
            if c:
                return "nested"
    return "flat"
"#;
        let file = create_temp_file(source, ".py");
        let result = analyze_file_cognitive_complexity(file.path(), Some(2));

        assert!(result.is_ok());
        let analysis = result.unwrap();

        assert!(analysis.violations.is_some());
        let violations = analysis.violations.unwrap();

        // Only complex_func should be a violation
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].function_name, "complex_func");
    }

    #[test]
    fn test_typescript_if_complexity() {
        let source = r#"
function withIf(x: number): string {
    if (x > 0) {
        return "positive";
    }
    return "non-positive";
}
"#;
        let file = create_temp_file(source, ".ts");
        let result = analyze_file_cognitive_complexity(file.path(), None);

        assert!(result.is_ok());
        let analysis = result.unwrap();

        assert_eq!(analysis.functions.len(), 1);
        assert_eq!(analysis.functions[0].complexity, 1);
    }

    #[test]
    fn test_nonexistent_file() {
        let result = analyze_file_cognitive_complexity("/nonexistent/path/file.py", None);
        assert!(result.is_err());
    }

    #[test]
    fn test_empty_file() {
        let source = "# Just a comment\n";
        let file = create_temp_file(source, ".py");
        let result = analyze_file_cognitive_complexity(file.path(), None);

        assert!(result.is_ok());
        let analysis = result.unwrap();

        assert_eq!(analysis.functions.len(), 0);
        assert_eq!(analysis.stats.total_functions, 0);
    }

    #[test]
    fn test_breakdown_details() {
        let source = r#"
def example(x, y):
    if x > 0:
        for i in range(y):
            if i > 5:
                print(i)
"#;
        let file = create_temp_file(source, ".py");
        let result = analyze_file_cognitive_complexity(file.path(), None);

        assert!(result.is_ok());
        let analysis = result.unwrap();

        assert_eq!(analysis.functions.len(), 1);
        let func = &analysis.functions[0];

        // Verify breakdown exists and has expected constructs
        assert!(!func.breakdown.is_empty());

        // outer if: +1 + 0 = 1
        // for: +1 + 1 = 2
        // inner if: +1 + 2 = 3
        // Total: 6
        assert_eq!(func.complexity, 6);
    }

    #[test]
    fn test_statistics_calculation() {
        let results = vec![
            CognitiveComplexity {
                function_name: "f1".to_string(),
                file: PathBuf::new(),
                line: 1,
                end_line: 5,
                complexity: 2,
                risk_level: CognitiveRiskLevel::Low,
                breakdown: vec![],
                max_nesting: 1,
                recursion_count: 0,
            },
            CognitiveComplexity {
                function_name: "f2".to_string(),
                file: PathBuf::new(),
                line: 10,
                end_line: 20,
                complexity: 8,
                risk_level: CognitiveRiskLevel::Medium,
                breakdown: vec![],
                max_nesting: 3,
                recursion_count: 1,
            },
        ];

        let stats = CognitiveStats::from_complexities(&results);

        assert_eq!(stats.total_functions, 2);
        assert_eq!(stats.min_complexity, 2);
        assert_eq!(stats.max_complexity, 8);
        assert_eq!(stats.functions_with_recursion, 1);
        assert!((stats.average_complexity - 5.0).abs() < 0.01);
    }
}