ryo-app 0.1.0

[preview] Application layer for RYO - Project management, Intent handling, API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
//! Project configuration (ryo.toml)
//!
//! Configuration schema for Ryo projects.
//! Loaded from `ryo.toml` in the project root.

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

use ryo_suggest::SuggestStrategy;

/// Project configuration loaded from `ryo.toml`
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct RyoConfig {
    /// Project metadata
    pub project: ProjectConfig,

    /// Module-specific settings
    #[serde(default)]
    pub modules: HashMap<String, ModuleConfig>,

    /// Import settings
    #[serde(default)]
    pub import: ImportConfig,

    /// Mutation execution settings
    #[serde(default)]
    pub mutations: MutationConfig,

    /// Suggestion settings
    #[serde(default)]
    pub suggest: SuggestConfig,
}

/// Project metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ProjectConfig {
    /// Project name (optional, defaults to Cargo.toml name)
    pub name: Option<String>,

    /// Project description
    pub description: Option<String>,

    /// Edition (defaults to 2021)
    #[serde(default = "default_edition")]
    pub edition: String,

    /// Workspace root directory (relative to ryo.toml location)
    ///
    /// If not set, detected from Cargo.toml location.
    /// Use this when the repository root differs from the Cargo workspace root.
    pub workspace_root: Option<PathBuf>,

    /// Path to Cargo.toml (relative to ryo.toml location)
    ///
    /// If not set, uses `{workspace_root}/Cargo.toml` or auto-detects.
    pub manifest_path: Option<PathBuf>,
}

impl Default for ProjectConfig {
    fn default() -> Self {
        Self {
            name: None,
            description: None,
            edition: default_edition(),
            workspace_root: None,
            manifest_path: None,
        }
    }
}

fn default_edition() -> String {
    "2021".to_string()
}

/// Module-specific configuration
///
/// Keys can be:
/// - File path: `[modules."src/generated"]` - matches by file path prefix
/// - SymbolPath: `[modules."my_crate::generated"]` - matches by symbol path (contains `::`)
///
/// SymbolPath patterns support wildcards:
/// - `my_crate::*` - all symbols in my_crate
/// - `*::tests::*` - all test modules in any crate
/// - `my_crate::generated::*` - all symbols under generated module
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct ModuleConfig {
    /// Skip lint checks for this module
    pub skip_lint: bool,

    /// Skip refactoring for this module
    pub skip_refactor: bool,

    /// Allow unsafe code in this module
    pub allow_unsafe: bool,

    /// Skip format checking
    pub skip_format_check: bool,

    /// Custom tags for this module
    #[serde(default)]
    pub tags: Vec<String>,

    /// Disabled rule IDs for this module (e.g., ["RL001", "RL09*"])
    #[serde(default)]
    pub disabled_rules: Vec<String>,

    /// Enabled rule IDs for this module (empty = all enabled after disabled filter)
    #[serde(default)]
    pub enabled_rules: Vec<String>,
}

/// Import configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ImportConfig {
    /// Preserve comments during import
    pub preserve_comments: bool,

    /// Auto-format after import
    pub auto_format: bool,

    /// Validate syntax on import
    pub validate_syntax: bool,
}

impl Default for ImportConfig {
    fn default() -> Self {
        Self {
            preserve_comments: true,
            auto_format: false,
            validate_syntax: true,
        }
    }
}

/// Mutation execution configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct MutationConfig {
    /// Auto-organize imports after mutation
    pub auto_organize_imports: bool,

    /// Run cargo check after mutation
    pub check_compile: bool,

    /// Parallel execution
    pub parallel: bool,
}

impl Default for MutationConfig {
    fn default() -> Self {
        Self {
            auto_organize_imports: false,
            check_compile: false,
            parallel: true,
        }
    }
}

