cargo_coupling/
metrics.rs

1//! Coupling metrics data structures
2//!
3//! This module defines the core data structures for measuring coupling
4//! based on Vlad Khononov's "Balancing Coupling in Software Design".
5
6use std::collections::{HashMap, HashSet};
7use std::fmt;
8use std::path::PathBuf;
9
10use crate::analyzer::ItemDependency;
11
12/// Visibility level of a Rust item
13///
14/// This is used to determine if access to an item from another module
15/// constitutes "Intrusive" coupling (access to private/internal details).
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
17pub enum Visibility {
18    /// Fully public (`pub`)
19    Public,
20    /// Crate-internal (`pub(crate)`)
21    PubCrate,
22    /// Super-module visible (`pub(super)`)
23    PubSuper,
24    /// Module-path restricted (`pub(in path)`)
25    PubIn,
26    /// Private (no visibility modifier)
27    #[default]
28    Private,
29}
30
31impl Visibility {
32    /// Check if this visibility allows access from a different module
33    pub fn allows_external_access(&self) -> bool {
34        matches!(self, Visibility::Public | Visibility::PubCrate)
35    }
36
37    /// Check if access from another module would be "intrusive"
38    ///
39    /// Intrusive access means accessing something that isn't part of the public API.
40    /// This indicates tight coupling to implementation details.
41    pub fn is_intrusive_from(&self, same_crate: bool, same_module: bool) -> bool {
42        if same_module {
43            // Same module access is never intrusive
44            return false;
45        }
46
47        match self {
48            Visibility::Public => false,         // Public API, not intrusive
49            Visibility::PubCrate => !same_crate, // Intrusive if from different crate
50            Visibility::PubSuper | Visibility::PubIn => true, // Limited visibility, intrusive from outside
51            Visibility::Private => true, // Private, always intrusive from outside
52        }
53    }
54
55    /// Get a penalty multiplier for coupling strength based on visibility
56    ///
57    /// Higher penalty = more "intrusive" the access is.
58    pub fn intrusive_penalty(&self) -> f64 {
59        match self {
60            Visibility::Public => 0.0,    // No penalty for public API
61            Visibility::PubCrate => 0.25, // Small penalty for crate-internal
62            Visibility::PubSuper => 0.5,  // Medium penalty
63            Visibility::PubIn => 0.5,     // Medium penalty
64            Visibility::Private => 1.0,   // Full penalty for private access
65        }
66    }
67}
68
69impl fmt::Display for Visibility {
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        match self {
72            Visibility::Public => write!(f, "pub"),
73            Visibility::PubCrate => write!(f, "pub(crate)"),
74            Visibility::PubSuper => write!(f, "pub(super)"),
75            Visibility::PubIn => write!(f, "pub(in ...)"),
76            Visibility::Private => write!(f, "private"),
77        }
78    }
79}
80
81/// Integration strength levels (how much knowledge is shared)
82#[derive(Debug, Clone, Copy, PartialEq)]
83pub enum IntegrationStrength {
84    /// Strongest coupling - direct access to internals
85    Intrusive,
86    /// Strong coupling - depends on function signatures
87    Functional,
88    /// Medium coupling - depends on data models
89    Model,
90    /// Weakest coupling - depends only on contracts/traits
91    Contract,
92}
93
94impl IntegrationStrength {
95    /// Returns the numeric value (0.0 - 1.0, higher = stronger)
96    pub fn value(&self) -> f64 {
97        match self {
98            IntegrationStrength::Intrusive => 1.0,
99            IntegrationStrength::Functional => 0.75,
100            IntegrationStrength::Model => 0.5,
101            IntegrationStrength::Contract => 0.25,
102        }
103    }
104}
105
106/// Distance levels (how far apart components are)
107#[derive(Debug, Clone, Copy, PartialEq)]
108pub enum Distance {
109    /// Same function/block
110    SameFunction,
111    /// Same module/file
112    SameModule,
113    /// Different module in same crate
114    DifferentModule,
115    /// Different crate
116    DifferentCrate,
117}
118
119impl Distance {
120    /// Returns the numeric value (0.0 - 1.0, higher = farther)
121    pub fn value(&self) -> f64 {
122        match self {
123            Distance::SameFunction => 0.0,
124            Distance::SameModule => 0.25,
125            Distance::DifferentModule => 0.5,
126            Distance::DifferentCrate => 1.0,
127        }
128    }
129}
130
131/// Volatility levels (how often a component changes)
132#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
133pub enum Volatility {
134    /// Rarely changes (0-2 times)
135    Low,
136    /// Sometimes changes (3-10 times)
137    Medium,
138    /// Frequently changes (11+ times)
139    High,
140}
141
142impl Volatility {
143    /// Returns the numeric value (0.0 - 1.0, higher = more volatile)
144    pub fn value(&self) -> f64 {
145        match self {
146            Volatility::Low => 0.0,
147            Volatility::Medium => 0.5,
148            Volatility::High => 1.0,
149        }
150    }
151
152    /// Classify from change count
153    pub fn from_count(count: usize) -> Self {
154        match count {
155            0..=2 => Volatility::Low,
156            3..=10 => Volatility::Medium,
157            _ => Volatility::High,
158        }
159    }
160}
161
162/// Location information for a coupling
163#[derive(Debug, Clone, Default)]
164pub struct CouplingLocation {
165    /// File path where the coupling originates
166    pub file_path: Option<PathBuf>,
167    /// Line number in the source file
168    pub line: usize,
169}
170
171/// Metrics for a single coupling relationship
172#[derive(Debug, Clone)]
173pub struct CouplingMetrics {
174    /// Source component
175    pub source: String,
176    /// Target component
177    pub target: String,
178    /// Integration strength
179    pub strength: IntegrationStrength,
180    /// Distance between components
181    pub distance: Distance,
182    /// Volatility of the target
183    pub volatility: Volatility,
184    /// Source crate name (when workspace analysis is available)
185    pub source_crate: Option<String>,
186    /// Target crate name (when workspace analysis is available)
187    pub target_crate: Option<String>,
188    /// Visibility of the target item (for intrusive detection)
189    pub target_visibility: Visibility,
190    /// Location where the coupling occurs
191    pub location: CouplingLocation,
192}
193
194impl CouplingMetrics {
195    /// Create new coupling metrics
196    pub fn new(
197        source: String,
198        target: String,
199        strength: IntegrationStrength,
200        distance: Distance,
201        volatility: Volatility,
202    ) -> Self {
203        Self {
204            source,
205            target,
206            strength,
207            distance,
208            volatility,
209            source_crate: None,
210            target_crate: None,
211            target_visibility: Visibility::default(),
212            location: CouplingLocation::default(),
213        }
214    }
215
216    /// Create new coupling metrics with visibility
217    pub fn with_visibility(
218        source: String,
219        target: String,
220        strength: IntegrationStrength,
221        distance: Distance,
222        volatility: Volatility,
223        visibility: Visibility,
224    ) -> Self {
225        Self {
226            source,
227            target,
228            strength,
229            distance,
230            volatility,
231            source_crate: None,
232            target_crate: None,
233            target_visibility: visibility,
234            location: CouplingLocation::default(),
235        }
236    }
237
238    /// Create new coupling metrics with location
239    #[allow(clippy::too_many_arguments)]
240    pub fn with_location(
241        source: String,
242        target: String,
243        strength: IntegrationStrength,
244        distance: Distance,
245        volatility: Volatility,
246        visibility: Visibility,
247        file_path: PathBuf,
248        line: usize,
249    ) -> Self {
250        Self {
251            source,
252            target,
253            strength,
254            distance,
255            volatility,
256            source_crate: None,
257            target_crate: None,
258            target_visibility: visibility,
259            location: CouplingLocation {
260                file_path: Some(file_path),
261                line,
262            },
263        }
264    }
265
266    /// Check if this coupling represents intrusive access based on visibility
267    ///
268    /// Returns true if the target's visibility suggests this is access to
269    /// internal implementation details rather than a public API.
270    pub fn is_visibility_intrusive(&self) -> bool {
271        let same_crate = self.source_crate == self.target_crate;
272        let same_module =
273            self.distance == Distance::SameModule || self.distance == Distance::SameFunction;
274        self.target_visibility
275            .is_intrusive_from(same_crate, same_module)
276    }
277
278    /// Get effective strength considering visibility
279    ///
280    /// If the target is not publicly visible and being accessed from outside,
281    /// the coupling is considered more intrusive.
282    pub fn effective_strength(&self) -> IntegrationStrength {
283        if self.is_visibility_intrusive() && self.strength != IntegrationStrength::Intrusive {
284            // Upgrade to more intrusive if accessing non-public items
285            match self.strength {
286                IntegrationStrength::Contract => IntegrationStrength::Model,
287                IntegrationStrength::Model => IntegrationStrength::Functional,
288                IntegrationStrength::Functional => IntegrationStrength::Intrusive,
289                IntegrationStrength::Intrusive => IntegrationStrength::Intrusive,
290            }
291        } else {
292            self.strength
293        }
294    }
295
296    /// Get effective strength value considering visibility
297    pub fn effective_strength_value(&self) -> f64 {
298        self.effective_strength().value()
299    }
300
301    /// Get numeric strength value
302    pub fn strength_value(&self) -> f64 {
303        self.strength.value()
304    }
305
306    /// Get numeric distance value
307    pub fn distance_value(&self) -> f64 {
308        self.distance.value()
309    }
310
311    /// Get numeric volatility value
312    pub fn volatility_value(&self) -> f64 {
313        self.volatility.value()
314    }
315}
316
317/// Information about a type definition in a module
318#[derive(Debug, Clone)]
319pub struct TypeDefinition {
320    /// Name of the type
321    pub name: String,
322    /// Visibility of the type
323    pub visibility: Visibility,
324    /// Whether this is a trait (vs struct/enum)
325    pub is_trait: bool,
326    /// Whether this is a newtype pattern (tuple struct with single field)
327    pub is_newtype: bool,
328    /// Inner type for newtypes (e.g., "u64" for `struct UserId(u64)`)
329    pub inner_type: Option<String>,
330    /// Whether this type has #[derive(Serialize)] or #[derive(Deserialize)]
331    pub has_serde_derive: bool,
332    /// Number of public fields (for pub field exposure detection)
333    pub public_field_count: usize,
334    /// Total number of fields
335    pub total_field_count: usize,
336}
337
338/// Information about a function definition in a module
339#[derive(Debug, Clone)]
340pub struct FunctionDefinition {
341    /// Name of the function
342    pub name: String,
343    /// Visibility of the function
344    pub visibility: Visibility,
345    /// Number of parameters
346    pub param_count: usize,
347    /// Number of primitive type parameters (String, u32, bool, etc.)
348    pub primitive_param_count: usize,
349    /// Parameter types (for primitive obsession detection)
350    pub param_types: Vec<String>,
351}
352
353/// Khononov's balance classification for couplings
354#[derive(Debug, Clone, Copy, PartialEq, Eq)]
355pub enum BalanceClassification {
356    /// High strength + Low distance = High cohesion (ideal)
357    HighCohesion,
358    /// Low strength + High distance = Loose coupling (ideal)
359    LooseCoupling,
360    /// High strength + High distance + Low volatility = Acceptable
361    Acceptable,
362    /// High strength + High distance + High volatility = Pain (needs refactoring)
363    Pain,
364    /// Low strength + Low distance = Local complexity (review needed)
365    LocalComplexity,
366}
367
368impl BalanceClassification {
369    /// Classify a coupling based on Khononov's formula
370    pub fn classify(
371        strength: IntegrationStrength,
372        distance: Distance,
373        volatility: Volatility,
374    ) -> Self {
375        let is_strong = strength.value() >= 0.5;
376        let is_far = distance.value() >= 0.5;
377        let is_volatile = volatility == Volatility::High;
378
379        match (is_strong, is_far, is_volatile) {
380            (true, false, _) => BalanceClassification::HighCohesion,
381            (false, true, _) => BalanceClassification::LooseCoupling,
382            (false, false, _) => BalanceClassification::LocalComplexity,
383            (true, true, false) => BalanceClassification::Acceptable,
384            (true, true, true) => BalanceClassification::Pain,
385        }
386    }
387
388    /// Get Japanese description
389    pub fn description_ja(&self) -> &'static str {
390        match self {
391            BalanceClassification::HighCohesion => "高凝集 (強+近)",
392            BalanceClassification::LooseCoupling => "疎結合 (弱+遠)",
393            BalanceClassification::Acceptable => "許容可能 (強+遠+安定)",
394            BalanceClassification::Pain => "要改善 (強+遠+変動)",
395            BalanceClassification::LocalComplexity => "局所複雑性 (弱+近)",
396        }
397    }
398
399    /// Get English description
400    pub fn description_en(&self) -> &'static str {
401        match self {
402            BalanceClassification::HighCohesion => "High Cohesion",
403            BalanceClassification::LooseCoupling => "Loose Coupling",
404            BalanceClassification::Acceptable => "Acceptable",
405            BalanceClassification::Pain => "Needs Refactoring",
406            BalanceClassification::LocalComplexity => "Local Complexity",
407        }
408    }
409
410    /// Is this classification ideal?
411    pub fn is_ideal(&self) -> bool {
412        matches!(
413            self,
414            BalanceClassification::HighCohesion | BalanceClassification::LooseCoupling
415        )
416    }
417
418    /// Does this need attention?
419    pub fn needs_attention(&self) -> bool {
420        matches!(
421            self,
422            BalanceClassification::Pain | BalanceClassification::LocalComplexity
423        )
424    }
425}
426
427/// Statistics for 3-dimensional coupling analysis
428#[derive(Debug, Clone, Default)]
429pub struct DimensionStats {
430    /// Strength distribution
431    pub strength_counts: StrengthCounts,
432    /// Distance distribution
433    pub distance_counts: DistanceCounts,
434    /// Volatility distribution
435    pub volatility_counts: VolatilityCounts,
436    /// Balance classification counts
437    pub balance_counts: BalanceCounts,
438}
439
440impl DimensionStats {
441    /// Total number of couplings analyzed
442    pub fn total(&self) -> usize {
443        self.strength_counts.total()
444    }
445
446    /// Get percentage of each strength level
447    pub fn strength_percentages(&self) -> (f64, f64, f64, f64) {
448        let total = self.total() as f64;
449        if total == 0.0 {
450            return (0.0, 0.0, 0.0, 0.0);
451        }
452        (
453            self.strength_counts.intrusive as f64 / total * 100.0,
454            self.strength_counts.functional as f64 / total * 100.0,
455            self.strength_counts.model as f64 / total * 100.0,
456            self.strength_counts.contract as f64 / total * 100.0,
457        )
458    }
459
460    /// Get percentage of each distance level
461    pub fn distance_percentages(&self) -> (f64, f64, f64) {
462        let total = self.total() as f64;
463        if total == 0.0 {
464            return (0.0, 0.0, 0.0);
465        }
466        (
467            self.distance_counts.same_module as f64 / total * 100.0,
468            self.distance_counts.different_module as f64 / total * 100.0,
469            self.distance_counts.different_crate as f64 / total * 100.0,
470        )
471    }
472
473    /// Get percentage of each volatility level
474    pub fn volatility_percentages(&self) -> (f64, f64, f64) {
475        let total = self.total() as f64;
476        if total == 0.0 {
477            return (0.0, 0.0, 0.0);
478        }
479        (
480            self.volatility_counts.low as f64 / total * 100.0,
481            self.volatility_counts.medium as f64 / total * 100.0,
482            self.volatility_counts.high as f64 / total * 100.0,
483        )
484    }
485
486    /// Count of ideal couplings (High Cohesion + Loose Coupling)
487    pub fn ideal_count(&self) -> usize {
488        self.balance_counts.high_cohesion + self.balance_counts.loose_coupling
489    }
490
491    /// Count of problematic couplings (Pain + Local Complexity)
492    pub fn problematic_count(&self) -> usize {
493        self.balance_counts.pain + self.balance_counts.local_complexity
494    }
495
496    /// Percentage of ideal couplings
497    pub fn ideal_percentage(&self) -> f64 {
498        let total = self.total() as f64;
499        if total == 0.0 {
500            return 0.0;
501        }
502        self.ideal_count() as f64 / total * 100.0
503    }
504}
505
506/// Counts for each strength level
507#[derive(Debug, Clone, Default)]
508pub struct StrengthCounts {
509    pub intrusive: usize,
510    pub functional: usize,
511    pub model: usize,
512    pub contract: usize,
513}
514
515impl StrengthCounts {
516    /// Total count across all strength levels
517    pub fn total(&self) -> usize {
518        self.intrusive + self.functional + self.model + self.contract
519    }
520}
521
522/// Counts for each distance level
523#[derive(Debug, Clone, Default)]
524pub struct DistanceCounts {
525    pub same_module: usize,
526    pub different_module: usize,
527    pub different_crate: usize,
528}
529
530/// Counts for each volatility level
531#[derive(Debug, Clone, Default)]
532pub struct VolatilityCounts {
533    pub low: usize,
534    pub medium: usize,
535    pub high: usize,
536}
537
538/// Counts for each balance classification
539#[derive(Debug, Clone, Default)]
540pub struct BalanceCounts {
541    pub high_cohesion: usize,
542    pub loose_coupling: usize,
543    pub acceptable: usize,
544    pub pain: usize,
545    pub local_complexity: usize,
546}
547
548/// Aggregated metrics for a module
549#[derive(Debug, Clone, Default)]
550pub struct ModuleMetrics {
551    /// Module path
552    pub path: PathBuf,
553    /// Module name
554    pub name: String,
555    /// Number of trait implementations (contract coupling)
556    pub trait_impl_count: usize,
557    /// Number of inherent implementations (intrusive coupling)
558    pub inherent_impl_count: usize,
559    /// Number of function calls
560    pub function_call_count: usize,
561    /// Number of struct/enum usages
562    pub type_usage_count: usize,
563    /// External crate dependencies
564    pub external_deps: Vec<String>,
565    /// Internal module dependencies
566    pub internal_deps: Vec<String>,
567    /// Type definitions in this module with visibility info
568    pub type_definitions: HashMap<String, TypeDefinition>,
569    /// Function definitions in this module with visibility info
570    pub function_definitions: HashMap<String, FunctionDefinition>,
571    /// Item-level dependencies (function → function, function → type, etc.)
572    pub item_dependencies: Vec<ItemDependency>,
573}
574
575impl ModuleMetrics {
576    pub fn new(path: PathBuf, name: String) -> Self {
577        Self {
578            path,
579            name,
580            ..Default::default()
581        }
582    }
583
584    /// Add a type definition to this module (simple version for backward compatibility)
585    pub fn add_type_definition(&mut self, name: String, visibility: Visibility, is_trait: bool) {
586        self.type_definitions.insert(
587            name.clone(),
588            TypeDefinition {
589                name,
590                visibility,
591                is_trait,
592                is_newtype: false,
593                inner_type: None,
594                has_serde_derive: false,
595                public_field_count: 0,
596                total_field_count: 0,
597            },
598        );
599    }
600
601    /// Add a type definition with full details
602    #[allow(clippy::too_many_arguments)]
603    pub fn add_type_definition_full(
604        &mut self,
605        name: String,
606        visibility: Visibility,
607        is_trait: bool,
608        is_newtype: bool,
609        inner_type: Option<String>,
610        has_serde_derive: bool,
611        public_field_count: usize,
612        total_field_count: usize,
613    ) {
614        self.type_definitions.insert(
615            name.clone(),
616            TypeDefinition {
617                name,
618                visibility,
619                is_trait,
620                is_newtype,
621                inner_type,
622                has_serde_derive,
623                public_field_count,
624                total_field_count,
625            },
626        );
627    }
628
629    /// Add a function definition to this module (simple version for backward compatibility)
630    pub fn add_function_definition(&mut self, name: String, visibility: Visibility) {
631        self.function_definitions.insert(
632            name.clone(),
633            FunctionDefinition {
634                name,
635                visibility,
636                param_count: 0,
637                primitive_param_count: 0,
638                param_types: Vec::new(),
639            },
640        );
641    }
642
643    /// Add a function definition with full details
644    pub fn add_function_definition_full(
645        &mut self,
646        name: String,
647        visibility: Visibility,
648        param_count: usize,
649        primitive_param_count: usize,
650        param_types: Vec<String>,
651    ) {
652        self.function_definitions.insert(
653            name.clone(),
654            FunctionDefinition {
655                name,
656                visibility,
657                param_count,
658                primitive_param_count,
659                param_types,
660            },
661        );
662    }
663
664    /// Get visibility of a type defined in this module
665    pub fn get_type_visibility(&self, name: &str) -> Option<Visibility> {
666        self.type_definitions.get(name).map(|t| t.visibility)
667    }
668
669    /// Count public types
670    pub fn public_type_count(&self) -> usize {
671        self.type_definitions
672            .values()
673            .filter(|t| t.visibility == Visibility::Public)
674            .count()
675    }
676
677    /// Count non-public types
678    pub fn private_type_count(&self) -> usize {
679        self.type_definitions
680            .values()
681            .filter(|t| t.visibility != Visibility::Public)
682            .count()
683    }
684
685    /// Calculate average integration strength
686    pub fn average_strength(&self) -> f64 {
687        let total = self.trait_impl_count + self.inherent_impl_count;
688        if total == 0 {
689            return 0.0;
690        }
691
692        let contract_weight = self.trait_impl_count as f64 * IntegrationStrength::Contract.value();
693        let intrusive_weight =
694            self.inherent_impl_count as f64 * IntegrationStrength::Intrusive.value();
695
696        (contract_weight + intrusive_weight) / total as f64
697    }
698
699    /// Count newtypes in this module
700    pub fn newtype_count(&self) -> usize {
701        self.type_definitions
702            .values()
703            .filter(|t| t.is_newtype)
704            .count()
705    }
706
707    /// Count types with serde derives
708    pub fn serde_type_count(&self) -> usize {
709        self.type_definitions
710            .values()
711            .filter(|t| t.has_serde_derive)
712            .count()
713    }
714
715    /// Calculate newtype usage ratio (newtypes / total non-trait types)
716    pub fn newtype_ratio(&self) -> f64 {
717        let non_trait_types = self
718            .type_definitions
719            .values()
720            .filter(|t| !t.is_trait)
721            .count();
722        if non_trait_types == 0 {
723            return 0.0;
724        }
725        self.newtype_count() as f64 / non_trait_types as f64
726    }
727
728    /// Count types with public fields
729    pub fn types_with_public_fields(&self) -> usize {
730        self.type_definitions
731            .values()
732            .filter(|t| t.public_field_count > 0)
733            .count()
734    }
735
736    /// Total function count
737    pub fn function_count(&self) -> usize {
738        self.function_definitions.len()
739    }
740
741    /// Count functions with high primitive parameter ratio
742    /// (potential Primitive Obsession)
743    pub fn functions_with_primitive_obsession(&self) -> Vec<&FunctionDefinition> {
744        self.function_definitions
745            .values()
746            .filter(|f| {
747                f.param_count >= 3 && f.primitive_param_count as f64 / f.param_count as f64 >= 0.6
748            })
749            .collect()
750    }
751
752    /// Check if this module is a potential "God Module"
753    /// (too many functions, types, or implementations)
754    pub fn is_god_module(&self, max_functions: usize, max_types: usize, max_impls: usize) -> bool {
755        self.function_count() > max_functions
756            || self.type_definitions.len() > max_types
757            || (self.trait_impl_count + self.inherent_impl_count) > max_impls
758    }
759}
760
761/// Project-wide analysis results
762#[derive(Debug, Default)]
763pub struct ProjectMetrics {
764    /// All module metrics
765    pub modules: HashMap<String, ModuleMetrics>,
766    /// All detected couplings
767    pub couplings: Vec<CouplingMetrics>,
768    /// File change counts (for volatility)
769    pub file_changes: HashMap<String, usize>,
770    /// Total files analyzed
771    pub total_files: usize,
772    /// Workspace name (if available from cargo metadata)
773    pub workspace_name: Option<String>,
774    /// Workspace member crate names
775    pub workspace_members: Vec<String>,
776    /// Crate-level dependencies (crate name -> list of dependencies)
777    pub crate_dependencies: HashMap<String, Vec<String>>,
778    /// Global type registry: type name -> (module name, visibility)
779    pub type_registry: HashMap<String, (String, Visibility)>,
780}
781
782impl ProjectMetrics {
783    pub fn new() -> Self {
784        Self::default()
785    }
786
787    /// Add module metrics
788    pub fn add_module(&mut self, metrics: ModuleMetrics) {
789        self.modules.insert(metrics.name.clone(), metrics);
790    }
791
792    /// Add coupling
793    pub fn add_coupling(&mut self, coupling: CouplingMetrics) {
794        self.couplings.push(coupling);
795    }
796
797    /// Register a type definition in the global registry
798    pub fn register_type(
799        &mut self,
800        type_name: String,
801        module_name: String,
802        visibility: Visibility,
803    ) {
804        self.type_registry
805            .insert(type_name, (module_name, visibility));
806    }
807
808    /// Look up visibility of a type by name
809    pub fn get_type_visibility(&self, type_name: &str) -> Option<Visibility> {
810        self.type_registry.get(type_name).map(|(_, vis)| *vis)
811    }
812
813    /// Look up the module where a type is defined
814    pub fn get_type_module(&self, type_name: &str) -> Option<&str> {
815        self.type_registry
816            .get(type_name)
817            .map(|(module, _)| module.as_str())
818    }
819
820    /// Update visibility information for existing couplings
821    ///
822    /// This should be called after all modules have been analyzed
823    /// to populate the target_visibility field of couplings.
824    pub fn update_coupling_visibility(&mut self) {
825        // First collect all the visibility lookups
826        let visibility_updates: Vec<(usize, Visibility)> = self
827            .couplings
828            .iter()
829            .enumerate()
830            .filter_map(|(idx, coupling)| {
831                let target_type = coupling
832                    .target
833                    .split("::")
834                    .last()
835                    .unwrap_or(&coupling.target);
836                self.type_registry
837                    .get(target_type)
838                    .map(|(_, vis)| (idx, *vis))
839            })
840            .collect();
841
842        // Then apply the updates
843        for (idx, visibility) in visibility_updates {
844            self.couplings[idx].target_visibility = visibility;
845        }
846    }
847
848    /// Get total module count
849    pub fn module_count(&self) -> usize {
850        self.modules.len()
851    }
852
853    /// Get total coupling count
854    pub fn coupling_count(&self) -> usize {
855        self.couplings.len()
856    }
857
858    /// Get internal coupling count (excludes external crate dependencies)
859    pub fn internal_coupling_count(&self) -> usize {
860        self.couplings
861            .iter()
862            .filter(|c| !crate::balance::is_external_crate(&c.target, &c.source))
863            .count()
864    }
865
866    /// Calculate average strength across all couplings
867    pub fn average_strength(&self) -> Option<f64> {
868        if self.couplings.is_empty() {
869            return None;
870        }
871        let sum: f64 = self.couplings.iter().map(|c| c.strength_value()).sum();
872        Some(sum / self.couplings.len() as f64)
873    }
874
875    /// Calculate average distance across all couplings
876    pub fn average_distance(&self) -> Option<f64> {
877        if self.couplings.is_empty() {
878            return None;
879        }
880        let sum: f64 = self.couplings.iter().map(|c| c.distance_value()).sum();
881        Some(sum / self.couplings.len() as f64)
882    }
883
884    /// Update volatility for all couplings based on file changes
885    ///
886    /// This should be called after git history analysis to update
887    /// the volatility of each coupling based on how often the target
888    /// module/file has changed.
889    pub fn update_volatility_from_git(&mut self) {
890        if self.file_changes.is_empty() {
891            return;
892        }
893
894        // Debug: print file changes for troubleshooting
895        #[cfg(test)]
896        {
897            eprintln!("DEBUG: file_changes = {:?}", self.file_changes);
898        }
899
900        for coupling in &mut self.couplings {
901            // Try to find the target file in file_changes
902            // The target is like "crate::module" or "crate::module::Type"
903            // We need to match this against file paths like "src/module.rs"
904            //
905            // Special cases in Rust module system:
906            // - crate root "crate::crate_name" or "crate_name::crate_name" -> lib.rs
907            // - binary entry point -> main.rs
908            // - glob imports "crate::*" -> don't match specific files
909
910            // Extract all path components from target
911            let target_parts: Vec<&str> = coupling.target.split("::").collect();
912
913            // Find the best matching file
914            let mut max_changes = 0usize;
915            for (file_path, &changes) in &self.file_changes {
916                // Get file name without .rs extension (e.g., "balance" from "src/balance.rs")
917                let file_name = file_path
918                    .rsplit('/')
919                    .next()
920                    .unwrap_or(file_path)
921                    .trim_end_matches(".rs");
922
923                // Check if any target path component matches the file name
924                let matches = target_parts.iter().any(|part| {
925                    let part_lower = part.to_lowercase();
926                    let file_lower = file_name.to_lowercase();
927
928                    // Direct match: "balance" == "balance"
929                    if part_lower == file_lower {
930                        return true;
931                    }
932
933                    // Handle crate root: if the part matches the crate name and file is lib.rs
934                    // e.g., "cargo_coupling" matches "lib" (lib.rs is the crate root)
935                    if file_lower == "lib" && !part.is_empty() && *part != "*" {
936                        // This could be the crate root reference
937                        // We also match if the part is the crate name (same as first path component)
938                        if target_parts.len() >= 2 && target_parts[1] == *part {
939                            return true;
940                        }
941                    }
942
943                    // Handle underscore vs hyphen in crate names
944                    // e.g., "cargo-coupling" might appear as "cargo_coupling" in code
945                    let part_normalized = part_lower.replace('-', "_");
946                    let file_normalized = file_lower.replace('-', "_");
947                    if part_normalized == file_normalized {
948                        return true;
949                    }
950
951                    // Path contains match: "web" matches "src/web/graph.rs"
952                    if file_path.to_lowercase().contains(&part_lower) {
953                        return true;
954                    }
955
956                    false
957                });
958
959                if matches {
960                    max_changes = max_changes.max(changes);
961                }
962            }
963
964            coupling.volatility = Volatility::from_count(max_changes);
965        }
966    }
967
968    /// Build a dependency graph from couplings
969    fn build_dependency_graph(&self) -> HashMap<String, HashSet<String>> {
970        let mut graph: HashMap<String, HashSet<String>> = HashMap::new();
971
972        for coupling in &self.couplings {
973            // Only consider internal couplings (not external crates)
974            if coupling.distance == Distance::DifferentCrate {
975                continue;
976            }
977
978            // Extract module names (remove crate prefix for cleaner cycles)
979            let source = coupling.source.clone();
980            let target = coupling.target.clone();
981
982            graph.entry(source).or_default().insert(target);
983        }
984
985        graph
986    }
987
988    /// Detect circular dependencies in the project
989    ///
990    /// Returns a list of cycles, where each cycle is a list of module names
991    /// forming the circular dependency chain.
992    pub fn detect_circular_dependencies(&self) -> Vec<Vec<String>> {
993        let graph = self.build_dependency_graph();
994        let mut cycles: Vec<Vec<String>> = Vec::new();
995        let mut visited: HashSet<String> = HashSet::new();
996        let mut rec_stack: HashSet<String> = HashSet::new();
997
998        for node in graph.keys() {
999            if !visited.contains(node) {
1000                let mut path = Vec::new();
1001                self.dfs_find_cycles(
1002                    node,
1003                    &graph,
1004                    &mut visited,
1005                    &mut rec_stack,
1006                    &mut path,
1007                    &mut cycles,
1008                );
1009            }
1010        }
1011
1012        // Deduplicate cycles (same cycle can be detected from different starting points)
1013        let mut unique_cycles: Vec<Vec<String>> = Vec::new();
1014        for cycle in cycles {
1015            let normalized = Self::normalize_cycle(&cycle);
1016            if !unique_cycles
1017                .iter()
1018                .any(|c| Self::normalize_cycle(c) == normalized)
1019            {
1020                unique_cycles.push(cycle);
1021            }
1022        }
1023
1024        unique_cycles
1025    }
1026
1027    /// DFS helper for cycle detection
1028    fn dfs_find_cycles(
1029        &self,
1030        node: &str,
1031        graph: &HashMap<String, HashSet<String>>,
1032        visited: &mut HashSet<String>,
1033        rec_stack: &mut HashSet<String>,
1034        path: &mut Vec<String>,
1035        cycles: &mut Vec<Vec<String>>,
1036    ) {
1037        visited.insert(node.to_string());
1038        rec_stack.insert(node.to_string());
1039        path.push(node.to_string());
1040
1041        if let Some(neighbors) = graph.get(node) {
1042            for neighbor in neighbors {
1043                if !visited.contains(neighbor) {
1044                    self.dfs_find_cycles(neighbor, graph, visited, rec_stack, path, cycles);
1045                } else if rec_stack.contains(neighbor) {
1046                    // Found a cycle - extract the cycle from path
1047                    if let Some(start_idx) = path.iter().position(|n| n == neighbor) {
1048                        let cycle: Vec<String> = path[start_idx..].to_vec();
1049                        if cycle.len() >= 2 {
1050                            cycles.push(cycle);
1051                        }
1052                    }
1053                }
1054            }
1055        }
1056
1057        path.pop();
1058        rec_stack.remove(node);
1059    }
1060
1061    /// Normalize a cycle for deduplication
1062    /// Rotates the cycle so the lexicographically smallest element is first
1063    fn normalize_cycle(cycle: &[String]) -> Vec<String> {
1064        if cycle.is_empty() {
1065            return Vec::new();
1066        }
1067
1068        // Find the position of the minimum element
1069        let min_pos = cycle
1070            .iter()
1071            .enumerate()
1072            .min_by_key(|(_, s)| s.as_str())
1073            .map(|(i, _)| i)
1074            .unwrap_or(0);
1075
1076        // Rotate the cycle
1077        let mut normalized: Vec<String> = cycle[min_pos..].to_vec();
1078        normalized.extend_from_slice(&cycle[..min_pos]);
1079        normalized
1080    }
1081
1082    /// Get circular dependency summary
1083    pub fn circular_dependency_summary(&self) -> CircularDependencySummary {
1084        let cycles = self.detect_circular_dependencies();
1085        let affected_modules: HashSet<String> = cycles.iter().flatten().cloned().collect();
1086
1087        CircularDependencySummary {
1088            total_cycles: cycles.len(),
1089            affected_modules: affected_modules.len(),
1090            cycles,
1091        }
1092    }
1093
1094    /// Calculate 3-dimensional coupling statistics
1095    ///
1096    /// Computes distribution of couplings across Strength, Distance,
1097    /// Volatility, and Balance Classification dimensions.
1098    pub fn calculate_dimension_stats(&self) -> DimensionStats {
1099        let mut stats = DimensionStats::default();
1100
1101        for coupling in &self.couplings {
1102            // Count strength distribution
1103            match coupling.strength {
1104                IntegrationStrength::Intrusive => stats.strength_counts.intrusive += 1,
1105                IntegrationStrength::Functional => stats.strength_counts.functional += 1,
1106                IntegrationStrength::Model => stats.strength_counts.model += 1,
1107                IntegrationStrength::Contract => stats.strength_counts.contract += 1,
1108            }
1109
1110            // Count distance distribution
1111            match coupling.distance {
1112                Distance::SameFunction | Distance::SameModule => {
1113                    stats.distance_counts.same_module += 1
1114                }
1115                Distance::DifferentModule => stats.distance_counts.different_module += 1,
1116                Distance::DifferentCrate => stats.distance_counts.different_crate += 1,
1117            }
1118
1119            // Count volatility distribution
1120            match coupling.volatility {
1121                Volatility::Low => stats.volatility_counts.low += 1,
1122                Volatility::Medium => stats.volatility_counts.medium += 1,
1123                Volatility::High => stats.volatility_counts.high += 1,
1124            }
1125
1126            // Classify and count balance
1127            let classification = BalanceClassification::classify(
1128                coupling.strength,
1129                coupling.distance,
1130                coupling.volatility,
1131            );
1132            match classification {
1133                BalanceClassification::HighCohesion => stats.balance_counts.high_cohesion += 1,
1134                BalanceClassification::LooseCoupling => stats.balance_counts.loose_coupling += 1,
1135                BalanceClassification::Acceptable => stats.balance_counts.acceptable += 1,
1136                BalanceClassification::Pain => stats.balance_counts.pain += 1,
1137                BalanceClassification::LocalComplexity => {
1138                    stats.balance_counts.local_complexity += 1
1139                }
1140            }
1141        }
1142
1143        stats
1144    }
1145
1146    /// Get total newtype count across all modules
1147    pub fn total_newtype_count(&self) -> usize {
1148        self.modules.values().map(|m| m.newtype_count()).sum()
1149    }
1150
1151    /// Get total type count across all modules (excluding traits)
1152    pub fn total_type_count(&self) -> usize {
1153        self.modules
1154            .values()
1155            .flat_map(|m| m.type_definitions.values())
1156            .filter(|t| !t.is_trait)
1157            .count()
1158    }
1159
1160    /// Calculate project-wide newtype usage ratio
1161    pub fn newtype_ratio(&self) -> f64 {
1162        let total = self.total_type_count();
1163        if total == 0 {
1164            return 0.0;
1165        }
1166        self.total_newtype_count() as f64 / total as f64
1167    }
1168
1169    /// Get types with serde derives (potential DTO exposure)
1170    pub fn serde_types(&self) -> Vec<(&str, &TypeDefinition)> {
1171        self.modules
1172            .iter()
1173            .flat_map(|(module_name, m)| {
1174                m.type_definitions
1175                    .values()
1176                    .filter(|t| t.has_serde_derive)
1177                    .map(move |t| (module_name.as_str(), t))
1178            })
1179            .collect()
1180    }
1181
1182    /// Identify potential God Modules
1183    pub fn god_modules(
1184        &self,
1185        max_functions: usize,
1186        max_types: usize,
1187        max_impls: usize,
1188    ) -> Vec<&str> {
1189        self.modules
1190            .iter()
1191            .filter(|(_, m)| m.is_god_module(max_functions, max_types, max_impls))
1192            .map(|(name, _)| name.as_str())
1193            .collect()
1194    }
1195
1196    /// Get all functions with potential Primitive Obsession
1197    pub fn functions_with_primitive_obsession(&self) -> Vec<(&str, &FunctionDefinition)> {
1198        self.modules
1199            .iter()
1200            .flat_map(|(module_name, m)| {
1201                m.functions_with_primitive_obsession()
1202                    .into_iter()
1203                    .map(move |f| (module_name.as_str(), f))
1204            })
1205            .collect()
1206    }
1207
1208    /// Get types with exposed public fields
1209    pub fn types_with_public_fields(&self) -> Vec<(&str, &TypeDefinition)> {
1210        self.modules
1211            .iter()
1212            .flat_map(|(module_name, m)| {
1213                m.type_definitions
1214                    .values()
1215                    .filter(|t| t.public_field_count > 0 && !t.is_trait)
1216                    .map(move |t| (module_name.as_str(), t))
1217            })
1218            .collect()
1219    }
1220}
1221
1222/// Summary of circular dependencies
1223#[derive(Debug, Clone)]
1224pub struct CircularDependencySummary {
1225    /// Total number of circular dependency cycles
1226    pub total_cycles: usize,
1227    /// Number of modules involved in cycles
1228    pub affected_modules: usize,
1229    /// The actual cycles (list of module names)
1230    pub cycles: Vec<Vec<String>>,
1231}
1232
1233#[cfg(test)]
1234mod tests {
1235    use super::*;
1236
1237    #[test]
1238    fn test_integration_strength_values() {
1239        assert_eq!(IntegrationStrength::Intrusive.value(), 1.0);
1240        assert_eq!(IntegrationStrength::Contract.value(), 0.25);
1241    }
1242
1243    #[test]
1244    fn test_distance_values() {
1245        assert_eq!(Distance::SameFunction.value(), 0.0);
1246        assert_eq!(Distance::DifferentCrate.value(), 1.0);
1247    }
1248
1249    #[test]
1250    fn test_volatility_from_count() {
1251        assert_eq!(Volatility::from_count(0), Volatility::Low);
1252        assert_eq!(Volatility::from_count(5), Volatility::Medium);
1253        assert_eq!(Volatility::from_count(15), Volatility::High);
1254    }
1255
1256    #[test]
1257    fn test_module_metrics_average_strength() {
1258        let mut metrics = ModuleMetrics::new(PathBuf::from("test.rs"), "test".to_string());
1259        metrics.trait_impl_count = 3;
1260        metrics.inherent_impl_count = 1;
1261
1262        let avg = metrics.average_strength();
1263        assert!(avg > 0.0 && avg < 1.0);
1264    }
1265
1266    #[test]
1267    fn test_project_metrics() {
1268        let mut project = ProjectMetrics::new();
1269
1270        let module = ModuleMetrics::new(PathBuf::from("lib.rs"), "lib".to_string());
1271        project.add_module(module);
1272
1273        assert_eq!(project.module_count(), 1);
1274        assert_eq!(project.coupling_count(), 0);
1275    }
1276
1277    #[test]
1278    fn test_circular_dependency_detection() {
1279        let mut project = ProjectMetrics::new();
1280
1281        // Create a cycle: A -> B -> C -> A
1282        project.add_coupling(CouplingMetrics::new(
1283            "module_a".to_string(),
1284            "module_b".to_string(),
1285            IntegrationStrength::Model,
1286            Distance::DifferentModule,
1287            Volatility::Low,
1288        ));
1289        project.add_coupling(CouplingMetrics::new(
1290            "module_b".to_string(),
1291            "module_c".to_string(),
1292            IntegrationStrength::Model,
1293            Distance::DifferentModule,
1294            Volatility::Low,
1295        ));
1296        project.add_coupling(CouplingMetrics::new(
1297            "module_c".to_string(),
1298            "module_a".to_string(),
1299            IntegrationStrength::Model,
1300            Distance::DifferentModule,
1301            Volatility::Low,
1302        ));
1303
1304        let cycles = project.detect_circular_dependencies();
1305        assert_eq!(cycles.len(), 1);
1306        assert_eq!(cycles[0].len(), 3);
1307    }
1308
1309    #[test]
1310    fn test_no_circular_dependencies() {
1311        let mut project = ProjectMetrics::new();
1312
1313        // Linear dependency: A -> B -> C (no cycle)
1314        project.add_coupling(CouplingMetrics::new(
1315            "module_a".to_string(),
1316            "module_b".to_string(),
1317            IntegrationStrength::Model,
1318            Distance::DifferentModule,
1319            Volatility::Low,
1320        ));
1321        project.add_coupling(CouplingMetrics::new(
1322            "module_b".to_string(),
1323            "module_c".to_string(),
1324            IntegrationStrength::Model,
1325            Distance::DifferentModule,
1326            Volatility::Low,
1327        ));
1328
1329        let cycles = project.detect_circular_dependencies();
1330        assert!(cycles.is_empty());
1331    }
1332
1333    #[test]
1334    fn test_external_crates_excluded_from_cycles() {
1335        let mut project = ProjectMetrics::new();
1336
1337        // External crate dependency should be ignored
1338        project.add_coupling(CouplingMetrics::new(
1339            "module_a".to_string(),
1340            "serde::Serialize".to_string(),
1341            IntegrationStrength::Contract,
1342            Distance::DifferentCrate, // External
1343            Volatility::Low,
1344        ));
1345        project.add_coupling(CouplingMetrics::new(
1346            "serde::Serialize".to_string(),
1347            "module_a".to_string(),
1348            IntegrationStrength::Contract,
1349            Distance::DifferentCrate, // External
1350            Volatility::Low,
1351        ));
1352
1353        let cycles = project.detect_circular_dependencies();
1354        assert!(cycles.is_empty());
1355    }
1356
1357    #[test]
1358    fn test_circular_dependency_summary() {
1359        let mut project = ProjectMetrics::new();
1360
1361        // Create a simple cycle: A <-> B
1362        project.add_coupling(CouplingMetrics::new(
1363            "module_a".to_string(),
1364            "module_b".to_string(),
1365            IntegrationStrength::Functional,
1366            Distance::DifferentModule,
1367            Volatility::Low,
1368        ));
1369        project.add_coupling(CouplingMetrics::new(
1370            "module_b".to_string(),
1371            "module_a".to_string(),
1372            IntegrationStrength::Functional,
1373            Distance::DifferentModule,
1374            Volatility::Low,
1375        ));
1376
1377        let summary = project.circular_dependency_summary();
1378        assert!(summary.total_cycles > 0);
1379        assert!(summary.affected_modules >= 2);
1380    }
1381
1382    #[test]
1383    fn test_visibility_intrusive_detection() {
1384        // Public items are never intrusive
1385        assert!(!Visibility::Public.is_intrusive_from(true, false));
1386        assert!(!Visibility::Public.is_intrusive_from(false, false));
1387
1388        // PubCrate is intrusive only from different crate
1389        assert!(!Visibility::PubCrate.is_intrusive_from(true, false));
1390        assert!(Visibility::PubCrate.is_intrusive_from(false, false));
1391
1392        // Private is always intrusive from outside
1393        assert!(Visibility::Private.is_intrusive_from(true, false));
1394        assert!(Visibility::Private.is_intrusive_from(false, false));
1395
1396        // Same module access is never intrusive
1397        assert!(!Visibility::Private.is_intrusive_from(true, true));
1398        assert!(!Visibility::Private.is_intrusive_from(false, true));
1399    }
1400
1401    #[test]
1402    fn test_visibility_penalty() {
1403        assert_eq!(Visibility::Public.intrusive_penalty(), 0.0);
1404        assert_eq!(Visibility::PubCrate.intrusive_penalty(), 0.25);
1405        assert_eq!(Visibility::Private.intrusive_penalty(), 1.0);
1406    }
1407
1408    #[test]
1409    fn test_effective_strength() {
1410        // Public target - no upgrade
1411        let coupling = CouplingMetrics::with_visibility(
1412            "source".to_string(),
1413            "target".to_string(),
1414            IntegrationStrength::Model,
1415            Distance::DifferentModule,
1416            Volatility::Low,
1417            Visibility::Public,
1418        );
1419        assert_eq!(coupling.effective_strength(), IntegrationStrength::Model);
1420
1421        // Private target from different module - upgraded
1422        let coupling = CouplingMetrics::with_visibility(
1423            "source".to_string(),
1424            "target".to_string(),
1425            IntegrationStrength::Model,
1426            Distance::DifferentModule,
1427            Volatility::Low,
1428            Visibility::Private,
1429        );
1430        assert_eq!(
1431            coupling.effective_strength(),
1432            IntegrationStrength::Functional
1433        );
1434    }
1435
1436    #[test]
1437    fn test_type_registry() {
1438        let mut project = ProjectMetrics::new();
1439
1440        project.register_type(
1441            "MyStruct".to_string(),
1442            "my_module".to_string(),
1443            Visibility::Public,
1444        );
1445        project.register_type(
1446            "InternalType".to_string(),
1447            "my_module".to_string(),
1448            Visibility::PubCrate,
1449        );
1450
1451        assert_eq!(
1452            project.get_type_visibility("MyStruct"),
1453            Some(Visibility::Public)
1454        );
1455        assert_eq!(
1456            project.get_type_visibility("InternalType"),
1457            Some(Visibility::PubCrate)
1458        );
1459        assert_eq!(project.get_type_visibility("Unknown"), None);
1460
1461        assert_eq!(project.get_type_module("MyStruct"), Some("my_module"));
1462    }
1463
1464    #[test]
1465    fn test_module_type_definitions() {
1466        let mut module = ModuleMetrics::new(PathBuf::from("test.rs"), "test".to_string());
1467
1468        module.add_type_definition("PublicStruct".to_string(), Visibility::Public, false);
1469        module.add_type_definition("PrivateStruct".to_string(), Visibility::Private, false);
1470        module.add_type_definition("PublicTrait".to_string(), Visibility::Public, true);
1471
1472        assert_eq!(module.public_type_count(), 2);
1473        assert_eq!(module.private_type_count(), 1);
1474        assert_eq!(
1475            module.get_type_visibility("PublicStruct"),
1476            Some(Visibility::Public)
1477        );
1478    }
1479
1480    #[test]
1481    fn test_update_volatility_from_git() {
1482        let mut project = ProjectMetrics::new();
1483
1484        // Add couplings with targets matching file names
1485        project.add_coupling(CouplingMetrics::new(
1486            "crate::main".to_string(),
1487            "crate::balance".to_string(),
1488            IntegrationStrength::Functional,
1489            Distance::DifferentModule,
1490            Volatility::Low, // Initial volatility
1491        ));
1492        project.add_coupling(CouplingMetrics::new(
1493            "crate::main".to_string(),
1494            "crate::analyzer".to_string(),
1495            IntegrationStrength::Functional,
1496            Distance::DifferentModule,
1497            Volatility::Low,
1498        ));
1499        project.add_coupling(CouplingMetrics::new(
1500            "crate::main".to_string(),
1501            "crate::report".to_string(),
1502            IntegrationStrength::Functional,
1503            Distance::DifferentModule,
1504            Volatility::Low,
1505        ));
1506
1507        // Simulate git file changes
1508        project
1509            .file_changes
1510            .insert("src/balance.rs".to_string(), 15); // High
1511        project
1512            .file_changes
1513            .insert("src/analyzer.rs".to_string(), 7); // Medium
1514        project.file_changes.insert("src/report.rs".to_string(), 2); // Low
1515
1516        // Update volatility from git data
1517        project.update_volatility_from_git();
1518
1519        // Verify volatility was updated correctly
1520        let balance_coupling = project
1521            .couplings
1522            .iter()
1523            .find(|c| c.target == "crate::balance")
1524            .unwrap();
1525        assert_eq!(balance_coupling.volatility, Volatility::High);
1526
1527        let analyzer_coupling = project
1528            .couplings
1529            .iter()
1530            .find(|c| c.target == "crate::analyzer")
1531            .unwrap();
1532        assert_eq!(analyzer_coupling.volatility, Volatility::Medium);
1533
1534        let report_coupling = project
1535            .couplings
1536            .iter()
1537            .find(|c| c.target == "crate::report")
1538            .unwrap();
1539        assert_eq!(report_coupling.volatility, Volatility::Low);
1540    }
1541
1542    #[test]
1543    fn test_volatility_with_type_targets() {
1544        // Test with more realistic targets that include type names (e.g., crate::balance::BalanceScore)
1545        let mut project = ProjectMetrics::new();
1546
1547        // Add couplings with Type-level targets (common in real analysis)
1548        project.add_coupling(CouplingMetrics::new(
1549            "crate::main".to_string(),
1550            "crate::balance::BalanceScore".to_string(), // Type in balance module
1551            IntegrationStrength::Functional,
1552            Distance::DifferentModule,
1553            Volatility::Low,
1554        ));
1555        project.add_coupling(CouplingMetrics::new(
1556            "crate::main".to_string(),
1557            "cargo-coupling::analyzer::analyze_file".to_string(), // Function in analyzer module
1558            IntegrationStrength::Functional,
1559            Distance::DifferentModule,
1560            Volatility::Low,
1561        ));
1562
1563        // Simulate git file changes
1564        project
1565            .file_changes
1566            .insert("src/balance.rs".to_string(), 15); // High
1567        project
1568            .file_changes
1569            .insert("src/analyzer.rs".to_string(), 7); // Medium
1570
1571        // Update volatility from git data
1572        project.update_volatility_from_git();
1573
1574        // Verify volatility was updated correctly by matching module path component
1575        let balance_coupling = project
1576            .couplings
1577            .iter()
1578            .find(|c| c.target.contains("balance"))
1579            .unwrap();
1580        assert_eq!(
1581            balance_coupling.volatility,
1582            Volatility::High,
1583            "Expected High volatility for balance module (15 changes)"
1584        );
1585
1586        let analyzer_coupling = project
1587            .couplings
1588            .iter()
1589            .find(|c| c.target.contains("analyzer"))
1590            .unwrap();
1591        assert_eq!(
1592            analyzer_coupling.volatility,
1593            Volatility::Medium,
1594            "Expected Medium volatility for analyzer module (7 changes)"
1595        );
1596    }
1597
1598    #[test]
1599    fn test_volatility_extracted_module_targets() {
1600        // Test with extracted module names (like what the analyzer produces)
1601        // The analyzer's extract_target_module() returns just "balance" from "crate::balance::Type"
1602        let mut project = ProjectMetrics::new();
1603
1604        // Extracted module targets (single component names)
1605        project.add_coupling(CouplingMetrics::new(
1606            "cargo-coupling::main".to_string(),
1607            "balance".to_string(), // Extracted module name
1608            IntegrationStrength::Functional,
1609            Distance::DifferentModule,
1610            Volatility::Low,
1611        ));
1612        project.add_coupling(CouplingMetrics::new(
1613            "cargo-coupling::main".to_string(),
1614            "analyzer".to_string(), // Extracted module name
1615            IntegrationStrength::Functional,
1616            Distance::DifferentModule,
1617            Volatility::Low,
1618        ));
1619        project.add_coupling(CouplingMetrics::new(
1620            "cargo-coupling::main".to_string(),
1621            "cli_output".to_string(), // Extracted module name with underscore
1622            IntegrationStrength::Functional,
1623            Distance::DifferentModule,
1624            Volatility::Low,
1625        ));
1626
1627        // Simulate git file changes
1628        project
1629            .file_changes
1630            .insert("src/balance.rs".to_string(), 15); // High
1631        project
1632            .file_changes
1633            .insert("src/analyzer.rs".to_string(), 7); // Medium
1634        project
1635            .file_changes
1636            .insert("src/cli_output.rs".to_string(), 3); // Medium
1637
1638        // Update volatility from git data
1639        project.update_volatility_from_git();
1640
1641        // Verify volatility was updated
1642        let balance = project
1643            .couplings
1644            .iter()
1645            .find(|c| c.target == "balance")
1646            .unwrap();
1647        assert_eq!(
1648            balance.volatility,
1649            Volatility::High,
1650            "balance should be High (15 changes)"
1651        );
1652
1653        let analyzer = project
1654            .couplings
1655            .iter()
1656            .find(|c| c.target == "analyzer")
1657            .unwrap();
1658        assert_eq!(
1659            analyzer.volatility,
1660            Volatility::Medium,
1661            "analyzer should be Medium (7 changes)"
1662        );
1663
1664        let cli_output = project
1665            .couplings
1666            .iter()
1667            .find(|c| c.target == "cli_output")
1668            .unwrap();
1669        assert_eq!(
1670            cli_output.volatility,
1671            Volatility::Medium,
1672            "cli_output should be Medium (3 changes)"
1673        );
1674    }
1675}