repotoire 0.5.3

Graph-powered code analysis CLI. 106 detectors for security, architecture, and code quality.
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
//! Class context and role inference from graph analysis
//!
//! Computes rich context for each class using graph metrics,
//! enabling smarter god-class detection beyond naive thresholds.

#![allow(dead_code)] // Module under development - structs/helpers used in tests only

use crate::graph::{EdgeKind, NodeKind};
use crate::graph::GraphQueryExt;
use std::collections::{HashMap, HashSet};
use tracing::{debug, info};

/// Inferred architectural role of a class
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClassRole {
    /// Framework core class (Flask, Express, Django, etc.)
    FrameworkCore,
    /// Facade pattern: large API surface but delegates to helpers
    Facade,
    /// Orchestrator: router, controller, dispatcher, handler — delegates to services
    Orchestrator,
    /// Entry point: main app class, CLI handler
    EntryPoint,
    /// Utility class: helpers, shared code
    Utility,
    /// Data class: DTO, model, entity (mostly data, few methods)
    DataClass,
    /// Regular application class
    Application,
}

impl ClassRole {
    /// Whether this role justifies large size
    pub fn allows_large_size(&self) -> bool {
        matches!(
            self,
            ClassRole::FrameworkCore
                | ClassRole::Facade
                | ClassRole::Orchestrator
                | ClassRole::EntryPoint
        )
    }

    /// Severity multiplier for god class findings
    pub fn severity_multiplier(&self) -> f64 {
        match self {
            ClassRole::FrameworkCore => 0.0, // Don't flag at all
            ClassRole::Facade => 0.3,        // Greatly reduce
            ClassRole::Orchestrator => 0.3,  // Greatly reduce — orchestrators delegate by design
            ClassRole::EntryPoint => 0.5,    // Reduce
            ClassRole::Utility => 0.7,       // Slightly reduce
            ClassRole::DataClass => 0.6,     // Data classes can be big
            ClassRole::Application => 1.0,   // Normal
        }
    }
}

/// Known framework class names that are intentionally large
const FRAMEWORK_CORE_NAMES: &[&str] = &[
    // Python frameworks
    "Flask",
    "Sanic",
    "FastAPI",
    "Django",
    "Bottle",
    "Tornado",
    "Application",
    "App",
    // Flask internals
    "Blueprint",
    "Scaffold",
    // JavaScript/Node
    "Express",
    "Koa",
    "Hapi",
    "Fastify",
    "NestFactory",
    // Java
    "SpringApplication",
    "Application",
    // Go
    "Gin",
    "Echo",
    "Fiber",
    "Mux",
    "Server",
    // General patterns
    "Router",
    "Server",
    "Gateway",
    "Proxy",
];

/// Patterns that indicate framework-like classes
const FRAMEWORK_PATTERNS: &[&str] = &["Application", "Framework", "Server", "Gateway", "Router"];

/// Suffixes that indicate framework core classes (e.g., Django internals)
const FRAMEWORK_CORE_SUFFIXES: &[&str] = &[
    "SchemaEditor", "Autodetector", "Compiler", "Admin",
    "Manager", "Registry", "Dispatcher",
];

/// Names/suffixes that indicate orchestrator classes (controllers, routers, dispatchers)
/// These classes delegate to services by design and should not be flagged for god class or feature envy.
const ORCHESTRATOR_NAME_PATTERNS: &[&str] = &[
    "Controller",
    "Router",
    "Handler",
    "Dispatcher",
    "Orchestrator",
    "Coordinator",
    "Mediator",
    "Presenter",
    "Endpoint",
    "Resource",    // JAX-RS resource classes
    "ViewSet",     // Django REST framework
    "Viewset",
    "View",        // MVC views that dispatch
    "Resolver",    // GraphQL resolvers
    "Middleware",
];

/// File path patterns that indicate orchestrator/routing code
const ORCHESTRATOR_PATH_PATTERNS: &[&str] = &[
    "/controllers/",
    "/controller/",
    "/routers/",
    "/router/",
    "/handlers/",
    "/handler/",
    "/dispatchers/",
    "/endpoints/",
    "/resources/",
    "/views/",
    "/viewsets/",
    "/resolvers/",
    "/middleware/",
    "/routes/",
];