/// Suggestion configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SuggestConfig {
    /// Evaluation strategy preset: "interactive", "high_perf", "batch", "manual"
    pub strategy: String,

    /// Auto-detect suggestions after successful run
    pub auto_detect_after_run: bool,

    /// Auto-apply safe suggestions (dangerous, default false)
    pub auto_apply: bool,

    /// Enabled pattern names (empty = all enabled)
    #[serde(default)]
    pub enabled_patterns: Vec<String>,

    /// Disabled pattern names
    #[serde(default)]
    pub disabled_patterns: Vec<String>,

    /// Disabled rule IDs (e.g., ["RL001", "RL003", "RL09*"])
    /// Supports wildcards: "RL*" matches all rules starting with "RL"
    #[serde(default)]
    pub disabled_rules: Vec<String>,

    /// Enabled rule IDs (empty = all enabled, after disabled_rules filter)
    /// Supports wildcards: "RL0*" matches RL001, RL002, etc.
    #[serde(default)]
    pub enabled_rules: Vec<String>,

    /// Severity overrides per rule ID
    /// e.g., { "RL003" = "Info", "RL043" = "Warning" }
    #[serde(default)]
    pub severity_overrides: std::collections::HashMap<String, String>,
}

impl Default for SuggestConfig {
    fn default() -> Self {
        Self {
            strategy: "interactive".to_string(),
            auto_detect_after_run: true,
            auto_apply: false,
            enabled_patterns: vec![],
            disabled_patterns: vec![],
            disabled_rules: vec![],
            enabled_rules: vec![],
            severity_overrides: std::collections::HashMap::new(),
        }
    }
}

impl SuggestConfig {
    /// Convert to SuggestStrategy
    pub fn to_strategy(&self) -> SuggestStrategy {
        match self.strategy.as_str() {
            "high_perf" => SuggestStrategy::high_perf(),
            "batch" | "manual" => SuggestStrategy::batch(),
            _ => SuggestStrategy::interactive(),
        }
    }

    /// Check if a pattern is enabled
    pub fn is_pattern_enabled(&self, name: &str) -> bool {
        // If explicitly disabled, return false
        if self.disabled_patterns.iter().any(|p| p == name) {
            return false;
        }

        // If enabled_patterns is empty, all patterns are enabled
        if self.enabled_patterns.is_empty() {
            return true;
        }

        // Otherwise, check if explicitly enabled
        self.enabled_patterns.iter().any(|p| p == name)
    }

    /// Check if a rule ID is enabled (supports wildcards like "RL*")
    pub fn is_rule_enabled(&self, rule_id: &str) -> bool {
        // If explicitly disabled (with wildcard support), return false
        if self
            .disabled_rules
            .iter()
            .any(|p| Self::matches_pattern(p, rule_id))
        {
            return false;
        }

        // If enabled_rules is empty, all rules are enabled
        if self.enabled_rules.is_empty() {
            return true;
        }

        // Otherwise, check if explicitly enabled (with wildcard support)
        self.enabled_rules
            .iter()
            .any(|p| Self::matches_pattern(p, rule_id))
    }

    /// Get severity override for a rule ID
    pub fn get_severity_override(&self, rule_id: &str) -> Option<&str> {
        self.severity_overrides.get(rule_id).map(|s| s.as_str())
    }

    /// Match pattern with wildcard support (e.g., "RL*" matches "RL001")
    fn matches_pattern(pattern: &str, value: &str) -> bool {
        if pattern == "*" {
            return true;
        }
        if let Some(prefix) = pattern.strip_suffix('*') {
            return value.starts_with(prefix);
        }
        if let Some(suffix) = pattern.strip_prefix('*') {
            return value.ends_with(suffix);
        }
        pattern == value
    }
}

/// Error loading configuration
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    #[error("TOML parse error: {0}")]
    Toml(#[from] toml::de::Error),

    #[error("Config not found: {0}")]
    NotFound(PathBuf),
}

impl RyoConfig {
    /// Config file name
    pub const FILE_NAME: &'static str = "ryo.toml";

    /// Load config from a directory (looks for ryo.toml)
    pub fn load(dir: impl AsRef<Path>) -> Result<Self, ConfigError> {
        let path = dir.as_ref().join(Self::FILE_NAME);
        Self::load_from_path(&path)
    }

    /// Load config from a specific path
    pub fn load_from_path(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
        let path = path.as_ref();
        if !path.exists() {
            return Err(ConfigError::NotFound(path.to_path_buf()));
        }

        let content = std::fs::read_to_string(path)?;
        let config: RyoConfig = toml::from_str(&content)?;
        Ok(config)
    }

