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
//! Cohesion metrics (LCOM variants) for class quality analysis.
//!
//! Lack of Cohesion of Methods (LCOM) measures how tightly related the methods
//! of a class are. High LCOM indicates a class that might be doing too many things
//! and should potentially be split into multiple classes.
//!
//! # LCOM Variants
//!
//! ## LCOM1 (Chidamber-Kemerer Original)
//! ```text
//! P = number of method pairs that DON'T share instance variables
//! Q = number of method pairs that DO share instance variables
//! LCOM1 = max(0, P - Q)
//! ```
//! - LCOM1 = 0: All methods share at least one attribute (cohesive)
//! - LCOM1 > 0: Some methods don't share attributes (less cohesive)
//!
//! ## LCOM2 (Chidamber-Kemerer Simplified)
//! ```text
//! LCOM2 = P - Q (can be negative = good cohesion)
//! ```
//! - LCOM2 < 0: More method pairs share attributes than not
//! - LCOM2 = 0: Equal sharing
//! - LCOM2 > 0: Poor cohesion
//!
//! ## LCOM3 (Henderson-Sellers)
//! Number of connected components in the method-attribute graph.
//! ```text
//! Graph: nodes = methods + attributes
//! Edges: method -> attribute (if method uses attribute)
//! LCOM3 = number of connected components
//! ```
//! - LCOM3 = 1: Perfectly cohesive class
//! - LCOM3 > 1: Class might be N separate classes
//!
//! ## LCOM4 (Extends LCOM3 with method calls)
//! Same as LCOM3 but also connects methods that call each other.
//! ```text
//! Additional edges: method -> method (if one calls the other)
//! LCOM4 = number of connected components
//! ```
//! - LCOM4 = 1: Perfectly cohesive
//! - LCOM4 > 1: Consider splitting into LCOM4 classes
//!
//! # Interpretation Guidelines
//!
//! - Classes with LCOM3/4 = 1 are well-designed
//! - Classes with LCOM3/4 > 1 might violate Single Responsibility Principle
//! - Static methods should be excluded (they don't use instance state)
//! - Constructors may have artificially low cohesion (initialize all fields)
//! - Utility classes may have low cohesion by design

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

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

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

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

/// Cohesion level based on LCOM3 value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CohesionLevel {
    /// LCOM3 = 1: Perfectly cohesive
    High,
    /// LCOM3 = 2: Minor cohesion issue
    Medium,
    /// LCOM3 = 3-4: Moderate cohesion problem
    Low,
    /// LCOM3 >= 5: Severe cohesion problem
    VeryLow,
}

impl CohesionLevel {
    /// Classify LCOM3 value into cohesion level.
    #[must_use]
    pub fn from_lcom3(lcom3: u32) -> Self {
        match lcom3 {
            0 | 1 => Self::High,
            2 => Self::Medium,
            3 | 4 => Self::Low,
            _ => Self::VeryLow,
        }
    }

    /// Get human-readable description.
    #[must_use]
    pub const fn description(&self) -> &'static str {
        match self {
            Self::High => "Cohesive class, well-designed",
            Self::Medium => "Minor cohesion issue, consider reviewing",
            Self::Low => "Low cohesion, consider splitting class",
            Self::VeryLow => "Very low cohesion, strongly recommend splitting",
        }
    }

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

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

/// Cohesion metrics for a single class.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CohesionMetrics {
    /// Class name (may include module prefix for nested classes)
    pub class_name: String,
    /// File path containing the class
    pub file: PathBuf,
    /// Starting line number (1-indexed)
    pub line: usize,
    /// Ending line number (1-indexed)
    pub end_line: usize,
    /// LCOM1 value: max(0, P - Q) where P = non-sharing pairs, Q = sharing pairs
    pub lcom1: u32,
    /// LCOM2 value: P - Q (can be negative)
    pub lcom2: i32,
    /// LCOM3 value: number of connected components in method-attribute graph
    pub lcom3: u32,
    /// LCOM4 value: LCOM3 extended with method-to-method call edges
    pub lcom4: u32,
    /// Number of instance methods analyzed
    pub methods: u32,
    /// Number of instance attributes detected
    pub attributes: u32,
    /// Cohesion level based on LCOM3
    pub cohesion_level: CohesionLevel,
    /// Whether class has low cohesion (LCOM3 > 1)
    pub is_low_cohesion: bool,
    /// Suggestion for improvement (if LCOM3 > 1)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub suggestion: Option<String>,
    /// Names of methods in each connected component (for LCOM4)
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub components: Vec<Vec<String>>,
}

