debtmap 0.16.3

Code complexity and technical debt analyzer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
//! Analysis configuration with premortem validation.
//!
//! This module provides the `AnalysisConfig` struct with comprehensive validation
//! using premortem's error accumulation and source tracking capabilities.
//!
//! # Design Philosophy
//!
//! - **Error Accumulation**: Show ALL configuration errors at once, not just the first
//! - **Source Tracking**: Know exactly where each config value came from
//! - **Cross-Field Validation**: Validate mutual exclusions and dependencies
//! - **Path Validation**: Verify paths exist before analysis begins
//!
//! # Example
//!
//! ```rust,ignore
//! use debtmap::config::analysis_config::{AnalysisConfig, AnalysisConfigBuilder};
//! use std::path::PathBuf;
//!
//! let config = AnalysisConfigBuilder::new(PathBuf::from("src"))
//!     .parallel(true)
//!     .jobs(4)
//!     .coverage_file(Some(PathBuf::from("coverage.lcov")))
//!     .build()?;
//!
//! // config is now validated - safe to use
//! ```

use serde::{Deserialize, Serialize};
use std::path::PathBuf;

use crate::effects::{
    combine_validations, validation_failure, validation_failures, validation_success,
    AnalysisValidation,
};
use crate::errors::AnalysisError;

use super::multi_source::ConfigSource;

/// Analysis configuration with declarative validation.
///
/// This struct holds all configuration options for code analysis,
/// with validation rules enforced at construction time.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalysisConfig {
    /// Project root directory to analyze.
    pub project_path: PathBuf,

    /// Enable parallel analysis.
    #[serde(default)]
    pub parallel: bool,

    /// Number of parallel jobs (1-256 when parallel is enabled).
    #[serde(default = "default_jobs")]
    pub jobs: usize,

    /// Output only aggregate results (mutually exclusive with no_aggregation).
    #[serde(default)]
    pub aggregate_only: bool,

    /// Disable aggregation entirely (mutually exclusive with aggregate_only).
    #[serde(default)]
    pub no_aggregation: bool,

    /// LCOV coverage file path (must exist if provided).
    #[serde(default)]
    pub coverage_file: Option<PathBuf>,

    /// Enable context-aware analysis.
    #[serde(default)]
    pub enable_context: bool,

    /// Enable multi-pass analysis (requires enable_context).
    #[serde(default)]
    pub multi_pass: bool,

    /// Complexity threshold for recommendations (1-1000).
    #[serde(default = "default_complexity_threshold")]
    pub complexity_threshold: u32,

    /// File patterns to exclude from analysis.
    #[serde(default)]
    pub exclude_patterns: Vec<String>,

    /// Show where config values came from (debug mode).
    #[serde(default)]
    pub show_config_sources: bool,
}

fn default_jobs() -> usize {
    std::thread::available_parallelism()
        .map(|p| p.get())
        .unwrap_or(4)
}

fn default_complexity_threshold() -> u32 {
    50
}

impl Default for AnalysisConfig {
    fn default() -> Self {
        Self {
            project_path: PathBuf::from("."),
            parallel: false,
            jobs: default_jobs(),
            aggregate_only: false,
            no_aggregation: false,
            coverage_file: None,
            enable_context: false,
            multi_pass: false,
            complexity_threshold: default_complexity_threshold(),
            exclude_patterns: Vec::new(),
            show_config_sources: false,
        }
    }
}

/// Traced configuration value with source information.
#[derive(Debug, Clone)]
pub struct TracedAnalysisValue<T> {
    /// The actual value
    pub value: T,
    /// Where this value came from
    pub source: ConfigSource,
}

impl<T> TracedAnalysisValue<T> {
    pub fn new(value: T, source: ConfigSource) -> Self {
        Self { value, source }
    }
}

/// A validation error with source location context.
#[derive(Debug, Clone)]
pub struct ConfigValidationError {
    /// The field path (e.g., "aggregate_only", "jobs")
    pub path: String,
    /// Source location where the value came from
    pub source: Option<ConfigSource>,
    /// The invalid value (as string for display)
    pub value: Option<String>,
    /// Human-readable error message
    pub message: String,
    /// Optional suggestion for fixing the error
    pub suggestion: Option<String>,
}

impl std::fmt::Display for ConfigValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(ref source) = self.source {
            write!(f, "[{}] ", source)?;
        }
        write!(f, "{}: {}", self.path, self.message)?;
        if let Some(ref value) = self.value {
            write!(f, " (value: {})", value)?;
        }
        if let Some(ref suggestion) = self.suggestion {
            write!(f, "\n    suggestion: {}", suggestion)?;
        }
        Ok(())
    }
}