/// Rich context for a class computed from graph analysis
#[derive(Debug, Clone)]
pub struct ClassContext {
    /// Qualified name (graph key)
    pub qualified_name: String,
    /// Simple class name
    pub name: String,
    /// File path
    pub file_path: String,

    // === Metrics ===
    /// Number of methods
    pub method_count: usize,
    /// Total lines of code
    pub loc: usize,
    /// Total complexity
    pub complexity: usize,
    /// Average complexity per method (low = thin wrappers)
    pub avg_method_complexity: f64,
    /// Number of methods calling external classes/functions
    pub delegating_methods: usize,
    /// Delegation ratio: what % of methods primarily delegate
    pub delegation_ratio: f64,
    /// Number of public methods (API surface)
    pub public_methods: usize,
    /// Number of unique external classes/modules called
    pub external_dependencies: usize,
    /// How many other classes use this one
    pub usages: usize,

    // === Inferred properties ===
    /// Inferred architectural role
    pub role: ClassRole,
    /// Is in a test file
    pub is_test: bool,
    /// Is in a framework/vendor path
    pub is_framework_path: bool,
    /// Specific reason for role assignment
    pub role_reason: String,
}

impl ClassContext {
    /// Whether god class finding should be skipped entirely
    pub fn skip_god_class(&self) -> bool {
        self.role == ClassRole::FrameworkCore || self.is_framework_path
    }

    /// Get adjusted thresholds based on role
    pub fn adjusted_thresholds(&self, base_methods: usize, base_loc: usize) -> (usize, usize) {
        match self.role {
            ClassRole::FrameworkCore => (usize::MAX, usize::MAX),
            ClassRole::Facade => (base_methods * 3, base_loc * 3),
            ClassRole::Orchestrator => (base_methods * 3, base_loc * 3), // Orchestrators can have many short delegate methods
            ClassRole::EntryPoint => (base_methods * 2, base_loc * 2),
            ClassRole::Utility => (
                (base_methods as f64 * 1.5) as usize,
                (base_loc as f64 * 1.5) as usize,
            ),
            ClassRole::DataClass => (base_methods * 2, base_loc * 2), // Data classes can have many getters/setters
            ClassRole::Application => (base_methods, base_loc),
        }
    }
}

/// Map of qualified names to class contexts
pub type ClassContextMap = HashMap<String, ClassContext>;

/// Builder that computes class contexts from the graph
pub struct ClassContextBuilder<'a> {
    graph: &'a dyn crate::graph::GraphQuery,
    /// Threshold for average complexity to consider "thin wrapper"
    thin_wrapper_complexity: f64,
    /// Threshold for delegation ratio to consider "facade"
    facade_delegation_ratio: f64,
}

impl<'a> ClassContextBuilder<'a> {
    pub fn new(graph: &'a dyn crate::graph::GraphQuery) -> Self {
        let _i = graph.interner();
        Self {
            graph,
            thin_wrapper_complexity: 3.0, // Avg complexity <= 3 = thin methods
            facade_delegation_ratio: 0.6, // 60%+ methods delegate = facade
        }
    }