    /// Load config or return default if not found
    pub fn load_or_default(dir: impl AsRef<Path>) -> Self {
        Self::load(dir).unwrap_or_default()
    }

    /// Save config to a directory
    pub fn save(&self, dir: impl AsRef<Path>) -> Result<(), ConfigError> {
        let path = dir.as_ref().join(Self::FILE_NAME);
        self.save_to_path(&path)
    }

    /// Save config to a specific path
    pub fn save_to_path(&self, path: impl AsRef<Path>) -> Result<(), ConfigError> {
        let content = toml::to_string_pretty(self).map_err(std::io::Error::other)?;
        std::fs::write(path, content)?;
        Ok(())
    }

    /// Get module config for a file path.
    ///
    /// Only matches file path patterns (keys without `::`).
    /// For SymbolPath matching, use `get_module_config_for_symbol`.
    pub fn get_module_config(&self, path: &str) -> Option<&ModuleConfig> {
        // Try exact match first (file paths only)
        if let Some(config) = self.modules.get(path) {
            if !path.contains("::") {
                return Some(config);
            }
        }

        // Try prefix match (e.g., "src/generated" matches "src/generated/foo.rs")
        // Skip SymbolPath patterns (containing "::")
        for (key, config) in &self.modules {
            if key.contains("::") {
                continue; // Skip SymbolPath patterns
            }
            if path.starts_with(key) {
                return Some(config);
            }
        }

        None
    }

    /// Get module config for a symbol path.
    ///
    /// Matches against SymbolPath patterns (keys containing `::`).
    /// Supports wildcards: `*` matches any segment.
    ///
    /// # Example patterns
    /// - `my_crate::generated` - exact match
    /// - `my_crate::generated::*` - any symbol under generated
    /// - `*::tests::*` - any test module in any crate
    pub fn get_module_config_for_symbol(&self, symbol_path: &str) -> Option<&ModuleConfig> {
        // Try exact match first
        if let Some(config) = self.modules.get(symbol_path) {
            return Some(config);
        }

        // Try pattern matching (only SymbolPath patterns)
        for (pattern, config) in &self.modules {
            if !pattern.contains("::") {
                continue; // Skip file path patterns
            }
            if Self::matches_symbol_path_pattern(pattern, symbol_path) {
                return Some(config);
            }
        }

        None
    }

    /// Match a SymbolPath pattern against a symbol path.
    ///
    /// Pattern segments are separated by `::`. `*` matches any single segment.
    /// Trailing `*` matches any remaining segments.
    fn matches_symbol_path_pattern(pattern: &str, symbol_path: &str) -> bool {
        let pattern_parts: Vec<&str> = pattern.split("::").collect();
        let path_parts: Vec<&str> = symbol_path.split("::").collect();

        // Check if pattern ends with `*` (matches any suffix)
        let ends_with_wildcard = pattern_parts.last() == Some(&"*");
        let pattern_parts = if ends_with_wildcard {
            &pattern_parts[..pattern_parts.len() - 1]
        } else {
            &pattern_parts[..]
        };

        // If pattern is longer than path (without trailing wildcard), no match
        if !ends_with_wildcard && pattern_parts.len() != path_parts.len() {
            return false;
        }
        if pattern_parts.len() > path_parts.len() {
            return false;
        }

        // Match each segment
        for (i, pattern_part) in pattern_parts.iter().enumerate() {
            if *pattern_part == "*" {
                continue; // Wildcard matches anything
            }
            if path_parts.get(i) != Some(pattern_part) {
                return false;
            }
        }

        true
    }

    /// Check if a module should be skipped for lint
    pub fn should_skip_lint(&self, path: &str) -> bool {
        self.get_module_config(path)
            .map(|c| c.skip_lint)
            .unwrap_or(false)
    }

    /// Check if a module should be skipped for refactor
    pub fn should_skip_refactor(&self, path: &str) -> bool {
        self.get_module_config(path)
            .map(|c| c.skip_refactor)
            .unwrap_or(false)
    }