/// Aggregate cohesion statistics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CohesionStats {
    /// Total number of classes analyzed
    pub total_classes: usize,
    /// Number of classes with LCOM3 = 1 (cohesive)
    pub cohesive_classes: usize,
    /// Number of classes with LCOM3 > 1 (potential issues)
    pub low_cohesion_classes: usize,
    /// Average LCOM3 across all classes
    pub average_lcom3: f64,
    /// Maximum LCOM3 found
    pub max_lcom3: u32,
    /// Distribution by cohesion level
    pub cohesion_distribution: HashMap<String, usize>,
    /// Average methods per class
    pub average_methods: f64,
    /// Average attributes per class
    pub average_attributes: f64,
}

impl CohesionStats {
    /// Calculate statistics from a list of cohesion metrics.
    fn from_metrics(metrics: &[CohesionMetrics]) -> Self {
        if metrics.is_empty() {
            return Self {
                total_classes: 0,
                cohesive_classes: 0,
                low_cohesion_classes: 0,
                average_lcom3: 0.0,
                max_lcom3: 0,
                cohesion_distribution: HashMap::new(),
                average_methods: 0.0,
                average_attributes: 0.0,
            };
        }

        let total = metrics.len();
        let cohesive = metrics.iter().filter(|m| m.lcom3 <= 1).count();
        let low_cohesion = metrics.iter().filter(|m| m.lcom3 > 1).count();

        let lcom3_sum: u64 = metrics.iter().map(|m| u64::from(m.lcom3)).sum();
        let average_lcom3 = lcom3_sum as f64 / total as f64;

        let max_lcom3 = metrics.iter().map(|m| m.lcom3).max().unwrap_or(0);

        let methods_sum: u64 = metrics.iter().map(|m| u64::from(m.methods)).sum();
        let attrs_sum: u64 = metrics.iter().map(|m| u64::from(m.attributes)).sum();

        let mut cohesion_distribution = HashMap::new();
        for m in metrics {
            *cohesion_distribution.entry(m.cohesion_level.to_string()).or_insert(0) += 1;
        }

        Self {
            total_classes: total,
            cohesive_classes: cohesive,
            low_cohesion_classes: low_cohesion,
            average_lcom3,
            max_lcom3,
            cohesion_distribution,
            average_methods: methods_sum as f64 / total as f64,
            average_attributes: attrs_sum as f64 / total as f64,
        }
    }
}

/// Complete cohesion analysis result for a file or project.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CohesionAnalysis {
    /// Path that was analyzed (file or directory)
    pub path: PathBuf,
    /// Language filter applied (if any)
    pub language: Option<String>,
    /// Individual class cohesion metrics
    pub classes: Vec<CohesionMetrics>,
    /// Classes with LCOM3 > threshold (if threshold specified)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub violations: Option<Vec<CohesionMetrics>>,
    /// Aggregate statistics
    pub stats: CohesionStats,
    /// Threshold used for filtering (if any)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub threshold: Option<u32>,
    /// Files that could not be analyzed
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub errors: Vec<CohesionError>,
}

/// Error encountered during cohesion analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CohesionError {
    /// File path where error occurred
    pub file: PathBuf,
    /// Error message
    pub message: String,
}

// =============================================================================
// METHOD-ATTRIBUTE GRAPH
// =============================================================================

/// Represents the method-attribute graph for LCOM calculation.
#[derive(Debug, Default)]
struct MethodAttributeGraph {
    /// Method names
    methods: Vec<String>,
    /// Attribute names
    attributes: HashSet<String>,
    /// Which attributes each method accesses: method_name -> set of attribute names
    method_attributes: HashMap<String, HashSet<String>>,
    /// Which methods each method calls: caller -> set of callee names
    method_calls: HashMap<String, HashSet<String>>,
}

impl MethodAttributeGraph {
    fn new() -> Self {
        Self::default()
    }

    /// Add a method to the graph.
    fn add_method(&mut self, name: &str) {
        if !self.methods.contains(&name.to_string()) {
            self.methods.push(name.to_string());
        }
    }

    /// Record that a method accesses an attribute.
    fn add_attribute_access(&mut self, method: &str, attribute: &str) {
        self.attributes.insert(attribute.to_string());
        self.method_attributes
            .entry(method.to_string())
            .or_default()
            .insert(attribute.to_string());
    }

    /// Record that one method calls another.
    fn add_method_call(&mut self, caller: &str, callee: &str) {
        self.method_calls
            .entry(caller.to_string())
            .or_default()
            .insert(callee.to_string());
    }

    /// Calculate LCOM1: max(0, P - Q)
    /// P = pairs that don't share attributes
    /// Q = pairs that share at least one attribute
    fn calculate_lcom1(&self) -> u32 {
        let (p, q) = self.count_sharing_pairs();
        if p > q { (p - q) as u32 } else { 0 }
    }

    /// Calculate LCOM2: P - Q (can be negative)
    fn calculate_lcom2(&self) -> i32 {
        let (p, q) = self.count_sharing_pairs();
        (p as i32) - (q as i32)
    }