    /// Build context map for all classes
    pub fn build(&self) -> ClassContextMap {
        let i = self.graph.interner();
        let start = std::time::Instant::now();

        let class_idxs = self.graph.classes_idx();

        // Use NodeIndex-based fast path when available (CodeGraph)
        // Fall back to old API for GraphBuilder (used in tests)
        if class_idxs.is_empty() {
            let classes = self.graph.get_classes_shared();
            if classes.is_empty() {
                return HashMap::new();
            }
            return self.build_legacy(i, &classes);
        }

        let class_count = class_idxs.len();

        info!("Building class context for {} classes", class_count);

        let call_edges = self.graph.all_call_edges();

        // Build call lookup: function qn -> set of called qns
        let call_map: HashMap<&str, HashSet<&str>> = {
            let mut map: HashMap<&str, HashSet<&str>> = HashMap::new();
            for &(caller_idx, callee_idx) in call_edges {
                if let (Some(caller), Some(callee)) = (self.graph.node_idx(caller_idx), self.graph.node_idx(callee_idx)) {
                    map.entry(caller.qn(i))
                        .or_default()
                        .insert(callee.qn(i));
                }
            }
            map
        };

        // Build class method map: class qn -> vec of method nodes
        // Group classes by file first to avoid calling functions_in_file_idx() 13K+ times.
        // With ~4 classes/file, this reduces from 13K to ~3.4K file lookups.
        let class_methods: HashMap<&str, Vec<crate::graph::store_models::CodeNode>> = {
            let mut map: HashMap<&str, Vec<crate::graph::store_models::CodeNode>> = HashMap::new();

            // Group classes by file path
            let mut classes_by_file: HashMap<&str, Vec<&crate::graph::store_models::CodeNode>> =
                HashMap::new();
            for &class_idx in class_idxs {
                if let Some(class) = self.graph.node_idx(class_idx) {
                    classes_by_file
                        .entry(class.path(i))
                        .or_default()
                        .push(class);
                }
            }

            // For each unique file, fetch functions once and assign to all classes in that file
            for (file_path, file_classes) in &classes_by_file {
                let file_func_idxs = self.graph.functions_in_file_idx(file_path);
                for class in file_classes {
                    let methods: Vec<_> = file_func_idxs
                        .iter()
                        .filter_map(|&idx| self.graph.node_idx(idx))
                        .filter(|f| {
                            f.line_start >= class.line_start && f.line_end <= class.line_end
                        })
                        .copied()
                        .collect();
                    if !methods.is_empty() {
                        map.insert(class.qn(i), methods);
                    }
                }
            }
            map
        };

        // Build class usage map: how many other classes use each class
        // O(E) approach: build method->class reverse map, then iterate call edges
        let class_usages: HashMap<&str, usize> = {
            // Build reverse map: method_qn -> class_qn
            let mut method_to_class: HashMap<&str, &str> = HashMap::new();
            for (class_qn, methods) in &class_methods {
                for method in methods {
                    method_to_class.insert(method.qn(i), class_qn);
                }
            }

            // For each call edge, if caller and callee belong to different classes,
            // record that caller's class uses callee's class
            let mut class_pair_seen: HashSet<(&str, &str)> = HashSet::new();
            let mut usages: HashMap<&str, usize> = HashMap::new();

            for &(caller_idx, callee_idx) in call_edges {
                if let (Some(caller), Some(callee)) = (self.graph.node_idx(caller_idx), self.graph.node_idx(callee_idx)) {
                    let caller_class = method_to_class.get(caller.qn(i));
                    let callee_class = method_to_class.get(callee.qn(i));
                    if let (Some(&from_class), Some(&to_class)) = (caller_class, callee_class) {
                        if from_class != to_class && class_pair_seen.insert((from_class, to_class)) {
                            *usages.entry(to_class).or_insert(0) += 1;
                        }
                    }
                }
            }
            usages
        };

        let mut contexts = ClassContextMap::new();

        for &class_idx in class_idxs {
            let Some(class) = self.graph.node_idx(class_idx) else { continue };
            let qn = class.qn(i);

            let methods = class_methods.get(qn).cloned().unwrap_or_default();
            // Use methodCount property if available (from parser), fall back to graph count
            let method_count = class
                .get_i64("methodCount")
                .map(|n| n as usize)
                .unwrap_or_else(|| methods.len());

            // Calculate aggregate complexity
            let total_complexity: i64 = methods.iter().filter_map(|m| m.complexity_opt()).sum();

            let avg_complexity = if method_count > 0 {
                total_complexity as f64 / method_count as f64
            } else {
                0.0
            };

            // Calculate delegation: methods that call external code
            let mut delegating_count = 0;
            let mut external_deps: HashSet<String> = HashSet::new();

            for method in &methods {
                if let Some(callees) = call_map.get(method.qn(i)) {
                    let external_calls: Vec<_> = callees
                        .iter()
                        .filter(|c| !methods.iter().any(|m| m.qn(i) == **c))
                        .collect();

                    if !external_calls.is_empty() {
                        delegating_count += 1;
                        for ext in external_calls {
                            // Extract module/class from qn
                            if let Some(module) = ext.rsplit("::").nth(1) {
                                external_deps.insert(module.to_string());
                            }
                        }
                    }
                }
            }

            let delegation_ratio = if method_count > 0 {
                delegating_count as f64 / method_count as f64
            } else {
                0.0
            };

            // Count public methods (heuristic: doesn't start with _)
            let public_methods = methods.iter().filter(|m| !m.node_name(i).starts_with('_')).count();

            let usages = *class_usages.get(qn).unwrap_or(&0);
            let is_test = self.is_test_path(class.path(i));
            let is_framework_path = self.is_framework_path(class.path(i));

            // Infer role
            let (role, role_reason) = self.infer_role(
                class.node_name(i),
                class.path(i),
                method_count,
                avg_complexity,
                delegation_ratio,
                external_deps.len(),
                usages,
                is_test,
                is_framework_path,
            );

            contexts.insert(
                qn.to_string(),
                ClassContext {
                    qualified_name: qn.to_string(),
                    name: class.node_name(i).to_string(),
                    file_path: class.path(i).to_string(),
                    method_count,
                    loc: class.loc() as usize,
                    complexity: total_complexity as usize,
                    avg_method_complexity: avg_complexity,
                    delegating_methods: delegating_count,
                    delegation_ratio,
                    public_methods,
                    external_dependencies: external_deps.len(),
                    usages,
                    role,
                    is_test,
                    is_framework_path,
                    role_reason,
                },
            );
        }

        let elapsed = start.elapsed();
        info!("Built class context in {:?}", elapsed);

        // Log role distribution
        let mut role_counts: HashMap<ClassRole, usize> = HashMap::new();
        for ctx in contexts.values() {
            *role_counts.entry(ctx.role).or_insert(0) += 1;
        }
        debug!("Class role distribution: {:?}", role_counts);

        contexts
    }