impl AnalysisConfig {
    /// Validate the configuration, accumulating ALL errors.
    ///
    /// Returns `AnalysisValidation` which is either:
    /// - `Success(())` if all validation passes
    /// - `Failure(errors)` with ALL accumulated errors
    pub fn validate(&self) -> AnalysisValidation<()> {
        let validations = vec![
            self.validate_project_path(),
            self.validate_mutual_exclusions(),
            self.validate_parallel_jobs(),
            self.validate_context_dependencies(),
            self.validate_paths(),
            self.validate_complexity_threshold(),
            self.validate_exclude_patterns(),
        ];

        combine_validations(validations).map(|_| ())
    }

    /// Validates that project_path is not empty.
    fn validate_project_path(&self) -> AnalysisValidation<()> {
        if self.project_path.as_os_str().is_empty() {
            validation_failure(AnalysisError::config(
                "project_path cannot be empty".to_string(),
            ))
        } else {
            validation_success(())
        }
    }

    /// Validates mutually exclusive options.
    fn validate_mutual_exclusions(&self) -> AnalysisValidation<()> {
        if self.aggregate_only && self.no_aggregation {
            validation_failure(AnalysisError::config(
                "aggregate_only and no_aggregation are mutually exclusive".to_string(),
            ))
        } else {
            validation_success(())
        }
    }

    /// Validates parallel job configuration.
    fn validate_parallel_jobs(&self) -> AnalysisValidation<()> {
        if self.parallel && self.jobs == 0 {
            return validation_failure(AnalysisError::config(
                "jobs must be > 0 when parallel is enabled".to_string(),
            ));
        }

        if self.jobs > 256 {
            return validation_failure(AnalysisError::config(format!(
                "jobs must be <= 256, got {}",
                self.jobs
            )));
        }

        validation_success(())
    }

    /// Validates context-dependent options.
    fn validate_context_dependencies(&self) -> AnalysisValidation<()> {
        if self.multi_pass && !self.enable_context {
            validation_failure(AnalysisError::config(
                "multi_pass requires enable_context to be true".to_string(),
            ))
        } else {
            validation_success(())
        }
    }

    /// Validates file paths exist.
    fn validate_paths(&self) -> AnalysisValidation<()> {
        let mut errors = Vec::new();

        // Validate project_path is a directory
        if !self.project_path.is_dir() {
            if !self.project_path.exists() {
                errors.push(AnalysisError::config(format!(
                    "project_path directory does not exist: {}",
                    self.project_path.display()
                )));
            } else {
                errors.push(AnalysisError::config(format!(
                    "project_path is not a directory: {}",
                    self.project_path.display()
                )));
            }
        }

        // Validate coverage_file exists if provided
        if let Some(ref coverage) = self.coverage_file {
            if !coverage.exists() {
                errors.push(AnalysisError::config(format!(
                    "coverage_file does not exist: {}",
                    coverage.display()
                )));
            }
        }

        if errors.is_empty() {
            validation_success(())
        } else {
            validation_failures(errors)
        }
    }

    /// Validates complexity threshold range.
    fn validate_complexity_threshold(&self) -> AnalysisValidation<()> {
        if self.complexity_threshold == 0 {
            return validation_failure(AnalysisError::config(
                "complexity_threshold must be > 0".to_string(),
            ));
        }

        if self.complexity_threshold > 1000 {
            return validation_failure(AnalysisError::config(format!(
                "complexity_threshold must be <= 1000, got {}",
                self.complexity_threshold
            )));
        }

        validation_success(())
    }

    /// Validates exclude patterns are valid globs.
    fn validate_exclude_patterns(&self) -> AnalysisValidation<()> {
        let mut errors = Vec::new();

        for (i, pattern) in self.exclude_patterns.iter().enumerate() {
            if let Err(e) = glob::Pattern::new(pattern) {
                errors.push(AnalysisError::config(format!(
                    "invalid exclude pattern #{}: '{}' - {}",
                    i + 1,
                    pattern,
                    e
                )));
            }
        }

        if errors.is_empty() {
            validation_success(())
        } else {
            validation_failures(errors)
        }
    }
}

/// Builder for AnalysisConfig with validation.
///
/// This builder collects all configuration values and validates them
/// at build time, reporting ALL errors at once.
#[derive(Debug)]
pub struct AnalysisConfigBuilder {
    config: AnalysisConfig,
    /// Track sources for each field
    sources: std::collections::HashMap<String, ConfigSource>,
}

impl AnalysisConfigBuilder {
    /// Create a new builder with required project path.
    pub fn new(project_path: PathBuf) -> Self {
        let mut sources = std::collections::HashMap::new();
        sources.insert("project_path".to_string(), ConfigSource::Default);

        Self {
            config: AnalysisConfig {
                project_path,
                ..Default::default()
            },
            sources,
        }
    }