    /// Count method pairs that share/don't share attributes.
    /// Returns (non_sharing_pairs, sharing_pairs)
    fn count_sharing_pairs(&self) -> (usize, usize) {
        let n = self.methods.len();
        if n < 2 {
            return (0, 0);
        }

        let mut p = 0; // non-sharing pairs
        let mut q = 0; // sharing pairs

        for i in 0..n {
            for j in (i + 1)..n {
                let m1 = &self.methods[i];
                let m2 = &self.methods[j];

                let attrs1 = self.method_attributes.get(m1);
                let attrs2 = self.method_attributes.get(m2);

                let shares = match (attrs1, attrs2) {
                    (Some(a1), Some(a2)) => !a1.is_disjoint(a2),
                    _ => false,
                };

                if shares {
                    q += 1;
                } else {
                    p += 1;
                }
            }
        }

        (p, q)
    }

    /// Calculate LCOM3: number of connected components (method-attribute graph only)
    fn calculate_lcom3(&self) -> (u32, Vec<Vec<String>>) {
        self.find_connected_components(false)
    }

    /// Calculate LCOM4: number of connected components (including method calls)
    fn calculate_lcom4(&self) -> (u32, Vec<Vec<String>>) {
        self.find_connected_components(true)
    }

    /// Find connected components in the method-attribute graph.
    /// If include_method_calls is true, also connects methods that call each other.
    fn find_connected_components(&self, include_method_calls: bool) -> (u32, Vec<Vec<String>>) {
        if self.methods.is_empty() {
            return (0, Vec::new());
        }

        // Build adjacency list for methods
        // Two methods are adjacent if they share an attribute or (optionally) call each other
        let mut adjacency: HashMap<&str, HashSet<&str>> = HashMap::new();

        for method in &self.methods {
            adjacency.insert(method.as_str(), HashSet::new());
        }

        // Connect methods that share attributes
        for i in 0..self.methods.len() {
            for j in (i + 1)..self.methods.len() {
                let m1 = &self.methods[i];
                let m2 = &self.methods[j];

                let attrs1 = self.method_attributes.get(m1);
                let attrs2 = self.method_attributes.get(m2);

                let shares_attribute = match (attrs1, attrs2) {
                    (Some(a1), Some(a2)) => !a1.is_disjoint(a2),
                    _ => false,
                };

                if shares_attribute {
                    adjacency.get_mut(m1.as_str()).unwrap().insert(m2.as_str());
                    adjacency.get_mut(m2.as_str()).unwrap().insert(m1.as_str());
                }
            }
        }

        // Connect methods that call each other (for LCOM4)
        if include_method_calls {
            for (caller, callees) in &self.method_calls {
                if !self.methods.contains(caller) {
                    continue;
                }
                for callee in callees {
                    if self.methods.contains(callee) {
                        adjacency.get_mut(caller.as_str()).unwrap().insert(callee.as_str());
                        adjacency.get_mut(callee.as_str()).unwrap().insert(caller.as_str());
                    }
                }
            }
        }

        // BFS to find connected components
        let mut visited: HashSet<&str> = HashSet::new();
        let mut components: Vec<Vec<String>> = Vec::new();

        for method in &self.methods {
            if visited.contains(method.as_str()) {
                continue;
            }

            let mut component = Vec::new();
            let mut queue = VecDeque::new();
            queue.push_back(method.as_str());
            visited.insert(method.as_str());

            while let Some(current) = queue.pop_front() {
                component.push(current.to_string());

                if let Some(neighbors) = adjacency.get(current) {
                    for &neighbor in neighbors {
                        if !visited.contains(neighbor) {
                            visited.insert(neighbor);
                            queue.push_back(neighbor);
                        }
                    }
                }
            }

            components.push(component);
        }

        (components.len() as u32, components)
    }
}

// =============================================================================
// ATTRIBUTE EXTRACTION
// =============================================================================

/// Extract instance attribute accesses from a method body.
///
/// Language-specific patterns:
/// - Python: `self.attr`
/// - TypeScript/JavaScript: `this.attr`
/// - Rust: `self.field`
/// - Go: receiver.field (where receiver is the struct type)
fn extract_attribute_accesses(
    node: Node,
    source: &[u8],
    language: &str,
) -> HashSet<String> {
    let mut attributes = HashSet::new();
    extract_attributes_recursive(node, source, language, &mut attributes);
    attributes
}

