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    /// Whether this module is a test module (mod tests or #[cfg(test)])
574    pub is_test_module: bool,
575    /// Number of test functions (#[test])
576    pub test_function_count: usize,
577}
578
579impl ModuleMetrics {
580    pub fn new(path: PathBuf, name: String) -> Self {
581        Self {
582            path,
583            name,
584            ..Default::default()
585        }
586    }
587
588    /// Add a type definition to this module (simple version for backward compatibility)
589    pub fn add_type_definition(&mut self, name: String, visibility: Visibility, is_trait: bool) {
590        self.type_definitions.insert(
591            name.clone(),
592            TypeDefinition {
593                name,
594                visibility,
595                is_trait,
596                is_newtype: false,
597                inner_type: None,
598                has_serde_derive: false,
599                public_field_count: 0,
600                total_field_count: 0,
601            },
602        );
603    }
604
605    /// Add a type definition with full details
606    #[allow(clippy::too_many_arguments)]
607    pub fn add_type_definition_full(
608        &mut self,
609        name: String,
610        visibility: Visibility,
611        is_trait: bool,
612        is_newtype: bool,
613        inner_type: Option<String>,
614        has_serde_derive: bool,
615        public_field_count: usize,
616        total_field_count: usize,
617    ) {
618        self.type_definitions.insert(
619            name.clone(),
620            TypeDefinition {
621                name,
622                visibility,
623                is_trait,
624                is_newtype,
625                inner_type,
626                has_serde_derive,
627                public_field_count,
628                total_field_count,
629            },
630        );
631    }
632
633    /// Add a function definition to this module (simple version for backward compatibility)
634    pub fn add_function_definition(&mut self, name: String, visibility: Visibility) {
635        self.function_definitions.insert(
636            name.clone(),
637            FunctionDefinition {
638                name,
639                visibility,
640                param_count: 0,
641                primitive_param_count: 0,
642                param_types: Vec::new(),
643            },
644        );
645    }
646
647    /// Add a function definition with full details
648    pub fn add_function_definition_full(
649        &mut self,
650        name: String,
651        visibility: Visibility,
652        param_count: usize,
653        primitive_param_count: usize,
654        param_types: Vec<String>,
655    ) {
656        self.function_definitions.insert(
657            name.clone(),
658            FunctionDefinition {
659                name,
660                visibility,
661                param_count,
662                primitive_param_count,
663                param_types,
664            },
665        );
666    }
667
668    /// Get visibility of a type defined in this module
669    pub fn get_type_visibility(&self, name: &str) -> Option<Visibility> {
670        self.type_definitions.get(name).map(|t| t.visibility)
671    }
672
673    /// Count public types
674    pub fn public_type_count(&self) -> usize {
675        self.type_definitions
676            .values()
677            .filter(|t| t.visibility == Visibility::Public)
678            .count()
679    }
680
681    /// Count non-public types
682    pub fn private_type_count(&self) -> usize {
683        self.type_definitions
684            .values()
685            .filter(|t| t.visibility != Visibility::Public)
686            .count()
687    }
688
689    /// Calculate average integration strength
690    pub fn average_strength(&self) -> f64 {
691        let total = self.trait_impl_count + self.inherent_impl_count;
692        if total == 0 {
693            return 0.0;
694        }
695
696        let contract_weight = self.trait_impl_count as f64 * IntegrationStrength::Contract.value();
697        let intrusive_weight =
698            self.inherent_impl_count as f64 * IntegrationStrength::Intrusive.value();
699
700        (contract_weight + intrusive_weight) / total as f64
701    }
702
703    /// Count newtypes in this module
704    pub fn newtype_count(&self) -> usize {
705        self.type_definitions
706            .values()
707            .filter(|t| t.is_newtype)
708            .count()
709    }
710
711    /// Count types with serde derives
712    pub fn serde_type_count(&self) -> usize {
713        self.type_definitions
714            .values()
715            .filter(|t| t.has_serde_derive)
716            .count()
717    }
718
719    /// Calculate newtype usage ratio (newtypes / total non-trait types)
720    pub fn newtype_ratio(&self) -> f64 {
721        let non_trait_types = self
722            .type_definitions
723            .values()
724            .filter(|t| !t.is_trait)
725            .count();
726        if non_trait_types == 0 {
727            return 0.0;
728        }
729        self.newtype_count() as f64 / non_trait_types as f64
730    }
731
732    /// Count types with public fields
733    pub fn types_with_public_fields(&self) -> usize {
734        self.type_definitions
735            .values()
736            .filter(|t| t.public_field_count > 0)
737            .count()
738    }
739
740    /// Total function count
741    pub fn function_count(&self) -> usize {
742        self.function_definitions.len()
743    }
744
745    /// Count functions with high primitive parameter ratio
746    /// (potential Primitive Obsession)
747    pub fn functions_with_primitive_obsession(&self) -> Vec<&FunctionDefinition> {
748        self.function_definitions
749            .values()
750            .filter(|f| {
751                f.param_count >= 3 && f.primitive_param_count as f64 / f.param_count as f64 >= 0.6
752            })
753            .collect()
754    }
755
756    /// Check if this module is a potential "God Module"
757    /// (too many functions, types, or implementations)
758    pub fn is_god_module(&self, max_functions: usize, max_types: usize, max_impls: usize) -> bool {
759        self.function_count() > max_functions
760            || self.type_definitions.len() > max_types
761            || (self.trait_impl_count + self.inherent_impl_count) > max_impls
762    }
763}
764
765/// Project-wide analysis results
766#[derive(Debug, Default)]
767pub struct ProjectMetrics {
768    /// All module metrics
769    pub modules: HashMap<String, ModuleMetrics>,
770    /// All detected couplings
771    pub couplings: Vec<CouplingMetrics>,
772    /// File change counts (for volatility)
773    pub file_changes: HashMap<String, usize>,
774    /// Total files analyzed
775    pub total_files: usize,
776    /// Workspace name (if available from cargo metadata)
777    pub workspace_name: Option<String>,
778    /// Workspace member crate names
779    pub workspace_members: Vec<String>,
780    /// Crate-level dependencies (crate name -> list of dependencies)
781    pub crate_dependencies: HashMap<String, Vec<String>>,
782    /// Global type registry: type name -> (module name, visibility)
783    pub type_registry: HashMap<String, (String, Visibility)>,
784}
785
786impl ProjectMetrics {
787    pub fn new() -> Self {
788        Self::default()
789    }
790
791    /// Add module metrics
792    pub fn add_module(&mut self, metrics: ModuleMetrics) {
793        self.modules.insert(metrics.name.clone(), metrics);
794    }
795
796    /// Add coupling
797    pub fn add_coupling(&mut self, coupling: CouplingMetrics) {
798        self.couplings.push(coupling);
799    }
800
801    /// Register a type definition in the global registry
802    pub fn register_type(
803        &mut self,
804        type_name: String,
805        module_name: String,
806        visibility: Visibility,
807    ) {
808        self.type_registry
809            .insert(type_name, (module_name, visibility));
810    }
811
812    /// Look up visibility of a type by name
813    pub fn get_type_visibility(&self, type_name: &str) -> Option<Visibility> {
814        self.type_registry.get(type_name).map(|(_, vis)| *vis)
815    }
816
817    /// Look up the module where a type is defined
818    pub fn get_type_module(&self, type_name: &str) -> Option<&str> {
819        self.type_registry
820            .get(type_name)
821            .map(|(module, _)| module.as_str())
822    }
823
824    /// Update visibility information for existing couplings
825    ///
826    /// This should be called after all modules have been analyzed
827    /// to populate the target_visibility field of couplings.
828    pub fn update_coupling_visibility(&mut self) {
829        // First collect all the visibility lookups
830        let visibility_updates: Vec<(usize, Visibility)> = self
831            .couplings
832            .iter()
833            .enumerate()
834            .filter_map(|(idx, coupling)| {
835                let target_type = coupling
836                    .target
837                    .split("::")
838                    .last()
839                    .unwrap_or(&coupling.target);
840                self.type_registry
841                    .get(target_type)
842                    .map(|(_, vis)| (idx, *vis))
843            })
844            .collect();
845
846        // Then apply the updates
847        for (idx, visibility) in visibility_updates {
848            self.couplings[idx].target_visibility = visibility;
849        }
850    }
851
852    /// Get total module count
853    pub fn module_count(&self) -> usize {
854        self.modules.len()
855    }
856
857    /// Get total coupling count
858    pub fn coupling_count(&self) -> usize {
859        self.couplings.len()
860    }
861
862    /// Get internal coupling count (excludes external crate dependencies)
863    pub fn internal_coupling_count(&self) -> usize {
864        self.couplings
865            .iter()
866            .filter(|c| !crate::balance::is_external_crate(&c.target, &c.source))
867            .count()
868    }
869
870    /// Calculate average strength across all couplings
871    pub fn average_strength(&self) -> Option<f64> {
872        if self.couplings.is_empty() {
873            return None;
874        }
875        let sum: f64 = self.couplings.iter().map(|c| c.strength_value()).sum();
876        Some(sum / self.couplings.len() as f64)
877    }
878
879    /// Calculate average distance across all couplings
880    pub fn average_distance(&self) -> Option<f64> {
881        if self.couplings.is_empty() {
882            return None;
883        }
884        let sum: f64 = self.couplings.iter().map(|c| c.distance_value()).sum();
885        Some(sum / self.couplings.len() as f64)
886    }
887
888    /// Update volatility for all couplings based on file changes
889    ///
890    /// This should be called after git history analysis to update
891    /// the volatility of each coupling based on how often the target
892    /// module/file has changed.
893    pub fn update_volatility_from_git(&mut self) {
894        if self.file_changes.is_empty() {
895            return;
896        }
897
898        // Debug: print file changes for troubleshooting
899        #[cfg(test)]
900        {
901            eprintln!("DEBUG: file_changes = {:?}", self.file_changes);
902        }
903
904        for coupling in &mut self.couplings {
905            // Try to find the target file in file_changes
906            // The target is like "crate::module" or "crate::module::Type"
907            // We need to match this against file paths like "src/module.rs"
908            //
909            // Special cases in Rust module system:
910            // - crate root "crate::crate_name" or "crate_name::crate_name" -> lib.rs
911            // - binary entry point -> main.rs
912            // - glob imports "crate::*" -> don't match specific files
913
914            // Extract all path components from target
915            let target_parts: Vec<&str> = coupling.target.split("::").collect();
916
917            // Find the best matching file
918            let mut max_changes = 0usize;
919            for (file_path, &changes) in &self.file_changes {
920                // Get file name without .rs extension (e.g., "balance" from "src/balance.rs")
921                let file_name = file_path
922                    .rsplit('/')
923                    .next()
924                    .unwrap_or(file_path)
925                    .trim_end_matches(".rs");
926
927                // Check if any target path component matches the file name
928                let matches = target_parts.iter().any(|part| {
929                    let part_lower = part.to_lowercase();
930                    let file_lower = file_name.to_lowercase();
931
932                    // Direct match: "balance" == "balance"
933                    if part_lower == file_lower {
934                        return true;
935                    }
936
937                    // Handle crate root: if the part matches the crate name and file is lib.rs
938                    // e.g., "cargo_coupling" matches "lib" (lib.rs is the crate root)
939                    if file_lower == "lib" && !part.is_empty() && *part != "*" {
940                        // This could be the crate root reference
941                        // We also match if the part is the crate name (same as first path component)
942                        if target_parts.len() >= 2 && target_parts[1] == *part {
943                            return true;
944                        }
945                    }
946
947                    // Handle underscore vs hyphen in crate names
948                    // e.g., "cargo-coupling" might appear as "cargo_coupling" in code
949                    let part_normalized = part_lower.replace('-', "_");
950                    let file_normalized = file_lower.replace('-', "_");
951                    if part_normalized == file_normalized {
952                        return true;
953                    }
954
955                    // Path contains match: "web" matches "src/web/graph.rs"
956                    if file_path.to_lowercase().contains(&part_lower) {
957                        return true;
958                    }
959
960                    false
961                });
962
963                if matches {
964                    max_changes = max_changes.max(changes);
965                }
966            }
967
968            coupling.volatility = Volatility::from_count(max_changes);
969        }
970    }
971
972    /// Build a dependency graph from couplings
973    fn build_dependency_graph(&self) -> HashMap<String, HashSet<String>> {
974        let mut graph: HashMap<String, HashSet<String>> = HashMap::new();
975
976        for coupling in &self.couplings {
977            // Only consider internal couplings (not external crates)
978            if coupling.distance == Distance::DifferentCrate {
979                continue;
980            }
981
982            // Extract module names (remove crate prefix for cleaner cycles)
983            let source = coupling.source.clone();
984            let target = coupling.target.clone();
985
986            graph.entry(source).or_default().insert(target);
987        }
988
989        graph
990    }
991
992    /// Detect circular dependencies in the project
993    ///
994    /// Returns a list of cycles, where each cycle is a list of module names
995    /// forming the circular dependency chain.
996    pub fn detect_circular_dependencies(&self) -> Vec<Vec<String>> {
997        let graph = self.build_dependency_graph();
998        let mut cycles: Vec<Vec<String>> = Vec::new();
999        let mut visited: HashSet<String> = HashSet::new();
1000        let mut rec_stack: HashSet<String> = HashSet::new();
1001
1002        for node in graph.keys() {
1003            if !visited.contains(node) {
1004                let mut path = Vec::new();
1005                self.dfs_find_cycles(
1006                    node,
1007                    &graph,
1008                    &mut visited,
1009                    &mut rec_stack,
1010                    &mut path,
1011                    &mut cycles,
1012                );
1013            }
1014        }
1015
1016        // Deduplicate cycles (same cycle can be detected from different starting points)
1017        let mut unique_cycles: Vec<Vec<String>> = Vec::new();
1018        for cycle in cycles {
1019            let normalized = Self::normalize_cycle(&cycle);
1020            if !unique_cycles
1021                .iter()
1022                .any(|c| Self::normalize_cycle(c) == normalized)
1023            {
1024                unique_cycles.push(cycle);
1025            }
1026        }
1027
1028        unique_cycles
1029    }
1030
1031    /// DFS helper for cycle detection
1032    fn dfs_find_cycles(
1033        &self,
1034        node: &str,
1035        graph: &HashMap<String, HashSet<String>>,
1036        visited: &mut HashSet<String>,
1037        rec_stack: &mut HashSet<String>,
1038        path: &mut Vec<String>,
1039        cycles: &mut Vec<Vec<String>>,
1040    ) {
1041        visited.insert(node.to_string());
1042        rec_stack.insert(node.to_string());
1043        path.push(node.to_string());
1044
1045        if let Some(neighbors) = graph.get(node) {
1046            for neighbor in neighbors {
1047                if !visited.contains(neighbor) {
1048                    self.dfs_find_cycles(neighbor, graph, visited, rec_stack, path, cycles);
1049                } else if rec_stack.contains(neighbor) {
1050                    // Found a cycle - extract the cycle from path
1051                    if let Some(start_idx) = path.iter().position(|n| n == neighbor) {
1052                        let cycle: Vec<String> = path[start_idx..].to_vec();
1053                        if cycle.len() >= 2 {
1054                            cycles.push(cycle);
1055                        }
1056                    }
1057                }
1058            }
1059        }
1060
1061        path.pop();
1062        rec_stack.remove(node);
1063    }
1064
1065    /// Normalize a cycle for deduplication
1066    /// Rotates the cycle so the lexicographically smallest element is first
1067    fn normalize_cycle(cycle: &[String]) -> Vec<String> {
1068        if cycle.is_empty() {
1069            return Vec::new();
1070        }
1071
1072        // Find the position of the minimum element
1073        let min_pos = cycle
1074            .iter()
1075            .enumerate()
1076            .min_by_key(|(_, s)| s.as_str())
1077            .map(|(i, _)| i)
1078            .unwrap_or(0);
1079
1080        // Rotate the cycle
1081        let mut normalized: Vec<String> = cycle[min_pos..].to_vec();
1082        normalized.extend_from_slice(&cycle[..min_pos]);
1083        normalized
1084    }
1085
1086    /// Get circular dependency summary
1087    pub fn circular_dependency_summary(&self) -> CircularDependencySummary {
1088        let cycles = self.detect_circular_dependencies();
1089        let affected_modules: HashSet<String> = cycles.iter().flatten().cloned().collect();
1090
1091        CircularDependencySummary {
1092            total_cycles: cycles.len(),
1093            affected_modules: affected_modules.len(),
1094            cycles,
1095        }
1096    }
1097
1098    /// Calculate 3-dimensional coupling statistics
1099    ///
1100    /// Computes distribution of couplings across Strength, Distance,
1101    /// Volatility, and Balance Classification dimensions.
1102    pub fn calculate_dimension_stats(&self) -> DimensionStats {
1103        let mut stats = DimensionStats::default();
1104
1105        for coupling in &self.couplings {
1106            // Count strength distribution
1107            match coupling.strength {
1108                IntegrationStrength::Intrusive => stats.strength_counts.intrusive += 1,
1109                IntegrationStrength::Functional => stats.strength_counts.functional += 1,
1110                IntegrationStrength::Model => stats.strength_counts.model += 1,
1111                IntegrationStrength::Contract => stats.strength_counts.contract += 1,
1112            }
1113
1114            // Count distance distribution
1115            match coupling.distance {
1116                Distance::SameFunction | Distance::SameModule => {
1117                    stats.distance_counts.same_module += 1
1118                }
1119                Distance::DifferentModule => stats.distance_counts.different_module += 1,
1120                Distance::DifferentCrate => stats.distance_counts.different_crate += 1,
1121            }
1122
1123            // Count volatility distribution
1124            match coupling.volatility {
1125                Volatility::Low => stats.volatility_counts.low += 1,
1126                Volatility::Medium => stats.volatility_counts.medium += 1,
1127                Volatility::High => stats.volatility_counts.high += 1,
1128            }
1129
1130            // Classify and count balance
1131            let classification = BalanceClassification::classify(
1132                coupling.strength,
1133                coupling.distance,
1134                coupling.volatility,
1135            );
1136            match classification {
1137                BalanceClassification::HighCohesion => stats.balance_counts.high_cohesion += 1,
1138                BalanceClassification::LooseCoupling => stats.balance_counts.loose_coupling += 1,
1139                BalanceClassification::Acceptable => stats.balance_counts.acceptable += 1,
1140                BalanceClassification::Pain => stats.balance_counts.pain += 1,
1141                BalanceClassification::LocalComplexity => {
1142                    stats.balance_counts.local_complexity += 1
1143                }
1144            }
1145        }
1146
1147        stats
1148    }
1149
1150    /// Get total newtype count across all modules
1151    pub fn total_newtype_count(&self) -> usize {
1152        self.modules.values().map(|m| m.newtype_count()).sum()
1153    }
1154
1155    /// Get total type count across all modules (excluding traits)
1156    pub fn total_type_count(&self) -> usize {
1157        self.modules
1158            .values()
1159            .flat_map(|m| m.type_definitions.values())
1160            .filter(|t| !t.is_trait)
1161            .count()
1162    }
1163
1164    /// Calculate project-wide newtype usage ratio
1165    pub fn newtype_ratio(&self) -> f64 {
1166        let total = self.total_type_count();
1167        if total == 0 {
1168            return 0.0;
1169        }
1170        self.total_newtype_count() as f64 / total as f64
1171    }
1172
1173    /// Get types with serde derives (potential DTO exposure)
1174    pub fn serde_types(&self) -> Vec<(&str, &TypeDefinition)> {
1175        self.modules
1176            .iter()
1177            .flat_map(|(module_name, m)| {
1178                m.type_definitions
1179                    .values()
1180                    .filter(|t| t.has_serde_derive)
1181                    .map(move |t| (module_name.as_str(), t))
1182            })
1183            .collect()
1184    }
1185
1186    /// Identify potential God Modules
1187    pub fn god_modules(
1188        &self,
1189        max_functions: usize,
1190        max_types: usize,
1191        max_impls: usize,
1192    ) -> Vec<&str> {
1193        self.modules
1194            .iter()
1195            .filter(|(_, m)| m.is_god_module(max_functions, max_types, max_impls))
1196            .map(|(name, _)| name.as_str())
1197            .collect()
1198    }
1199
1200    /// Get all functions with potential Primitive Obsession
1201    pub fn functions_with_primitive_obsession(&self) -> Vec<(&str, &FunctionDefinition)> {
1202        self.modules
1203            .iter()
1204            .flat_map(|(module_name, m)| {
1205                m.functions_with_primitive_obsession()
1206                    .into_iter()
1207                    .map(move |f| (module_name.as_str(), f))
1208            })
1209            .collect()
1210    }
1211
1212    /// Get types with exposed public fields
1213    pub fn types_with_public_fields(&self) -> Vec<(&str, &TypeDefinition)> {
1214        self.modules
1215            .iter()
1216            .flat_map(|(module_name, m)| {
1217                m.type_definitions
1218                    .values()
1219                    .filter(|t| t.public_field_count > 0 && !t.is_trait)
1220                    .map(move |t| (module_name.as_str(), t))
1221            })
1222            .collect()
1223    }
1224}
1225
1226/// Summary of circular dependencies
1227#[derive(Debug, Clone)]
1228pub struct CircularDependencySummary {
1229    /// Total number of circular dependency cycles
1230    pub total_cycles: usize,
1231    /// Number of modules involved in cycles
1232    pub affected_modules: usize,
1233    /// The actual cycles (list of module names)
1234    pub cycles: Vec<Vec<String>>,
1235}
1236
1237#[cfg(test)]
1238mod tests {
1239    use super::*;
1240
1241    #[test]
1242    fn test_integration_strength_values() {
1243        assert_eq!(IntegrationStrength::Intrusive.value(), 1.0);
1244        assert_eq!(IntegrationStrength::Contract.value(), 0.25);
1245    }
1246
1247    #[test]
1248    fn test_distance_values() {
1249        assert_eq!(Distance::SameFunction.value(), 0.0);
1250        assert_eq!(Distance::DifferentCrate.value(), 1.0);
1251    }
1252
1253    #[test]
1254    fn test_volatility_from_count() {
1255        assert_eq!(Volatility::from_count(0), Volatility::Low);
1256        assert_eq!(Volatility::from_count(5), Volatility::Medium);
1257        assert_eq!(Volatility::from_count(15), Volatility::High);
1258    }
1259
1260    #[test]
1261    fn test_module_metrics_average_strength() {
1262        let mut metrics = ModuleMetrics::new(PathBuf::from("test.rs"), "test".to_string());
1263        metrics.trait_impl_count = 3;
1264        metrics.inherent_impl_count = 1;
1265
1266        let avg = metrics.average_strength();
1267        assert!(avg > 0.0 && avg < 1.0);
1268    }
1269
1270    #[test]
1271    fn test_project_metrics() {
1272        let mut project = ProjectMetrics::new();
1273
1274        let module = ModuleMetrics::new(PathBuf::from("lib.rs"), "lib".to_string());
1275        project.add_module(module);
1276
1277        assert_eq!(project.module_count(), 1);
1278        assert_eq!(project.coupling_count(), 0);
1279    }
1280
1281    #[test]
1282    fn test_circular_dependency_detection() {
1283        let mut project = ProjectMetrics::new();
1284
1285        // Create a cycle: A -> B -> C -> A
1286        project.add_coupling(CouplingMetrics::new(
1287            "module_a".to_string(),
1288            "module_b".to_string(),
1289            IntegrationStrength::Model,
1290            Distance::DifferentModule,
1291            Volatility::Low,
1292        ));
1293        project.add_coupling(CouplingMetrics::new(
1294            "module_b".to_string(),
1295            "module_c".to_string(),
1296            IntegrationStrength::Model,
1297            Distance::DifferentModule,
1298            Volatility::Low,
1299        ));
1300        project.add_coupling(CouplingMetrics::new(
1301            "module_c".to_string(),
1302            "module_a".to_string(),
1303            IntegrationStrength::Model,
1304            Distance::DifferentModule,
1305            Volatility::Low,
1306        ));
1307
1308        let cycles = project.detect_circular_dependencies();
1309        assert_eq!(cycles.len(), 1);
1310        assert_eq!(cycles[0].len(), 3);
1311    }
1312
1313    #[test]
1314    fn test_no_circular_dependencies() {
1315        let mut project = ProjectMetrics::new();
1316
1317        // Linear dependency: A -> B -> C (no cycle)
1318        project.add_coupling(CouplingMetrics::new(
1319            "module_a".to_string(),
1320            "module_b".to_string(),
1321            IntegrationStrength::Model,
1322            Distance::DifferentModule,
1323            Volatility::Low,
1324        ));
1325        project.add_coupling(CouplingMetrics::new(
1326            "module_b".to_string(),
1327            "module_c".to_string(),
1328            IntegrationStrength::Model,
1329            Distance::DifferentModule,
1330            Volatility::Low,
1331        ));
1332
1333        let cycles = project.detect_circular_dependencies();
1334        assert!(cycles.is_empty());
1335    }
1336
1337    #[test]
1338    fn test_external_crates_excluded_from_cycles() {
1339        let mut project = ProjectMetrics::new();
1340
1341        // External crate dependency should be ignored
1342        project.add_coupling(CouplingMetrics::new(
1343            "module_a".to_string(),
1344            "serde::Serialize".to_string(),
1345            IntegrationStrength::Contract,
1346            Distance::DifferentCrate, // External
1347            Volatility::Low,
1348        ));
1349        project.add_coupling(CouplingMetrics::new(
1350            "serde::Serialize".to_string(),
1351            "module_a".to_string(),
1352            IntegrationStrength::Contract,
1353            Distance::DifferentCrate, // External
1354            Volatility::Low,
1355        ));
1356
1357        let cycles = project.detect_circular_dependencies();
1358        assert!(cycles.is_empty());
1359    }
1360
1361    #[test]
1362    fn test_circular_dependency_summary() {
1363        let mut project = ProjectMetrics::new();
1364
1365        // Create a simple cycle: A <-> B
1366        project.add_coupling(CouplingMetrics::new(
1367            "module_a".to_string(),
1368            "module_b".to_string(),
1369            IntegrationStrength::Functional,
1370            Distance::DifferentModule,
1371            Volatility::Low,
1372        ));
1373        project.add_coupling(CouplingMetrics::new(
1374            "module_b".to_string(),
1375            "module_a".to_string(),
1376            IntegrationStrength::Functional,
1377            Distance::DifferentModule,
1378            Volatility::Low,
1379        ));
1380
1381        let summary = project.circular_dependency_summary();
1382        assert!(summary.total_cycles > 0);
1383        assert!(summary.affected_modules >= 2);
1384    }
1385
1386    #[test]
1387    fn test_visibility_intrusive_detection() {
1388        // Public items are never intrusive
1389        assert!(!Visibility::Public.is_intrusive_from(true, false));
1390        assert!(!Visibility::Public.is_intrusive_from(false, false));
1391
1392        // PubCrate is intrusive only from different crate
1393        assert!(!Visibility::PubCrate.is_intrusive_from(true, false));
1394        assert!(Visibility::PubCrate.is_intrusive_from(false, false));
1395
1396        // Private is always intrusive from outside
1397        assert!(Visibility::Private.is_intrusive_from(true, false));
1398        assert!(Visibility::Private.is_intrusive_from(false, false));
1399
1400        // Same module access is never intrusive
1401        assert!(!Visibility::Private.is_intrusive_from(true, true));
1402        assert!(!Visibility::Private.is_intrusive_from(false, true));
1403    }
1404
1405    #[test]
1406    fn test_visibility_penalty() {
1407        assert_eq!(Visibility::Public.intrusive_penalty(), 0.0);
1408        assert_eq!(Visibility::PubCrate.intrusive_penalty(), 0.25);
1409        assert_eq!(Visibility::Private.intrusive_penalty(), 1.0);
1410    }
1411
1412    #[test]
1413    fn test_effective_strength() {
1414        // Public target - no upgrade
1415        let coupling = CouplingMetrics::with_visibility(
1416            "source".to_string(),
1417            "target".to_string(),
1418            IntegrationStrength::Model,
1419            Distance::DifferentModule,
1420            Volatility::Low,
1421            Visibility::Public,
1422        );
1423        assert_eq!(coupling.effective_strength(), IntegrationStrength::Model);
1424
1425        // Private target from different module - upgraded
1426        let coupling = CouplingMetrics::with_visibility(
1427            "source".to_string(),
1428            "target".to_string(),
1429            IntegrationStrength::Model,
1430            Distance::DifferentModule,
1431            Volatility::Low,
1432            Visibility::Private,
1433        );
1434        assert_eq!(
1435            coupling.effective_strength(),
1436            IntegrationStrength::Functional
1437        );
1438    }
1439
1440    #[test]
1441    fn test_type_registry() {
1442        let mut project = ProjectMetrics::new();
1443
1444        project.register_type(
1445            "MyStruct".to_string(),
1446            "my_module".to_string(),
1447            Visibility::Public,
1448        );
1449        project.register_type(
1450            "InternalType".to_string(),
1451            "my_module".to_string(),
1452            Visibility::PubCrate,
1453        );
1454
1455        assert_eq!(
1456            project.get_type_visibility("MyStruct"),
1457            Some(Visibility::Public)
1458        );
1459        assert_eq!(
1460            project.get_type_visibility("InternalType"),
1461            Some(Visibility::PubCrate)
1462        );
1463        assert_eq!(project.get_type_visibility("Unknown"), None);
1464
1465        assert_eq!(project.get_type_module("MyStruct"), Some("my_module"));
1466    }
1467
1468    #[test]
1469    fn test_module_type_definitions() {
1470        let mut module = ModuleMetrics::new(PathBuf::from("test.rs"), "test".to_string());
1471
1472        module.add_type_definition("PublicStruct".to_string(), Visibility::Public, false);
1473        module.add_type_definition("PrivateStruct".to_string(), Visibility::Private, false);
1474        module.add_type_definition("PublicTrait".to_string(), Visibility::Public, true);
1475
1476        assert_eq!(module.public_type_count(), 2);
1477        assert_eq!(module.private_type_count(), 1);
1478        assert_eq!(
1479            module.get_type_visibility("PublicStruct"),
1480            Some(Visibility::Public)
1481        );
1482    }
1483
1484    #[test]
1485    fn test_update_volatility_from_git() {
1486        let mut project = ProjectMetrics::new();
1487
1488        // Add couplings with targets matching file names
1489        project.add_coupling(CouplingMetrics::new(
1490            "crate::main".to_string(),
1491            "crate::balance".to_string(),
1492            IntegrationStrength::Functional,
1493            Distance::DifferentModule,
1494            Volatility::Low, // Initial volatility
1495        ));
1496        project.add_coupling(CouplingMetrics::new(
1497            "crate::main".to_string(),
1498            "crate::analyzer".to_string(),
1499            IntegrationStrength::Functional,
1500            Distance::DifferentModule,
1501            Volatility::Low,
1502        ));
1503        project.add_coupling(CouplingMetrics::new(
1504            "crate::main".to_string(),
1505            "crate::report".to_string(),
1506            IntegrationStrength::Functional,
1507            Distance::DifferentModule,
1508            Volatility::Low,
1509        ));
1510
1511        // Simulate git file changes
1512        project
1513            .file_changes
1514            .insert("src/balance.rs".to_string(), 15); // High
1515        project
1516            .file_changes
1517            .insert("src/analyzer.rs".to_string(), 7); // Medium
1518        project.file_changes.insert("src/report.rs".to_string(), 2); // Low
1519
1520        // Update volatility from git data
1521        project.update_volatility_from_git();
1522
1523        // Verify volatility was updated correctly
1524        let balance_coupling = project
1525            .couplings
1526            .iter()
1527            .find(|c| c.target == "crate::balance")
1528            .unwrap();
1529        assert_eq!(balance_coupling.volatility, Volatility::High);
1530
1531        let analyzer_coupling = project
1532            .couplings
1533            .iter()
1534            .find(|c| c.target == "crate::analyzer")
1535            .unwrap();
1536        assert_eq!(analyzer_coupling.volatility, Volatility::Medium);
1537
1538        let report_coupling = project
1539            .couplings
1540            .iter()
1541            .find(|c| c.target == "crate::report")
1542            .unwrap();
1543        assert_eq!(report_coupling.volatility, Volatility::Low);
1544    }
1545
1546    #[test]
1547    fn test_volatility_with_type_targets() {
1548        // Test with more realistic targets that include type names (e.g., crate::balance::BalanceScore)
1549        let mut project = ProjectMetrics::new();
1550
1551        // Add couplings with Type-level targets (common in real analysis)
1552        project.add_coupling(CouplingMetrics::new(
1553            "crate::main".to_string(),
1554            "crate::balance::BalanceScore".to_string(), // Type in balance module
1555            IntegrationStrength::Functional,
1556            Distance::DifferentModule,
1557            Volatility::Low,
1558        ));
1559        project.add_coupling(CouplingMetrics::new(
1560            "crate::main".to_string(),
1561            "cargo-coupling::analyzer::analyze_file".to_string(), // Function in analyzer module
1562            IntegrationStrength::Functional,
1563            Distance::DifferentModule,
1564            Volatility::Low,
1565        ));
1566
1567        // Simulate git file changes
1568        project
1569            .file_changes
1570            .insert("src/balance.rs".to_string(), 15); // High
1571        project
1572            .file_changes
1573            .insert("src/analyzer.rs".to_string(), 7); // Medium
1574
1575        // Update volatility from git data
1576        project.update_volatility_from_git();
1577
1578        // Verify volatility was updated correctly by matching module path component
1579        let balance_coupling = project
1580            .couplings
1581            .iter()
1582            .find(|c| c.target.contains("balance"))
1583            .unwrap();
1584        assert_eq!(
1585            balance_coupling.volatility,
1586            Volatility::High,
1587            "Expected High volatility for balance module (15 changes)"
1588        );
1589
1590        let analyzer_coupling = project
1591            .couplings
1592            .iter()
1593            .find(|c| c.target.contains("analyzer"))
1594            .unwrap();
1595        assert_eq!(
1596            analyzer_coupling.volatility,
1597            Volatility::Medium,
1598            "Expected Medium volatility for analyzer module (7 changes)"
1599        );
1600    }
1601
1602    #[test]
1603    fn test_volatility_extracted_module_targets() {
1604        // Test with extracted module names (like what the analyzer produces)
1605        // The analyzer's extract_target_module() returns just "balance" from "crate::balance::Type"
1606        let mut project = ProjectMetrics::new();
1607
1608        // Extracted module targets (single component names)
1609        project.add_coupling(CouplingMetrics::new(
1610            "cargo-coupling::main".to_string(),
1611            "balance".to_string(), // Extracted module name
1612            IntegrationStrength::Functional,
1613            Distance::DifferentModule,
1614            Volatility::Low,
1615        ));
1616        project.add_coupling(CouplingMetrics::new(
1617            "cargo-coupling::main".to_string(),
1618            "analyzer".to_string(), // Extracted module name
1619            IntegrationStrength::Functional,
1620            Distance::DifferentModule,
1621            Volatility::Low,
1622        ));
1623        project.add_coupling(CouplingMetrics::new(
1624            "cargo-coupling::main".to_string(),
1625            "cli_output".to_string(), // Extracted module name with underscore
1626            IntegrationStrength::Functional,
1627            Distance::DifferentModule,
1628            Volatility::Low,
1629        ));
1630
1631        // Simulate git file changes
1632        project
1633            .file_changes
1634            .insert("src/balance.rs".to_string(), 15); // High
1635        project
1636            .file_changes
1637            .insert("src/analyzer.rs".to_string(), 7); // Medium
1638        project
1639            .file_changes
1640            .insert("src/cli_output.rs".to_string(), 3); // Medium
1641
1642        // Update volatility from git data
1643        project.update_volatility_from_git();
1644
1645        // Verify volatility was updated
1646        let balance = project
1647            .couplings
1648            .iter()
1649            .find(|c| c.target == "balance")
1650            .unwrap();
1651        assert_eq!(
1652            balance.volatility,
1653            Volatility::High,
1654            "balance should be High (15 changes)"
1655        );
1656
1657        let analyzer = project
1658            .couplings
1659            .iter()
1660            .find(|c| c.target == "analyzer")
1661            .unwrap();
1662        assert_eq!(
1663            analyzer.volatility,
1664            Volatility::Medium,
1665            "analyzer should be Medium (7 changes)"
1666        );
1667
1668        let cli_output = project
1669            .couplings
1670            .iter()
1671            .find(|c| c.target == "cli_output")
1672            .unwrap();
1673        assert_eq!(
1674            cli_output.volatility,
1675            Volatility::Medium,
1676            "cli_output should be Medium (3 changes)"
1677        );
1678    }
1679}