    /// Build using old string-based API (GraphBuilder fallback for tests).
    fn build_legacy(
        &self,
        i: &crate::graph::interner::StringInterner,
        classes: &std::sync::Arc<[crate::graph::store_models::CodeNode]>,
    ) -> ClassContextMap {
        let start = std::time::Instant::now();
        info!("Building class context for {} classes (legacy)", classes.len());

        let calls = self.graph.get_calls_shared();

        let call_map: HashMap<&str, HashSet<&str>> = {
            let mut map: HashMap<&str, HashSet<&str>> = HashMap::new();
            for (caller, callee) in calls.iter() {
                map.entry(i.resolve(*caller))
                    .or_default()
                    .insert(i.resolve(*callee));
            }
            map
        };

        let class_methods: HashMap<&str, Vec<crate::graph::store_models::CodeNode>> = {
            let mut map: HashMap<&str, Vec<crate::graph::store_models::CodeNode>> = HashMap::new();
            let mut classes_by_file: HashMap<&str, Vec<&crate::graph::store_models::CodeNode>> =
                HashMap::new();
            for class in classes.iter() {
                classes_by_file
                    .entry(class.path(i))
                    .or_default()
                    .push(class);
            }
            for (file_path, file_classes) in &classes_by_file {
                let file_funcs = self.graph.get_functions_in_file(file_path);
                for class in file_classes {
                    let methods: Vec<_> = file_funcs
                        .iter()
                        .filter(|f| f.line_start >= class.line_start && f.line_end <= class.line_end)
                        .cloned()
                        .collect();
                    if !methods.is_empty() {
                        map.insert(class.qn(i), methods);
                    }
                }
            }
            map
        };

        let class_usages: HashMap<&str, usize> = {
            let mut method_to_class: HashMap<&str, &str> = HashMap::new();
            for (class_qn, methods) in &class_methods {
                for method in methods {
                    method_to_class.insert(method.qn(i), class_qn);
                }
            }
            let mut class_pair_seen: HashSet<(&str, &str)> = HashSet::new();
            let mut usages: HashMap<&str, usize> = HashMap::new();
            for (caller, callee) in calls.iter() {
                let caller_class = method_to_class.get(i.resolve(*caller));
                let callee_class = method_to_class.get(i.resolve(*callee));
                if let (Some(&from_class), Some(&to_class)) = (caller_class, callee_class) {
                    if from_class != to_class && class_pair_seen.insert((from_class, to_class)) {
                        *usages.entry(to_class).or_insert(0) += 1;
                    }
                }
            }
            usages
        };

        let mut contexts = ClassContextMap::new();
        for class in classes.iter() {
            let qn = class.qn(i);
            let methods = class_methods.get(qn).cloned().unwrap_or_default();
            let method_count = class.get_i64("methodCount").map(|n| n as usize).unwrap_or(methods.len());
            let total_complexity: i64 = methods.iter().filter_map(|m| m.complexity_opt()).sum();
            let avg_complexity = if method_count > 0 { total_complexity as f64 / method_count as f64 } else { 0.0 };
            let mut delegating_count = 0;
            let mut external_deps: HashSet<String> = HashSet::new();
            for method in &methods {
                if let Some(callees) = call_map.get(method.qn(i)) {
                    let ext: Vec<_> = callees.iter().filter(|c| !methods.iter().any(|m| m.qn(i) == **c)).collect();
                    if !ext.is_empty() {
                        delegating_count += 1;
                        for e in ext { if let Some(m) = e.rsplit("::").nth(1) { external_deps.insert(m.to_string()); } }
                    }
                }
            }
            let delegation_ratio = if method_count > 0 { delegating_count as f64 / method_count as f64 } else { 0.0 };
            let public_methods = methods.iter().filter(|m| !m.node_name(i).starts_with('_')).count();
            let usages = *class_usages.get(qn).unwrap_or(&0);
            let is_test = self.is_test_path(class.path(i));
            let is_framework_path = self.is_framework_path(class.path(i));
            let (role, role_reason) = self.infer_role(
                class.node_name(i), class.path(i), method_count, avg_complexity,
                delegation_ratio, external_deps.len(), usages, is_test, is_framework_path,
            );
            contexts.insert(qn.to_string(), ClassContext {
                qualified_name: qn.to_string(),
                name: class.node_name(i).to_string(),
                file_path: class.path(i).to_string(),
                method_count,
                loc: class.loc() as usize,
                complexity: total_complexity as usize,
                avg_method_complexity: avg_complexity,
                delegating_methods: delegating_count,
                delegation_ratio,
                public_methods,
                external_dependencies: external_deps.len(),
                usages,
                role,
                is_test,
                is_framework_path,
                role_reason,
            });
        }

        let elapsed = start.elapsed();
        info!("Built class context (legacy) in {:?}", elapsed);
        contexts
    }