fn extract_attributes_recursive(
    node: Node,
    source: &[u8],
    language: &str,
    attributes: &mut HashSet<String>,
) {
    let node_kind = node.kind();

    // Check for attribute access patterns based on language
    match language {
        "python" => {
            // Python: self.attr as attribute access
            if node_kind == "attribute" {
                if let Some(object) = node.child_by_field_name("object") {
                    let obj_text = node_text(object, source);
                    if obj_text == "self" {
                        if let Some(attr) = node.child_by_field_name("attribute") {
                            let attr_name = node_text(attr, source);
                            // Exclude methods (will be handled separately)
                            if !attr_name.starts_with('_') || attr_name.starts_with("__") && attr_name.ends_with("__") {
                                // Include private attrs but filter dunder methods
                                if !(attr_name.starts_with("__") && attr_name.ends_with("__")) {
                                    attributes.insert(attr_name.to_string());
                                }
                            } else {
                                attributes.insert(attr_name.to_string());
                            }
                        }
                    }
                }
            }
        }
        "typescript" | "javascript" | "tsx" | "jsx" => {
            // TypeScript/JavaScript: this.attr
            if node_kind == "member_expression" {
                if let Some(object) = node.child_by_field_name("object") {
                    let obj_text = node_text(object, source);
                    if obj_text == "this" {
                        if let Some(prop) = node.child_by_field_name("property") {
                            let attr_name = node_text(prop, source);
                            attributes.insert(attr_name.to_string());
                        }
                    }
                }
            }
        }
        "rust" => {
            // Rust: self.field
            if node_kind == "field_expression" {
                if let Some(value) = node.child_by_field_name("value") {
                    let val_text = node_text(value, source);
                    if val_text == "self" {
                        if let Some(field) = node.child_by_field_name("field") {
                            let field_name = node_text(field, source);
                            attributes.insert(field_name.to_string());
                        }
                    }
                }
            }
        }
        "go" => {
            // Go: receiver.field - first parameter of method
            // We detect selector_expression where the object matches receiver pattern
            if node_kind == "selector_expression" {
                // In Go, methods access struct fields via the receiver parameter
                // This is more complex to detect accurately without full type info
                // For now, we'll check for single-letter identifiers (common Go pattern)
                // or identifiers matching common receiver names
                if let Some(operand) = node.child_by_field_name("operand") {
                    let operand_kind = operand.kind();
                    if operand_kind == "identifier" {
                        let var_name = node_text(operand, source);
                        // Common Go receiver patterns: single letter, or common names
                        if var_name.len() <= 3 || var_name.starts_with("this") || var_name.starts_with("self") {
                            if let Some(field) = node.child_by_field_name("field") {
                                let field_name = node_text(field, source);
                                attributes.insert(field_name.to_string());
                            }
                        }
                    }
                }
            }
        }
        "java" | "kotlin" | "csharp" => {
            // Java/Kotlin/C#: this.field or implicit field access
            if node_kind == "field_access" || node_kind == "member_access_expression" {
                if let Some(object) = node.child_by_field_name("object") {
                    let obj_text = node_text(object, source);
                    if obj_text == "this" {
                        if let Some(field) = node.child_by_field_name("field").or_else(|| node.child_by_field_name("name")) {
                            let field_name = node_text(field, source);
                            attributes.insert(field_name.to_string());
                        }
                    }
                }
            }
        }
        "cpp" | "c" => {
            // C++: this->field
            if node_kind == "field_expression" {
                if let Some(argument) = node.child_by_field_name("argument") {
                    let arg_text = node_text(argument, source);
                    if arg_text == "this" {
                        if let Some(field) = node.child_by_field_name("field") {
                            let field_name = node_text(field, source);
                            attributes.insert(field_name.to_string());
                        }
                    }
                }
            }
        }
        _ => {}
    }

    // Recurse into children
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        extract_attributes_recursive(child, source, language, attributes);
    }
}

/// Extract method calls within a method body (for LCOM4).
fn extract_method_calls(
    node: Node,
    source: &[u8],
    language: &str,
    class_methods: &HashSet<String>,
) -> HashSet<String> {
    let mut calls = HashSet::new();
    extract_calls_recursive(node, source, language, class_methods, &mut calls);
    calls
}