    /// Set parallel analysis mode.
    pub fn parallel(mut self, parallel: bool) -> Self {
        self.config.parallel = parallel;
        self
    }

    /// Set parallel analysis with source tracking.
    pub fn parallel_from(mut self, parallel: bool, source: ConfigSource) -> Self {
        self.config.parallel = parallel;
        self.sources.insert("parallel".to_string(), source);
        self
    }

    /// Set number of parallel jobs.
    pub fn jobs(mut self, jobs: usize) -> Self {
        self.config.jobs = jobs;
        self
    }

    /// Set jobs with source tracking.
    pub fn jobs_from(mut self, jobs: usize, source: ConfigSource) -> Self {
        self.config.jobs = jobs;
        self.sources.insert("jobs".to_string(), source);
        self
    }

    /// Set aggregate_only mode.
    pub fn aggregate_only(mut self, aggregate_only: bool) -> Self {
        self.config.aggregate_only = aggregate_only;
        self
    }

    /// Set no_aggregation mode.
    pub fn no_aggregation(mut self, no_aggregation: bool) -> Self {
        self.config.no_aggregation = no_aggregation;
        self
    }

    /// Set coverage file path.
    pub fn coverage_file(mut self, coverage_file: Option<PathBuf>) -> Self {
        self.config.coverage_file = coverage_file;
        self
    }

    /// Set coverage file with source tracking.
    pub fn coverage_file_from(
        mut self,
        coverage_file: Option<PathBuf>,
        source: ConfigSource,
    ) -> Self {
        self.config.coverage_file = coverage_file;
        self.sources.insert("coverage_file".to_string(), source);
        self
    }

    /// Set enable_context mode.
    pub fn enable_context(mut self, enable_context: bool) -> Self {
        self.config.enable_context = enable_context;
        self
    }

    /// Set multi_pass mode.
    pub fn multi_pass(mut self, multi_pass: bool) -> Self {
        self.config.multi_pass = multi_pass;
        self
    }

    /// Set complexity threshold.
    pub fn complexity_threshold(mut self, threshold: u32) -> Self {
        self.config.complexity_threshold = threshold;
        self
    }

    /// Set exclude patterns.
    pub fn exclude_patterns(mut self, patterns: Vec<String>) -> Self {
        self.config.exclude_patterns = patterns;
        self
    }

    /// Set show_config_sources.
    pub fn show_config_sources(mut self, show: bool) -> Self {
        self.config.show_config_sources = show;
        self
    }

    /// Build and validate the configuration.
    ///
    /// Returns `Ok(AnalysisConfig)` if valid, or `Err` with ALL validation errors.
    pub fn build(self) -> Result<AnalysisConfig, Vec<AnalysisError>> {
        match self.config.validate() {
            stillwater::Validation::Success(_) => Ok(self.config),
            stillwater::Validation::Failure(errors) => Err(errors.into_iter().collect()),
        }
    }

    /// Build with validation using AnalysisValidation for error accumulation.
    pub fn build_validated(self) -> AnalysisValidation<AnalysisConfig> {
        match self.config.validate() {
            stillwater::Validation::Success(_) => validation_success(self.config),
            stillwater::Validation::Failure(errors) => stillwater::Validation::Failure(errors),
        }
    }

    /// Get tracked sources for debugging.
    pub fn sources(&self) -> &std::collections::HashMap<String, ConfigSource> {
        &self.sources
    }
}