    /// Infer class role from metrics
    fn infer_role(
        &self,
        name: &str,
        file_path: &str,
        method_count: usize,
        avg_complexity: f64,
        delegation_ratio: f64,
        external_dependencies: usize,
        usages: usize,
        _is_test: bool,
        is_framework_path: bool,
    ) -> (ClassRole, String) {
        // Framework core: known names or patterns
        if FRAMEWORK_CORE_NAMES.contains(&name) {
            return (
                ClassRole::FrameworkCore,
                format!("Known framework class: {}", name),
            );
        }

        if FRAMEWORK_PATTERNS.iter().any(|p| name.contains(p)) {
            return (
                ClassRole::FrameworkCore,
                format!("Framework pattern in name: {}", name),
            );
        }

        // Framework path check
        if is_framework_path {
            return (
                ClassRole::FrameworkCore,
                "In framework/vendor path".to_string(),
            );
        }

        // Orchestrator: name-based detection (controllers, routers, handlers, dispatchers)
        if let Some(pattern) = ORCHESTRATOR_NAME_PATTERNS
            .iter()
            .find(|p| name.contains(**p))
        {
            return (
                ClassRole::Orchestrator,
                format!(
                    "Orchestrator pattern '{}' in name: {} ({} methods, {:.0}% delegate, {} external deps)",
                    pattern, name, method_count, delegation_ratio * 100.0, external_dependencies
                ),
            );
        }

        // Check framework core suffixes (after orchestrator name check to avoid conflicts)
        if FRAMEWORK_CORE_SUFFIXES.iter().any(|s| name.ends_with(s)) {
            return (
                ClassRole::FrameworkCore,
                "Name ends with framework suffix".to_string(),
            );
        }

        // Orchestrator: path-based detection
        let path_lower = file_path.to_lowercase();
        if let Some(pattern) = ORCHESTRATOR_PATH_PATTERNS
            .iter()
            .find(|p| path_lower.contains(**p))
        {
            return (
                ClassRole::Orchestrator,
                format!(
                    "In orchestrator path '{}': {} ({} methods, {:.0}% delegate)",
                    pattern, name, method_count, delegation_ratio * 100.0
                ),
            );
        }

        // Orchestrator: metric-based detection
        // High delegation + many external deps + low complexity = orchestrator
        if method_count >= 5
            && delegation_ratio >= 0.6
            && external_dependencies >= 4
            && avg_complexity <= self.thin_wrapper_complexity
        {
            return (
                ClassRole::Orchestrator,
                format!(
                    "Orchestrator pattern (metrics): {} methods, avg complexity {:.1}, {:.0}% delegate, {} external deps",
                    method_count, avg_complexity, delegation_ratio * 100.0, external_dependencies
                ),
            );
        }

        // Facade: large API surface + thin methods + high delegation
        if method_count >= 10
            && avg_complexity <= self.thin_wrapper_complexity
            && delegation_ratio >= self.facade_delegation_ratio
        {
            return (
                ClassRole::Facade,
                format!(
                    "Facade pattern: {} methods, avg complexity {:.1}, {:.0}% delegate",
                    method_count,
                    avg_complexity,
                    delegation_ratio * 100.0
                ),
            );
        }

        // Entry point: heavily used, many public methods
        if usages >= 5 && method_count >= 10 {
            return (
                ClassRole::EntryPoint,
                format!("Entry point: used by {} other classes", usages),
            );
        }

        // Data class: mostly properties/getters, low complexity
        if avg_complexity <= 1.5 && method_count <= 20 {
            return (
                ClassRole::DataClass,
                format!("Data class: avg complexity {:.1}", avg_complexity),
            );
        }

        // Utility: low method count, high reuse
        if method_count <= 15 && usages >= 3 {
            return (
                ClassRole::Utility,
                format!(
                    "Utility class: {} methods, used by {} others",
                    method_count, usages
                ),
            );
        }

        (
            ClassRole::Application,
            "Standard application class".to_string(),
        )
    }