fn extract_calls_recursive(
    node: Node,
    source: &[u8],
    language: &str,
    class_methods: &HashSet<String>,
    calls: &mut HashSet<String>,
) {
    let node_kind = node.kind();

    match language {
        "python" => {
            // Python: self.method() calls
            if node_kind == "call" {
                if let Some(func) = node.child_by_field_name("function") {
                    if func.kind() == "attribute" {
                        if let Some(obj) = func.child_by_field_name("object") {
                            if node_text(obj, source) == "self" {
                                if let Some(attr) = func.child_by_field_name("attribute") {
                                    let method_name = node_text(attr, source);
                                    if class_methods.contains(method_name) {
                                        calls.insert(method_name.to_string());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        "typescript" | "javascript" | "tsx" | "jsx" => {
            // this.method() calls
            if node_kind == "call_expression" {
                if let Some(func) = node.child_by_field_name("function") {
                    if func.kind() == "member_expression" {
                        if let Some(obj) = func.child_by_field_name("object") {
                            if node_text(obj, source) == "this" {
                                if let Some(prop) = func.child_by_field_name("property") {
                                    let method_name = node_text(prop, source);
                                    if class_methods.contains(method_name) {
                                        calls.insert(method_name.to_string());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        "rust" => {
            // self.method() calls
            if node_kind == "call_expression" {
                if let Some(func) = node.child_by_field_name("function") {
                    if func.kind() == "field_expression" {
                        if let Some(val) = func.child_by_field_name("value") {
                            if node_text(val, source) == "self" {
                                if let Some(field) = func.child_by_field_name("field") {
                                    let method_name = node_text(field, source);
                                    if class_methods.contains(method_name) {
                                        calls.insert(method_name.to_string());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        _ => {}
    }

    // Recurse
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        extract_calls_recursive(child, source, language, class_methods, calls);
    }
}

/// Helper to get node text safely.
fn node_text<'a>(node: Node<'a>, source: &'a [u8]) -> &'a str {
    std::str::from_utf8(&source[node.start_byte()..node.end_byte()]).unwrap_or("")
}

// =============================================================================
// ANALYSIS FUNCTIONS
// =============================================================================

/// Analyze cohesion for a project or directory.
///
/// # Arguments
///
/// * `path` - Path to file or directory to analyze
/// * `language` - Optional language filter
/// * `threshold` - Optional LCOM3 threshold for filtering (default: show all classes)
///
/// # Returns
///
/// Complete analysis with individual class metrics and statistics.
pub fn analyze_cohesion(
    path: impl AsRef<Path>,
    language: Option<&str>,
    threshold: Option<u32>,
) -> Result<CohesionAnalysis> {
    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_cohesion(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 cohesion", scan_result.files.len());

    // Analyze files in parallel
    let results: Vec<(Vec<CohesionMetrics>, Vec<CohesionError>)> = scan_result
        .files
        .par_iter()
        .map(|file| analyze_file_classes(file, threshold))
        .collect();

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

    for (classes, errors) in results {
        all_classes.extend(classes);
        all_errors.extend(errors);
    }

    // Calculate statistics
    let stats = CohesionStats::from_metrics(&all_classes);

    // Filter violations if threshold specified
    let violations = threshold.map(|t| {
        all_classes
            .iter()
            .filter(|c| c.lcom3 > t)
            .cloned()
            .collect::<Vec<_>>()
    });

    Ok(CohesionAnalysis {
        path: path.to_path_buf(),
        language: language.map(String::from),
        classes: all_classes,
        violations,
        stats,
        threshold,
        errors: all_errors,
    })
}

/// Analyze cohesion for a single file.
pub fn analyze_file_cohesion(
    file: impl AsRef<Path>,
    threshold: Option<u32>,
) -> Result<CohesionAnalysis> {
    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 (classes, errors) = analyze_file_classes(file, threshold);
    let stats = CohesionStats::from_metrics(&classes);

    let violations = threshold.map(|t| {
        classes
            .iter()
            .filter(|c| c.lcom3 > t)
            .cloned()
            .collect::<Vec<_>>()
    });

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

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

/// Internal function to analyze all classes in a file.
fn analyze_file_classes(
    file: &Path,
    _threshold: Option<u32>,
) -> (Vec<CohesionMetrics>, Vec<CohesionError>) {
    let mut results = Vec::new();
    let mut errors = Vec::new();

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

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

    let language = &module.language;

    // Get parser for this language
    let registry = LanguageRegistry::global();
    let lang_impl = match registry.detect_language(file) {
        Some(l) => l,
        None => {
            errors.push(CohesionError {
                file: file.to_path_buf(),
                message: "Unsupported language".to_string(),
            });
            return (results, errors);
        }
    };

    let mut parser = match lang_impl.parser() {
        Ok(p) => p,
        Err(e) => {
            errors.push(CohesionError {
                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(CohesionError {
                file: file.to_path_buf(),
                message: "Failed to parse file".to_string(),
            });
            return (results, errors);
        }
    };

    // Analyze each class
    for class in &module.classes {
        if let Some(metrics) = analyze_class_cohesion(
            file,
            class,
            &tree,
            &source,
            language,
        ) {
            results.push(metrics);
        }

        // Also analyze nested classes
        for inner in &class.inner_classes {
            if let Some(metrics) = analyze_class_cohesion(
                file,
                inner,
                &tree,
                &source,
                language,
            ) {
                results.push(metrics);
            }
        }
    }

    (results, errors)
}

/// Analyze cohesion for a single class.
fn analyze_class_cohesion(
    file: &Path,
    class: &crate::ast::types::ClassInfo,
    tree: &tree_sitter::Tree,
    source: &[u8],
    language: &str,
) -> Option<CohesionMetrics> {
    // Skip classes with no methods
    if class.methods.is_empty() {
        return None;
    }

    // Build method-attribute graph
    let mut graph = MethodAttributeGraph::new();

    // Collect method names (excluding static methods and dunder methods for Python)
    let mut class_method_names: HashSet<String> = HashSet::new();

    for method in &class.methods {
        // Skip static methods (they don't use instance state)
        let is_static = method.decorators.iter().any(|d| {
            d == "staticmethod" || d == "static" || d.contains("@staticmethod")
        });

        // For Python, skip if first param is not self/cls
        let is_class_method = method.decorators.iter().any(|d| {
            d == "classmethod" || d.contains("@classmethod")
        });

        if is_static || is_class_method {
            continue;
        }

        // Skip Python dunder methods except __init__
        if language == "python" && method.name.starts_with("__") && method.name.ends_with("__") {
            if method.name != "__init__" {
                continue;
            }
        }

        class_method_names.insert(method.name.clone());
        graph.add_method(&method.name);
    }

    // Skip classes with 0 or 1 instance methods (trivially cohesive)
    if graph.methods.len() <= 1 {
        return None;
    }

    // Find class node in AST and extract attribute accesses per method
    let root = tree.root_node();
    if let Some(class_node) = find_class_node(root, &class.name, class.line_number) {
        for method in &class.methods {
            if !class_method_names.contains(&method.name) {
                continue;
            }

            // Find method node within class
            if let Some(method_node) = find_method_node(class_node, &method.name, method.line_number, language) {
                // Extract attribute accesses
                let attrs = extract_attribute_accesses(method_node, source, language);
                for attr in &attrs {
                    graph.add_attribute_access(&method.name, attr);
                }

                // Extract method calls for LCOM4
                let calls = extract_method_calls(method_node, source, language, &class_method_names);
                for callee in &calls {
                    graph.add_method_call(&method.name, callee);
                }
            }
        }
    }

    // Calculate LCOM metrics
    let lcom1 = graph.calculate_lcom1();
    let lcom2 = graph.calculate_lcom2();
    let (lcom3, _) = graph.calculate_lcom3();
    let (lcom4, components) = graph.calculate_lcom4();

    let cohesion_level = CohesionLevel::from_lcom3(lcom3);
    let is_low_cohesion = lcom3 > 1;

    let suggestion = if lcom4 > 1 {
        Some(format!(
            "Consider splitting into {} classes based on connected components",
            lcom4
        ))
    } else {
        None
    };

    Some(CohesionMetrics {
        class_name: class.name.clone(),
        file: file.to_path_buf(),
        line: class.line_number,
        end_line: class.end_line_number.unwrap_or(class.line_number),
        lcom1,
        lcom2,
        lcom3,
        lcom4,
        methods: graph.methods.len() as u32,
        attributes: graph.attributes.len() as u32,
        cohesion_level,
        is_low_cohesion,
        suggestion,
        components,
    })
}

/// Find a class node by name and line number.
fn find_class_node<'a>(node: Node<'a>, class_name: &str, line: usize) -> Option<Node<'a>> {
    let node_kind = node.kind();

    // Check if this is a class definition
    let is_class = matches!(
        node_kind,
        "class_definition" | "class_declaration" | "class" |
        "impl_item" | "struct_item" | "type_declaration"
    );

    if is_class {
        // Try to get name from various field names
        let name = node.child_by_field_name("name")
            .or_else(|| {
                // For Python class_definition, name is direct child
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    if child.kind() == "identifier" || child.kind() == "type_identifier" {
                        return Some(child);
                    }
                }
                None
            });

        if name.is_some() {
            // We need access to source for name comparison
            // Since we don't have it here, check by line number instead
            let node_line = node.start_position().row + 1;
            if node_line == line {
                return Some(node);
            }
        }
    }

    // Recurse into children
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if let Some(found) = find_class_node(child, class_name, line) {
            return Some(found);
        }
    }

    None
}

/// Find a method node within a class.
fn find_method_node<'a>(
    class_node: Node<'a>,
    _method_name: &str,
    line: usize,
    language: &str,
) -> Option<Node<'a>> {
    let method_kinds = match language {
        "python" => vec!["function_definition"],
        "typescript" | "javascript" | "tsx" | "jsx" => vec!["method_definition", "function_declaration", "function"],
        "rust" => vec!["function_item"],
        "go" => vec!["function_declaration", "method_declaration"],
        "java" | "kotlin" | "csharp" => vec!["method_declaration", "function_declaration"],
        "cpp" | "c" => vec!["function_definition", "function_declarator"],
        _ => vec!["function_definition", "method_definition"],
    };

    find_method_recursive(class_node, &method_kinds, line)
}

fn find_method_recursive<'a>(
    node: Node<'a>,
    method_kinds: &[&str],
    line: usize,
) -> Option<Node<'a>> {
    if method_kinds.contains(&node.kind()) {
        let node_line = node.start_position().row + 1;
        if node_line == line {
            return Some(node);
        }
    }

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if let Some(found) = find_method_recursive(child, method_kinds, line) {
            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_cohesion_level_classification() {
        assert_eq!(CohesionLevel::from_lcom3(0), CohesionLevel::High);
        assert_eq!(CohesionLevel::from_lcom3(1), CohesionLevel::High);
        assert_eq!(CohesionLevel::from_lcom3(2), CohesionLevel::Medium);
        assert_eq!(CohesionLevel::from_lcom3(3), CohesionLevel::Low);
        assert_eq!(CohesionLevel::from_lcom3(4), CohesionLevel::Low);
        assert_eq!(CohesionLevel::from_lcom3(5), CohesionLevel::VeryLow);
        assert_eq!(CohesionLevel::from_lcom3(10), CohesionLevel::VeryLow);
    }

    #[test]
    fn test_cohesion_level_display() {
        assert_eq!(CohesionLevel::High.to_string(), "high");
        assert_eq!(CohesionLevel::Medium.to_string(), "medium");
        assert_eq!(CohesionLevel::Low.to_string(), "low");
        assert_eq!(CohesionLevel::VeryLow.to_string(), "very_low");
    }

    #[test]
    fn test_method_attribute_graph_lcom1() {
        let mut graph = MethodAttributeGraph::new();

        // Two methods sharing an attribute
        graph.add_method("method_a");
        graph.add_method("method_b");
        graph.add_attribute_access("method_a", "attr1");
        graph.add_attribute_access("method_b", "attr1");

        // LCOM1 should be 0 (all pairs share)
        assert_eq!(graph.calculate_lcom1(), 0);

        // Add third method not sharing
        graph.add_method("method_c");
        graph.add_attribute_access("method_c", "attr2");

        // Now: (a,b) share, (a,c) don't, (b,c) don't
        // P = 2, Q = 1, LCOM1 = max(0, 2-1) = 1
        assert_eq!(graph.calculate_lcom1(), 1);
    }

    #[test]
    fn test_method_attribute_graph_lcom2() {
        let mut graph = MethodAttributeGraph::new();

        // All methods share attributes - negative LCOM2 (good)
        graph.add_method("m1");
        graph.add_method("m2");
        graph.add_method("m3");
        graph.add_attribute_access("m1", "a");
        graph.add_attribute_access("m2", "a");
        graph.add_attribute_access("m3", "a");

        // All 3 pairs share attribute 'a'
        // P = 0, Q = 3, LCOM2 = 0 - 3 = -3
        assert_eq!(graph.calculate_lcom2(), -3);
    }

    #[test]
    fn test_method_attribute_graph_connected_components() {
        let mut graph = MethodAttributeGraph::new();

        // Two separate clusters
        // Cluster 1: m1, m2 share attr1
        graph.add_method("m1");
        graph.add_method("m2");
        graph.add_attribute_access("m1", "attr1");
        graph.add_attribute_access("m2", "attr1");

        // Cluster 2: m3, m4 share attr2
        graph.add_method("m3");
        graph.add_method("m4");
        graph.add_attribute_access("m3", "attr2");
        graph.add_attribute_access("m4", "attr2");

        let (lcom3, components) = graph.calculate_lcom3();
        assert_eq!(lcom3, 2);
        assert_eq!(components.len(), 2);
    }

    #[test]
    fn test_method_attribute_graph_lcom4_with_calls() {
        let mut graph = MethodAttributeGraph::new();

        // Two separate attribute clusters
        graph.add_method("m1");
        graph.add_method("m2");
        graph.add_method("m3");
        graph.add_attribute_access("m1", "attr1");
        graph.add_attribute_access("m2", "attr1");
        graph.add_attribute_access("m3", "attr2");

        // Without method calls: 2 components (m1,m2) and (m3)
        let (lcom3, _) = graph.calculate_lcom3();
        assert_eq!(lcom3, 2);

        // With method call connecting them
        graph.add_method_call("m2", "m3");
        let (lcom4, _) = graph.calculate_lcom4();
        assert_eq!(lcom4, 1); // Now all connected
    }

    #[test]
    fn test_cohesive_python_class() {
        let source = r#"
class Calculator:
    def __init__(self):
        self.value = 0
        self.history = []

    def add(self, x):
        self.value += x
        self.history.append(('add', x))

    def subtract(self, x):
        self.value -= x
        self.history.append(('sub', x))

    def get_value(self):
        return self.value

    def get_history(self):
        return self.history
"#;
        let file = create_temp_file(source, ".py");
        let result = analyze_file_cohesion(file.path(), None);

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

        assert_eq!(analysis.classes.len(), 1);
        let metrics = &analysis.classes[0];
        assert_eq!(metrics.class_name, "Calculator");
        // All methods share 'value' or 'history' attributes
        assert!(metrics.lcom3 <= 2, "Expected cohesive class, got LCOM3 = {}", metrics.lcom3);
    }

    #[test]
    fn test_low_cohesion_python_class() {
        let source = r#"
class GodObject:
    def process_users(self):
        self.users = []
        return self.users

    def handle_payments(self):
        self.payments = []
        return self.payments

    def send_emails(self):
        self.emails = []
        return self.emails

    def generate_reports(self):
        self.reports = []
        return self.reports
"#;
        let file = create_temp_file(source, ".py");
        let result = analyze_file_cohesion(file.path(), None);

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

        assert_eq!(analysis.classes.len(), 1);
        let metrics = &analysis.classes[0];
        assert_eq!(metrics.class_name, "GodObject");
        // Each method uses different attributes - no sharing
        assert!(metrics.lcom3 >= 3, "Expected low cohesion, got LCOM3 = {}", metrics.lcom3);
        assert!(metrics.is_low_cohesion);
    }

    #[test]
    fn test_statistics_calculation() {
        let metrics = vec![
            CohesionMetrics {
                class_name: "A".to_string(),
                file: PathBuf::from("a.py"),
                line: 1,
                end_line: 10,
                lcom1: 0,
                lcom2: -2,
                lcom3: 1,
                lcom4: 1,
                methods: 3,
                attributes: 2,
                cohesion_level: CohesionLevel::High,
                is_low_cohesion: false,
                suggestion: None,
                components: vec![],
            },
            CohesionMetrics {
                class_name: "B".to_string(),
                file: PathBuf::from("b.py"),
                line: 1,
                end_line: 20,
                lcom1: 5,
                lcom2: 3,
                lcom3: 3,
                lcom4: 2,
                methods: 4,
                attributes: 4,
                cohesion_level: CohesionLevel::Low,
                is_low_cohesion: true,
                suggestion: Some("Consider splitting".to_string()),
                components: vec![],
            },
        ];

        let stats = CohesionStats::from_metrics(&metrics);

        assert_eq!(stats.total_classes, 2);
        assert_eq!(stats.cohesive_classes, 1);
        assert_eq!(stats.low_cohesion_classes, 1);
        assert_eq!(stats.max_lcom3, 3);
        assert!((stats.average_lcom3 - 2.0).abs() < 0.01);
    }

    #[test]
    fn test_empty_class_skipped() {
        let source = r#"
class Empty:
    pass
"#;
        let file = create_temp_file(source, ".py");
        let result = analyze_file_cohesion(file.path(), None);

        assert!(result.is_ok());
        let analysis = result.unwrap();
        // Empty class should be skipped
        assert_eq!(analysis.classes.len(), 0);
    }

    #[test]
    fn test_single_method_class_skipped() {
        let source = r#"
class SingleMethod:
    def only_method(self):
        self.attr = 1
"#;
        let file = create_temp_file(source, ".py");
        let result = analyze_file_cohesion(file.path(), None);

        assert!(result.is_ok());
        let analysis = result.unwrap();
        // Single-method classes are trivially cohesive, skip them
        assert_eq!(analysis.classes.len(), 0);
    }

    #[test]
    fn test_static_methods_excluded() {
        let source = r#"
class WithStatic:
    @staticmethod
    def static_helper():
        return 42

    def instance_method(self):
        self.value = 1

    def another_instance(self):
        self.value = 2
"#;
        let file = create_temp_file(source, ".py");
        let result = analyze_file_cohesion(file.path(), None);

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

        assert_eq!(analysis.classes.len(), 1);
        let metrics = &analysis.classes[0];
        // Only 2 instance methods, static method excluded
        assert_eq!(metrics.methods, 2);
    }

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

    #[test]
    fn test_threshold_filtering() {
        let source = r#"
class Cohesive:
    def method_a(self):
        self.shared = 1
    def method_b(self):
        self.shared = 2

class NotCohesive:
    def isolated_a(self):
        self.a = 1
    def isolated_b(self):
        self.b = 1
    def isolated_c(self):
        self.c = 1
"#;
        let file = create_temp_file(source, ".py");
        let result = analyze_file_cohesion(file.path(), Some(1));

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

        // Should have violations (classes with LCOM3 > 1)
        assert!(analysis.violations.is_some());
        let violations = analysis.violations.unwrap();
        // NotCohesive should be a violation
        assert!(violations.iter().any(|v| v.class_name == "NotCohesive"));
    }
}