    /// Check if a rule is enabled for a symbol path.
    ///
    /// Checks module-level disabled_rules first, then falls back to global suggest config.
    pub fn is_rule_enabled_for_symbol(&self, symbol_path: &str, rule_id: &str) -> bool {
        // Check module-level config first
        if let Some(module_config) = self.get_module_config_for_symbol(symbol_path) {
            // Check disabled_rules with wildcard support
            if module_config
                .disabled_rules
                .iter()
                .any(|p| SuggestConfig::matches_pattern(p, rule_id))
            {
                return false;
            }
            // Check enabled_rules (if specified)
            if !module_config.enabled_rules.is_empty()
                && !module_config
                    .enabled_rules
                    .iter()
                    .any(|p| SuggestConfig::matches_pattern(p, rule_id))
            {
                return false;
            }
        }

        // Fall back to global suggest config
        self.suggest.is_rule_enabled(rule_id)
    }

    /// Check if a rule is enabled for a file path.
    ///
    /// Checks module-level disabled_rules first (using file path prefix matching),
    /// then falls back to global suggest config.
    pub fn is_rule_enabled_for_file(&self, file_path: &str, rule_id: &str) -> bool {
        // Check module-level config first (file path based)
        if let Some(module_config) = self.get_module_config(file_path) {
            // Check disabled_rules with wildcard support
            if module_config
                .disabled_rules
                .iter()
                .any(|p| SuggestConfig::matches_pattern(p, rule_id))
            {
                return false;
            }
            // Check enabled_rules (if specified)
            if !module_config.enabled_rules.is_empty()
                && !module_config
                    .enabled_rules
                    .iter()
                    .any(|p| SuggestConfig::matches_pattern(p, rule_id))
            {
                return false;
            }
        }

        // Fall back to global suggest config
        self.suggest.is_rule_enabled(rule_id)
    }
}

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

    #[test]
    fn test_parse_minimal_config() {
        let toml = r#"
[project]
name = "my-app"
"#;
        let config: RyoConfig = toml::from_str(toml).unwrap();
        assert_eq!(config.project.name, Some("my-app".to_string()));
    }

    #[test]
    fn test_parse_full_config() {
        let toml = r#"
[project]
name = "my-app"
description = "A sample project"
edition = "2021"

[modules."src/generated"]
skip_lint = true
allow_unsafe = true

[modules."src/legacy"]
skip_refactor = true
tags = ["deprecated"]

[import]
preserve_comments = true
auto_format = false

[mutations]
auto_organize_imports = true
check_compile = true
parallel = true
"#;
        let config: RyoConfig = toml::from_str(toml).unwrap();

        assert_eq!(config.project.name, Some("my-app".to_string()));

        let gen_config = config.modules.get("src/generated").unwrap();
        assert!(gen_config.skip_lint);
        assert!(gen_config.allow_unsafe);

        let legacy_config = config.modules.get("src/legacy").unwrap();
        assert!(legacy_config.skip_refactor);
        assert_eq!(legacy_config.tags, vec!["deprecated"]);

        assert!(config.import.preserve_comments);
        assert!(config.mutations.auto_organize_imports);
    }

    #[test]
    fn test_default_config() {
        let config = RyoConfig::default();
        assert_eq!(config.project.edition, "2021");
        assert!(config.import.preserve_comments);
        assert!(config.mutations.parallel);
    }

    #[test]
    fn test_module_config_prefix_match() {
        let toml = r#"
[modules."src/generated"]
skip_lint = true
"#;
        let config: RyoConfig = toml::from_str(toml).unwrap();

        // Exact match
        assert!(config.should_skip_lint("src/generated"));

        // Prefix match
        assert!(config.should_skip_lint("src/generated/foo.rs"));
        assert!(config.should_skip_lint("src/generated/bar/baz.rs"));

        // No match
        assert!(!config.should_skip_lint("src/main.rs"));
    }

    #[test]
    fn test_suggest_config_default() {
        let config = SuggestConfig::default();
        assert_eq!(config.strategy, "interactive");
        assert!(config.auto_detect_after_run);
        assert!(!config.auto_apply);
        assert!(config.enabled_patterns.is_empty());
        assert!(config.disabled_patterns.is_empty());
    }

    #[test]
    fn test_suggest_config_parse() {
        let toml = r#"
[suggest]
strategy = "high_perf"
auto_detect_after_run = false
auto_apply = false
disabled_patterns = ["Builder"]
"#;
        let config: RyoConfig = toml::from_str(toml).unwrap();
        assert_eq!(config.suggest.strategy, "high_perf");
        assert!(!config.suggest.auto_detect_after_run);
        assert_eq!(config.suggest.disabled_patterns, vec!["Builder"]);
    }

    #[test]
    fn test_suggest_config_to_strategy() {
        let config = SuggestConfig {
            strategy: "interactive".to_string(),
            ..Default::default()
        };
        let _ = config.to_strategy(); // Should not panic

        let config = SuggestConfig {
            strategy: "high_perf".to_string(),
            ..Default::default()
        };
        let _ = config.to_strategy();

        let config = SuggestConfig {
            strategy: "batch".to_string(),
            ..Default::default()
        };
        let _ = config.to_strategy();
    }

    #[test]
    fn test_suggest_config_pattern_enabled() {
        // Default: all enabled
        let config = SuggestConfig::default();
        assert!(config.is_pattern_enabled("Default"));
        assert!(config.is_pattern_enabled("Builder"));

        // With enabled_patterns: only listed enabled
        let config = SuggestConfig {
            enabled_patterns: vec!["Default".to_string()],
            ..Default::default()
        };
        assert!(config.is_pattern_enabled("Default"));
        assert!(!config.is_pattern_enabled("Builder"));

        // With disabled_patterns: listed disabled
        let config = SuggestConfig {
            disabled_patterns: vec!["Builder".to_string()],
            ..Default::default()
        };
        assert!(config.is_pattern_enabled("Default"));
        assert!(!config.is_pattern_enabled("Builder"));

        // Disabled takes precedence over enabled
        let config = SuggestConfig {
            enabled_patterns: vec!["Default".to_string(), "Builder".to_string()],
            disabled_patterns: vec!["Builder".to_string()],
            ..Default::default()
        };
        assert!(config.is_pattern_enabled("Default"));
        assert!(!config.is_pattern_enabled("Builder"));
    }

    #[test]
    fn test_suggest_config_rule_enabled() {
        // Default: all enabled
        let config = SuggestConfig::default();
        assert!(config.is_rule_enabled("RL001"));
        assert!(config.is_rule_enabled("RL090"));

        // With disabled_rules: listed disabled
        let config = SuggestConfig {
            disabled_rules: vec!["RL001".to_string()],
            ..Default::default()
        };
        assert!(!config.is_rule_enabled("RL001"));
        assert!(config.is_rule_enabled("RL002"));

        // Wildcard: disable all RL09* rules
        let config = SuggestConfig {
            disabled_rules: vec!["RL09*".to_string()],
            ..Default::default()
        };
        assert!(config.is_rule_enabled("RL001"));
        assert!(!config.is_rule_enabled("RL090"));
        assert!(!config.is_rule_enabled("RL091"));

        // With enabled_rules: only listed enabled
        let config = SuggestConfig {
            enabled_rules: vec!["RL00*".to_string()],
            ..Default::default()
        };
        assert!(config.is_rule_enabled("RL001"));
        assert!(config.is_rule_enabled("RL002"));
        assert!(!config.is_rule_enabled("RL010"));
        assert!(!config.is_rule_enabled("RL090"));

        // Disabled takes precedence over enabled
        let config = SuggestConfig {
            enabled_rules: vec!["RL00*".to_string()],
            disabled_rules: vec!["RL002".to_string()],
            ..Default::default()
        };
        assert!(config.is_rule_enabled("RL001"));
        assert!(!config.is_rule_enabled("RL002"));
        assert!(!config.is_rule_enabled("RL010"));
    }

    #[test]
    fn test_suggest_config_matches_pattern() {
        assert!(SuggestConfig::matches_pattern("*", "anything"));
        assert!(SuggestConfig::matches_pattern("RL*", "RL001"));
        assert!(SuggestConfig::matches_pattern("RL*", "RL999"));
        assert!(!SuggestConfig::matches_pattern("RL*", "XX001"));
        assert!(SuggestConfig::matches_pattern("*001", "RL001"));
        assert!(!SuggestConfig::matches_pattern("*001", "RL002"));
        assert!(SuggestConfig::matches_pattern("RL001", "RL001"));
        assert!(!SuggestConfig::matches_pattern("RL001", "RL002"));
    }

    #[test]
    fn test_suggest_config_severity_overrides() {
        let mut overrides = std::collections::HashMap::new();
        overrides.insert("RL001".to_string(), "Error".to_string());
        overrides.insert("RL090".to_string(), "Warning".to_string());

        let config = SuggestConfig {
            severity_overrides: overrides,
            ..Default::default()
        };

        // Override exists
        assert_eq!(config.get_severity_override("RL001"), Some("Error"));
        assert_eq!(config.get_severity_override("RL090"), Some("Warning"));

        // No override
        assert_eq!(config.get_severity_override("RL002"), None);
    }

    #[test]
    fn test_suggest_config_severity_parse() {
        let toml = r#"
[suggest]
severity_overrides = { "RL001" = "Error", "RL021" = "Info" }
"#;
        let config: crate::config::RyoConfig = toml::from_str(toml).unwrap();
        assert_eq!(config.suggest.get_severity_override("RL001"), Some("Error"));
        assert_eq!(config.suggest.get_severity_override("RL021"), Some("Info"));
        assert_eq!(config.suggest.get_severity_override("RL999"), None);
    }

    // ========== SymbolPath pattern matching tests ==========

    #[test]
    fn test_matches_symbol_path_pattern_exact() {
        // Exact match
        assert!(RyoConfig::matches_symbol_path_pattern(
            "my_crate::module::Symbol",
            "my_crate::module::Symbol"
        ));
        // Not exact match
        assert!(!RyoConfig::matches_symbol_path_pattern(
            "my_crate::module::Symbol",
            "my_crate::module::Other"
        ));
        // Different depth
        assert!(!RyoConfig::matches_symbol_path_pattern(
            "my_crate::module",
            "my_crate::module::Symbol"
        ));
    }

    #[test]
    fn test_matches_symbol_path_pattern_trailing_wildcard() {
        // Trailing * matches any suffix
        assert!(RyoConfig::matches_symbol_path_pattern(
            "my_crate::generated::*",
            "my_crate::generated::Foo"
        ));
        assert!(RyoConfig::matches_symbol_path_pattern(
            "my_crate::generated::*",
            "my_crate::generated::sub::Bar"
        ));
        // Must match prefix
        assert!(!RyoConfig::matches_symbol_path_pattern(
            "my_crate::generated::*",
            "my_crate::other::Foo"
        ));
        // Pattern shorter than path with trailing wildcard
        assert!(RyoConfig::matches_symbol_path_pattern(
            "my_crate::*",
            "my_crate::module::sub::Symbol"
        ));
    }

    #[test]
    fn test_matches_symbol_path_pattern_segment_wildcard() {
        // * in middle matches any segment
        assert!(RyoConfig::matches_symbol_path_pattern(
            "*::tests::*",
            "my_crate::tests::test_foo"
        ));
        assert!(RyoConfig::matches_symbol_path_pattern(
            "*::tests::*",
            "other_crate::tests::test_bar"
        ));
        // Must have same structure
        assert!(!RyoConfig::matches_symbol_path_pattern(
            "*::tests::*",
            "my_crate::module::Symbol"
        ));
        // Wildcard at start
        assert!(RyoConfig::matches_symbol_path_pattern(
            "*::generated::Foo",
            "any_crate::generated::Foo"
        ));
    }

    #[test]
    fn test_get_module_config_for_symbol_exact() {
        let toml = r#"
[modules."my_crate::generated"]
skip_lint = true
disabled_rules = ["RL001"]
"#;
        let config: RyoConfig = toml::from_str(toml).unwrap();

        // Exact match
        let module_config = config.get_module_config_for_symbol("my_crate::generated");
        assert!(module_config.is_some());
        assert!(module_config.unwrap().skip_lint);

        // No match for deeper path without wildcard
        let no_match = config.get_module_config_for_symbol("my_crate::generated::Foo");
        assert!(no_match.is_none());
    }

    #[test]
    fn test_get_module_config_for_symbol_with_wildcard() {
        let toml = r#"
[modules."my_crate::generated::*"]
skip_lint = true
disabled_rules = ["RL090", "RL091"]
"#;
        let config: RyoConfig = toml::from_str(toml).unwrap();

        // Wildcard matches
        let module_config = config.get_module_config_for_symbol("my_crate::generated::Foo");
        assert!(module_config.is_some());
        assert!(module_config.unwrap().skip_lint);

        // Deeper paths also match
        let deep = config.get_module_config_for_symbol("my_crate::generated::sub::Bar");
        assert!(deep.is_some());

        // No match outside generated
        let no_match = config.get_module_config_for_symbol("my_crate::other::Foo");
        assert!(no_match.is_none());
    }

    #[test]
    fn test_get_module_config_file_path_vs_symbol_path() {
        let toml = r#"
[modules."src/generated"]
skip_lint = true

[modules."my_crate::generated::*"]
skip_refactor = true
"#;
        let config: RyoConfig = toml::from_str(toml).unwrap();

        // File path should only match file paths
        let file_config = config.get_module_config("src/generated/foo.rs");
        assert!(file_config.is_some());
        assert!(file_config.unwrap().skip_lint);
        assert!(!file_config.unwrap().skip_refactor);

        // SymbolPath should only match symbol paths
        let symbol_config = config.get_module_config_for_symbol("my_crate::generated::Foo");
        assert!(symbol_config.is_some());
        assert!(symbol_config.unwrap().skip_refactor);
        assert!(!symbol_config.unwrap().skip_lint);

        // File path method should not match SymbolPath patterns
        let no_file_match = config.get_module_config("my_crate::generated::Foo");
        assert!(no_file_match.is_none());

        // SymbolPath method should not match file path patterns
        let no_symbol_match = config.get_module_config_for_symbol("src/generated/foo.rs");
        assert!(no_symbol_match.is_none());
    }

    #[test]
    fn test_is_rule_enabled_for_symbol_module_override() {
        let toml = r#"
[suggest]
disabled_rules = ["RL001"]

[modules."my_crate::generated::*"]
disabled_rules = ["RL090", "RL091"]
"#;
        let config: RyoConfig = toml::from_str(toml).unwrap();

        // Global disabled rule
        assert!(!config.is_rule_enabled_for_symbol("any::path", "RL001"));

        // Module-level disabled rule
        assert!(!config.is_rule_enabled_for_symbol("my_crate::generated::Foo", "RL090"));
        assert!(!config.is_rule_enabled_for_symbol("my_crate::generated::Foo", "RL091"));

        // Rule not disabled for this symbol
        assert!(config.is_rule_enabled_for_symbol("my_crate::generated::Foo", "RL002"));

        // Outside generated module, RL090 is enabled
        assert!(config.is_rule_enabled_for_symbol("my_crate::other::Bar", "RL090"));
    }

    #[test]
    fn test_is_rule_enabled_for_symbol_with_enabled_rules() {
        let toml = r#"
[modules."my_crate::special::*"]
enabled_rules = ["RL001", "RL002"]
"#;
        let config: RyoConfig = toml::from_str(toml).unwrap();

        // Only RL001 and RL002 are enabled in special module
        assert!(config.is_rule_enabled_for_symbol("my_crate::special::Foo", "RL001"));
        assert!(config.is_rule_enabled_for_symbol("my_crate::special::Foo", "RL002"));
        assert!(!config.is_rule_enabled_for_symbol("my_crate::special::Foo", "RL003"));

        // Outside special module, all rules enabled (by global config)
        assert!(config.is_rule_enabled_for_symbol("my_crate::other::Bar", "RL003"));
    }

    #[test]
    fn test_module_config_disabled_rules_with_wildcard() {
        let toml = r#"
[modules."*::tests::*"]
disabled_rules = ["RL*"]
"#;
        let config: RyoConfig = toml::from_str(toml).unwrap();

        // All RL rules disabled in test modules
        assert!(!config.is_rule_enabled_for_symbol("my_crate::tests::test_foo", "RL001"));
        assert!(!config.is_rule_enabled_for_symbol("other::tests::test_bar", "RL999"));

        // Outside test modules, rules are enabled
        assert!(config.is_rule_enabled_for_symbol("my_crate::lib::Foo", "RL001"));
    }
}