/// Format validation errors with source locations for user display.
///
/// # Example Output
///
/// ```text
/// Configuration errors (3):
///
///   [debtmap.toml:8] aggregate_only: aggregate_only and no_aggregation are mutually exclusive
///     value: true
///     suggestion: Remove one of these options
///
///   [env:DEBTMAP_JOBS] jobs: value 0 is not in range 1..=256
///     value: 0
///     suggestion: Set DEBTMAP_JOBS to a value between 1 and 256
/// ```
pub fn format_config_errors(errors: &[AnalysisError]) -> String {
    let mut output = format!("Configuration errors ({}):\n", errors.len());

    for error in errors {
        output.push_str(&format!("\n  {}\n", error));
    }

    output.push_str("\nFix all errors and try again.\n");
    output
}

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

    #[test]
    fn test_valid_config_builds_successfully() {
        let temp_dir = TempDir::new().unwrap();

        let config = AnalysisConfigBuilder::new(temp_dir.path().to_path_buf())
            .parallel(true)
            .jobs(4)
            .build();

        assert!(config.is_ok());
        let config = config.unwrap();
        assert!(config.parallel);
        assert_eq!(config.jobs, 4);
    }

    #[test]
    fn test_mutual_exclusion_error() {
        let temp_dir = TempDir::new().unwrap();

        let result = AnalysisConfigBuilder::new(temp_dir.path().to_path_buf())
            .aggregate_only(true)
            .no_aggregation(true)
            .build();

        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert!(errors
            .iter()
            .any(|e| e.to_string().contains("mutually exclusive")));
    }

    #[test]
    fn test_parallel_jobs_validation() {
        let temp_dir = TempDir::new().unwrap();

        // jobs=0 with parallel=true should fail
        let result = AnalysisConfigBuilder::new(temp_dir.path().to_path_buf())
            .parallel(true)
            .jobs(0)
            .build();

        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert!(errors.iter().any(|e| e.to_string().contains("jobs")));
    }

    #[test]
    fn test_jobs_too_high() {
        let temp_dir = TempDir::new().unwrap();

        let result = AnalysisConfigBuilder::new(temp_dir.path().to_path_buf())
            .jobs(500)
            .build();

        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert!(errors.iter().any(|e| e.to_string().contains("256")));
    }

    #[test]
    fn test_context_dependency_validation() {
        let temp_dir = TempDir::new().unwrap();

        // multi_pass without enable_context should fail
        let result = AnalysisConfigBuilder::new(temp_dir.path().to_path_buf())
            .multi_pass(true)
            .enable_context(false)
            .build();

        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert!(errors
            .iter()
            .any(|e| e.to_string().contains("multi_pass requires enable_context")));
    }

    #[test]
    fn test_coverage_file_not_found() {
        let temp_dir = TempDir::new().unwrap();

        let result = AnalysisConfigBuilder::new(temp_dir.path().to_path_buf())
            .coverage_file(Some(PathBuf::from("/nonexistent/coverage.lcov")))
            .build();

        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert!(errors
            .iter()
            .any(|e| e.to_string().contains("does not exist")));
    }

    #[test]
    fn test_project_path_not_directory() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("file.txt");
        std::fs::write(&file_path, "test").unwrap();

        let result = AnalysisConfigBuilder::new(file_path).build();

        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert!(errors
            .iter()
            .any(|e| e.to_string().contains("not a directory")));
    }

    #[test]
    fn test_multiple_errors_accumulated() {
        // All errors should be reported together
        let result = AnalysisConfigBuilder::new(PathBuf::from("/nonexistent/path"))
            .parallel(true)
            .jobs(0) // Error: jobs must be > 0
            .aggregate_only(true)
            .no_aggregation(true) // Error: mutually exclusive
            .multi_pass(true) // Error: requires enable_context
            .build();

        assert!(result.is_err());
        let errors = result.unwrap_err();
        // Should have at least 3 errors (path, mutual exclusion, multi_pass)
        assert!(
            errors.len() >= 3,
            "Expected at least 3 errors, got {}: {:?}",
            errors.len(),
            errors
        );
    }

    #[test]
    fn test_invalid_exclude_pattern() {
        let temp_dir = TempDir::new().unwrap();

        let result = AnalysisConfigBuilder::new(temp_dir.path().to_path_buf())
            .exclude_patterns(vec!["[invalid".to_string()])
            .build();

        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert!(errors
            .iter()
            .any(|e| e.to_string().contains("invalid exclude pattern")));
    }

    #[test]
    fn test_complexity_threshold_validation() {
        let temp_dir = TempDir::new().unwrap();

        // Zero threshold should fail
        let result = AnalysisConfigBuilder::new(temp_dir.path().to_path_buf())
            .complexity_threshold(0)
            .build();

        assert!(result.is_err());

        // Threshold too high should fail
        let result = AnalysisConfigBuilder::new(temp_dir.path().to_path_buf())
            .complexity_threshold(2000)
            .build();

        assert!(result.is_err());
    }

    #[test]
    fn test_default_config() {
        let config = AnalysisConfig::default();
        assert!(!config.parallel);
        assert!(!config.aggregate_only);
        assert!(!config.no_aggregation);
        assert!(!config.enable_context);
        assert!(!config.multi_pass);
        assert_eq!(config.complexity_threshold, 50);
    }

    #[test]
    fn test_format_config_errors() {
        let errors = vec![
            AnalysisError::config("error 1".to_string()),
            AnalysisError::config("error 2".to_string()),
        ];

        let output = format_config_errors(&errors);
        assert!(output.contains("Configuration errors (2)"));
        assert!(output.contains("error 1"));
        assert!(output.contains("error 2"));
    }

    #[test]
    fn test_source_tracking() {
        let temp_dir = TempDir::new().unwrap();

        let builder = AnalysisConfigBuilder::new(temp_dir.path().to_path_buf())
            .jobs_from(8, ConfigSource::Environment("DEBTMAP_JOBS".to_string()));

        let sources = builder.sources();
        assert!(sources.contains_key("jobs"));
        assert!(matches!(
            sources.get("jobs"),
            Some(ConfigSource::Environment(_))
        ));
    }
}