    /// Check if path is a test file
    fn is_test_path(&self, path: &str) -> bool {
        let lower = path.to_lowercase();
        lower.contains("/test/")
            || lower.contains("/tests/")
            || lower.contains("/__tests__/")
            || lower.contains("/spec/")
            || lower.ends_with("_test.go")
            || lower.ends_with("_test.py")
            || lower.ends_with(".test.ts")
            || lower.ends_with(".test.js")
            || lower.ends_with(".spec.ts")
            || lower.ends_with(".spec.js")
            // Handle relative paths starting with test directories
            || lower.starts_with("tests/")
            || lower.starts_with("test/")
            || lower.starts_with("__tests__/")
            || lower.starts_with("spec/")
    }

    /// Check if path is in a framework/vendor directory
    fn is_framework_path(&self, path: &str) -> bool {
        let lower = path.to_lowercase();
        lower.contains("/node_modules/")
            || lower.contains("/site-packages/")
            || lower.contains("/vendor/")
            || lower.contains("/.venv/")
            || lower.contains("/venv/")
            || lower.contains("/dist-packages/")
    }
}

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

    #[test]
    fn test_framework_core_detection() {
        let store = crate::graph::GraphBuilder::new().freeze();
        let builder = ClassContextBuilder::new(&store);

        let (role, _) = builder.infer_role("Flask", "src/app.py", 50, 5.0, 0.8, 3, 10, false, false);
        assert_eq!(role, ClassRole::FrameworkCore);

        let (role, _) = builder.infer_role("MyApplication", "src/app.py", 30, 3.0, 0.5, 2, 5, false, false);
        assert_eq!(role, ClassRole::FrameworkCore);
    }

    #[test]
    fn test_facade_detection() {
        let store = crate::graph::GraphBuilder::new().freeze();
        let builder = ClassContextBuilder::new(&store);

        // High method count, low complexity, high delegation
        // Note: name must not match orchestrator patterns, and ext deps < 4 to avoid orchestrator metric match
        let (role, _) = builder.infer_role("ApiClient", "src/client.py", 20, 2.0, 0.7, 3, 2, false, false);
        assert_eq!(role, ClassRole::Facade);
    }

    #[test]
    fn test_data_class_detection() {
        let store = crate::graph::GraphBuilder::new().freeze();
        let builder = ClassContextBuilder::new(&store);

        let (role, _) = builder.infer_role("UserDTO", "src/models.py", 10, 1.0, 0.1, 0, 2, false, false);
        assert_eq!(role, ClassRole::DataClass);
    }

    #[test]
    fn test_orchestrator_detection_by_name() {
        let store = crate::graph::GraphBuilder::new().freeze();
        let builder = ClassContextBuilder::new(&store);

        // Controller suffix
        let (role, reason) = builder.infer_role("UserController", "src/api.py", 15, 2.0, 0.8, 5, 3, false, false);
        assert_eq!(role, ClassRole::Orchestrator, "Controller should be Orchestrator: {}", reason);

        // Handler suffix
        let (role, _) = builder.infer_role("RequestHandler", "src/server.py", 10, 1.5, 0.7, 3, 2, false, false);
        assert_eq!(role, ClassRole::Orchestrator);

        // Dispatcher suffix
        let (role, _) = builder.infer_role("EventDispatcher", "src/events.py", 8, 2.0, 0.6, 4, 1, false, false);
        assert_eq!(role, ClassRole::Orchestrator);

        // Orchestrator suffix
        let (role, _) = builder.infer_role("WorkflowOrchestrator", "src/workflows.py", 12, 1.0, 0.9, 6, 2, false, false);
        assert_eq!(role, ClassRole::Orchestrator);
    }

    #[test]
    fn test_orchestrator_detection_by_path() {
        let store = crate::graph::GraphBuilder::new().freeze();
        let builder = ClassContextBuilder::new(&store);

        // File in controllers/ directory
        let (role, _) = builder.infer_role("Users", "src/controllers/users.py", 10, 2.0, 0.5, 3, 2, false, false);
        assert_eq!(role, ClassRole::Orchestrator);

        // File in handlers/ directory
        let (role, _) = builder.infer_role("Auth", "src/handlers/auth.ts", 8, 1.5, 0.4, 2, 1, false, false);
        assert_eq!(role, ClassRole::Orchestrator);
    }

    #[test]
    fn test_orchestrator_detection_by_metrics() {
        let store = crate::graph::GraphBuilder::new().freeze();
        let builder = ClassContextBuilder::new(&store);

        // High delegation + many external deps + low complexity = orchestrator
        // Name and path are generic (not matching name/path patterns)
        let (role, reason) = builder.infer_role(
            "OrderService", "src/services/orders.py",
            8, 2.0, 0.7, 5, 2, false, false,
        );
        assert_eq!(role, ClassRole::Orchestrator, "Metric-based orchestrator: {}", reason);
    }

    #[test]
    fn test_orchestrator_not_triggered_for_low_delegation() {
        let store = crate::graph::GraphBuilder::new().freeze();
        let builder = ClassContextBuilder::new(&store);

        // Low delegation + few external deps = NOT orchestrator (should be data class)
        let (role, _) = builder.infer_role(
            "OrderService", "src/services/orders.py",
            8, 1.0, 0.2, 1, 2, false, false,
        );
        assert_ne!(role, ClassRole::Orchestrator);
    }

    #[test]
    fn test_orchestrator_severity_multiplier() {
        assert_eq!(ClassRole::Orchestrator.severity_multiplier(), 0.3);
    }

    #[test]
    fn test_orchestrator_allows_large_size() {
        assert!(ClassRole::Orchestrator.allows_large_size());
    }

    #[test]
    fn test_role_severity_multipliers() {
        assert_eq!(ClassRole::FrameworkCore.severity_multiplier(), 0.0);
        assert_eq!(ClassRole::Facade.severity_multiplier(), 0.3);
        assert_eq!(ClassRole::Orchestrator.severity_multiplier(), 0.3);
        assert_eq!(ClassRole::Application.severity_multiplier(), 1.0);
    }
}