rumdl_lib/
config.rs

1//!
2//! This module defines configuration structures, loading logic, and provenance tracking for rumdl.
3//! Supports TOML, pyproject.toml, and markdownlint config formats, and provides merging and override logic.
4
5use crate::rule::Rule;
6use crate::rules;
7use crate::types::LineLength;
8use log;
9use serde::{Deserialize, Serialize};
10use std::collections::BTreeMap;
11use std::collections::{HashMap, HashSet};
12use std::fmt;
13use std::fs;
14use std::io;
15use std::marker::PhantomData;
16use std::path::Path;
17use std::str::FromStr;
18use toml_edit::DocumentMut;
19
20// ============================================================================
21// Typestate markers for configuration pipeline
22// ============================================================================
23
24/// Marker type for configuration that has been loaded but not yet validated.
25/// This is the initial state after `load_with_discovery()`.
26#[derive(Debug, Clone, Copy, Default)]
27pub struct ConfigLoaded;
28
29/// Marker type for configuration that has been validated.
30/// Only validated configs can be converted to `Config`.
31#[derive(Debug, Clone, Copy, Default)]
32pub struct ConfigValidated;
33
34/// Markdown flavor/dialect enumeration
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, schemars::JsonSchema)]
36#[serde(rename_all = "lowercase")]
37pub enum MarkdownFlavor {
38    /// Standard Markdown without flavor-specific adjustments
39    #[serde(rename = "standard", alias = "none", alias = "")]
40    #[default]
41    Standard,
42    /// MkDocs flavor with auto-reference support
43    #[serde(rename = "mkdocs")]
44    MkDocs,
45    /// MDX flavor with JSX and ESM support (.mdx files)
46    #[serde(rename = "mdx")]
47    MDX,
48    /// Quarto/RMarkdown flavor for scientific publishing (.qmd, .Rmd files)
49    #[serde(rename = "quarto")]
50    Quarto,
51    // Future flavors can be added here when they have actual implementation differences
52    // Planned: GFM (GitHub Flavored Markdown) - for GitHub-specific features like tables, strikethrough
53    // Planned: CommonMark - for strict CommonMark compliance
54}
55
56impl fmt::Display for MarkdownFlavor {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        match self {
59            MarkdownFlavor::Standard => write!(f, "standard"),
60            MarkdownFlavor::MkDocs => write!(f, "mkdocs"),
61            MarkdownFlavor::MDX => write!(f, "mdx"),
62            MarkdownFlavor::Quarto => write!(f, "quarto"),
63        }
64    }
65}
66
67impl FromStr for MarkdownFlavor {
68    type Err = String;
69
70    fn from_str(s: &str) -> Result<Self, Self::Err> {
71        match s.to_lowercase().as_str() {
72            "standard" | "" | "none" => Ok(MarkdownFlavor::Standard),
73            "mkdocs" => Ok(MarkdownFlavor::MkDocs),
74            "mdx" => Ok(MarkdownFlavor::MDX),
75            "quarto" | "qmd" | "rmd" | "rmarkdown" => Ok(MarkdownFlavor::Quarto),
76            // GFM and CommonMark are aliases for Standard since the base parser
77            // (pulldown-cmark) already supports GFM extensions (tables, task lists,
78            // strikethrough, autolinks, etc.) which are a superset of CommonMark
79            "gfm" | "github" | "commonmark" => Ok(MarkdownFlavor::Standard),
80            _ => Err(format!("Unknown markdown flavor: {s}")),
81        }
82    }
83}
84
85impl MarkdownFlavor {
86    /// Detect flavor from file extension
87    pub fn from_extension(ext: &str) -> Self {
88        match ext.to_lowercase().as_str() {
89            "mdx" => Self::MDX,
90            "qmd" => Self::Quarto,
91            "rmd" => Self::Quarto,
92            _ => Self::Standard,
93        }
94    }
95
96    /// Detect flavor from file path
97    pub fn from_path(path: &std::path::Path) -> Self {
98        path.extension()
99            .and_then(|e| e.to_str())
100            .map(Self::from_extension)
101            .unwrap_or(Self::Standard)
102    }
103
104    /// Check if this flavor supports ESM imports/exports (MDX-specific)
105    pub fn supports_esm_blocks(self) -> bool {
106        matches!(self, Self::MDX)
107    }
108
109    /// Check if this flavor supports JSX components (MDX-specific)
110    pub fn supports_jsx(self) -> bool {
111        matches!(self, Self::MDX)
112    }
113
114    /// Check if this flavor supports auto-references (MkDocs-specific)
115    pub fn supports_auto_references(self) -> bool {
116        matches!(self, Self::MkDocs)
117    }
118
119    /// Get a human-readable name for this flavor
120    pub fn name(self) -> &'static str {
121        match self {
122            Self::Standard => "Standard",
123            Self::MkDocs => "MkDocs",
124            Self::MDX => "MDX",
125            Self::Quarto => "Quarto",
126        }
127    }
128}
129
130/// Normalizes configuration keys (rule names, option names) to lowercase kebab-case.
131pub fn normalize_key(key: &str) -> String {
132    // If the key looks like a rule name (e.g., MD013), uppercase it
133    if key.len() == 5 && key.to_ascii_lowercase().starts_with("md") && key[2..].chars().all(|c| c.is_ascii_digit()) {
134        key.to_ascii_uppercase()
135    } else {
136        key.replace('_', "-").to_ascii_lowercase()
137    }
138}
139
140/// Represents a rule-specific configuration
141#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, schemars::JsonSchema)]
142pub struct RuleConfig {
143    /// Severity override for this rule (Error, Warning, or Info)
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub severity: Option<crate::rule::Severity>,
146
147    /// Configuration values for the rule
148    #[serde(flatten)]
149    #[schemars(schema_with = "arbitrary_value_schema")]
150    pub values: BTreeMap<String, toml::Value>,
151}
152
153/// Generate a JSON schema for arbitrary configuration values
154fn arbitrary_value_schema(_gen: &mut schemars::SchemaGenerator) -> schemars::Schema {
155    schemars::json_schema!({
156        "type": "object",
157        "additionalProperties": true
158    })
159}
160
161/// Represents the complete configuration loaded from rumdl.toml
162#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, schemars::JsonSchema)]
163#[schemars(
164    description = "rumdl configuration for linting Markdown files. Rules can be configured individually using [MD###] sections with rule-specific options."
165)]
166pub struct Config {
167    /// Global configuration options
168    #[serde(default)]
169    pub global: GlobalConfig,
170
171    /// Per-file rule ignores: maps file patterns to lists of rules to ignore
172    /// Example: { "README.md": ["MD033"], "docs/**/*.md": ["MD013"] }
173    #[serde(default, rename = "per-file-ignores")]
174    pub per_file_ignores: HashMap<String, Vec<String>>,
175
176    /// Rule-specific configurations (e.g., MD013, MD007, MD044)
177    /// Each rule section can contain options specific to that rule.
178    ///
179    /// Common examples:
180    /// - MD013: line_length, code_blocks, tables, headings
181    /// - MD007: indent
182    /// - MD003: style ("atx", "atx_closed", "setext")
183    /// - MD044: names (array of proper names to check)
184    ///
185    /// See https://github.com/rvben/rumdl for full rule documentation.
186    #[serde(flatten)]
187    pub rules: BTreeMap<String, RuleConfig>,
188
189    /// Project root directory, used for resolving relative paths in per-file-ignores
190    #[serde(skip)]
191    pub project_root: Option<std::path::PathBuf>,
192}
193
194impl Config {
195    /// Check if the Markdown flavor is set to MkDocs
196    pub fn is_mkdocs_flavor(&self) -> bool {
197        self.global.flavor == MarkdownFlavor::MkDocs
198    }
199
200    // Future methods for when GFM and CommonMark are implemented:
201    // pub fn is_gfm_flavor(&self) -> bool
202    // pub fn is_commonmark_flavor(&self) -> bool
203
204    /// Get the configured Markdown flavor
205    pub fn markdown_flavor(&self) -> MarkdownFlavor {
206        self.global.flavor
207    }
208
209    /// Legacy method for backwards compatibility - redirects to is_mkdocs_flavor
210    pub fn is_mkdocs_project(&self) -> bool {
211        self.is_mkdocs_flavor()
212    }
213
214    /// Get the severity override for a specific rule, if configured
215    pub fn get_rule_severity(&self, rule_name: &str) -> Option<crate::rule::Severity> {
216        self.rules.get(rule_name).and_then(|r| r.severity)
217    }
218
219    /// Get the set of rules that should be ignored for a specific file based on per-file-ignores configuration
220    /// Returns a HashSet of rule names (uppercase, e.g., "MD033") that match the given file path
221    pub fn get_ignored_rules_for_file(&self, file_path: &Path) -> HashSet<String> {
222        use globset::{Glob, GlobSetBuilder};
223
224        let mut ignored_rules = HashSet::new();
225
226        if self.per_file_ignores.is_empty() {
227            return ignored_rules;
228        }
229
230        // Normalize the file path to be relative to project_root for pattern matching
231        // This ensures patterns like ".github/file.md" work with absolute paths
232        let path_for_matching: std::borrow::Cow<'_, Path> = if let Some(ref root) = self.project_root {
233            if let Ok(canonical_path) = file_path.canonicalize() {
234                if let Ok(canonical_root) = root.canonicalize() {
235                    if let Ok(relative) = canonical_path.strip_prefix(&canonical_root) {
236                        std::borrow::Cow::Owned(relative.to_path_buf())
237                    } else {
238                        std::borrow::Cow::Borrowed(file_path)
239                    }
240                } else {
241                    std::borrow::Cow::Borrowed(file_path)
242                }
243            } else {
244                std::borrow::Cow::Borrowed(file_path)
245            }
246        } else {
247            std::borrow::Cow::Borrowed(file_path)
248        };
249
250        // Build a globset for efficient matching
251        let mut builder = GlobSetBuilder::new();
252        let mut pattern_to_rules: Vec<(usize, &Vec<String>)> = Vec::new();
253
254        for (idx, (pattern, rules)) in self.per_file_ignores.iter().enumerate() {
255            if let Ok(glob) = Glob::new(pattern) {
256                builder.add(glob);
257                pattern_to_rules.push((idx, rules));
258            } else {
259                log::warn!("Invalid glob pattern in per-file-ignores: {pattern}");
260            }
261        }
262
263        let globset = match builder.build() {
264            Ok(gs) => gs,
265            Err(e) => {
266                log::error!("Failed to build globset for per-file-ignores: {e}");
267                return ignored_rules;
268            }
269        };
270
271        // Match the file path against all patterns
272        for match_idx in globset.matches(path_for_matching.as_ref()) {
273            if let Some((_, rules)) = pattern_to_rules.get(match_idx) {
274                for rule in rules.iter() {
275                    // Normalize rule names to uppercase (MD033, md033 -> MD033)
276                    ignored_rules.insert(normalize_key(rule));
277                }
278            }
279        }
280
281        ignored_rules
282    }
283}
284
285/// Global configuration options
286#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
287#[serde(default, rename_all = "kebab-case")]
288pub struct GlobalConfig {
289    /// Enabled rules
290    #[serde(default)]
291    pub enable: Vec<String>,
292
293    /// Disabled rules
294    #[serde(default)]
295    pub disable: Vec<String>,
296
297    /// Files to exclude
298    #[serde(default)]
299    pub exclude: Vec<String>,
300
301    /// Files to include
302    #[serde(default)]
303    pub include: Vec<String>,
304
305    /// Respect .gitignore files when scanning directories
306    #[serde(default = "default_respect_gitignore", alias = "respect_gitignore")]
307    pub respect_gitignore: bool,
308
309    /// Global line length setting (used by MD013 and other rules if not overridden)
310    #[serde(default, alias = "line_length")]
311    pub line_length: LineLength,
312
313    /// Output format for linting results (e.g., "text", "json", "pylint", etc.)
314    #[serde(skip_serializing_if = "Option::is_none", alias = "output_format")]
315    pub output_format: Option<String>,
316
317    /// Rules that are allowed to be fixed when --fix is used
318    /// If specified, only these rules will be fixed
319    #[serde(default)]
320    pub fixable: Vec<String>,
321
322    /// Rules that should never be fixed, even when --fix is used
323    /// Takes precedence over fixable
324    #[serde(default)]
325    pub unfixable: Vec<String>,
326
327    /// Markdown flavor/dialect to use (mkdocs, gfm, commonmark, etc.)
328    /// When set, adjusts parsing and validation rules for that specific Markdown variant
329    #[serde(default)]
330    pub flavor: MarkdownFlavor,
331
332    /// [DEPRECATED] Whether to enforce exclude patterns for explicitly passed paths.
333    /// This option is deprecated as of v0.0.156 and has no effect.
334    /// Exclude patterns are now always respected, even for explicitly provided files.
335    /// This prevents duplication between rumdl config and tool configs like pre-commit.
336    #[serde(default, alias = "force_exclude")]
337    #[deprecated(since = "0.0.156", note = "Exclude patterns are now always respected")]
338    pub force_exclude: bool,
339
340    /// Directory to store cache files (default: .rumdl_cache)
341    /// Can also be set via --cache-dir CLI flag or RUMDL_CACHE_DIR environment variable
342    #[serde(default, alias = "cache_dir", skip_serializing_if = "Option::is_none")]
343    pub cache_dir: Option<String>,
344
345    /// Whether caching is enabled (default: true)
346    /// Can also be disabled via --no-cache CLI flag
347    #[serde(default = "default_true")]
348    pub cache: bool,
349}
350
351fn default_respect_gitignore() -> bool {
352    true
353}
354
355fn default_true() -> bool {
356    true
357}
358
359// Add the Default impl
360impl Default for GlobalConfig {
361    #[allow(deprecated)]
362    fn default() -> Self {
363        Self {
364            enable: Vec::new(),
365            disable: Vec::new(),
366            exclude: Vec::new(),
367            include: Vec::new(),
368            respect_gitignore: true,
369            line_length: LineLength::default(),
370            output_format: None,
371            fixable: Vec::new(),
372            unfixable: Vec::new(),
373            flavor: MarkdownFlavor::default(),
374            force_exclude: false,
375            cache_dir: None,
376            cache: true,
377        }
378    }
379}
380
381const MARKDOWNLINT_CONFIG_FILES: &[&str] = &[
382    ".markdownlint.json",
383    ".markdownlint.jsonc",
384    ".markdownlint.yaml",
385    ".markdownlint.yml",
386    "markdownlint.json",
387    "markdownlint.jsonc",
388    "markdownlint.yaml",
389    "markdownlint.yml",
390];
391
392/// Create a default configuration file at the specified path
393pub fn create_default_config(path: &str) -> Result<(), ConfigError> {
394    // Check if file already exists
395    if Path::new(path).exists() {
396        return Err(ConfigError::FileExists { path: path.to_string() });
397    }
398
399    // Default configuration content
400    let default_config = r#"# rumdl configuration file
401
402# Global configuration options
403[global]
404# List of rules to disable (uncomment and modify as needed)
405# disable = ["MD013", "MD033"]
406
407# List of rules to enable exclusively (if provided, only these rules will run)
408# enable = ["MD001", "MD003", "MD004"]
409
410# List of file/directory patterns to include for linting (if provided, only these will be linted)
411# include = [
412#    "docs/*.md",
413#    "src/**/*.md",
414#    "README.md"
415# ]
416
417# List of file/directory patterns to exclude from linting
418exclude = [
419    # Common directories to exclude
420    ".git",
421    ".github",
422    "node_modules",
423    "vendor",
424    "dist",
425    "build",
426
427    # Specific files or patterns
428    "CHANGELOG.md",
429    "LICENSE.md",
430]
431
432# Respect .gitignore files when scanning directories (default: true)
433respect-gitignore = true
434
435# Markdown flavor/dialect (uncomment to enable)
436# Options: standard (default), gfm, commonmark, mkdocs, mdx, quarto
437# flavor = "mkdocs"
438
439# Rule-specific configurations (uncomment and modify as needed)
440
441# [MD003]
442# style = "atx"  # Heading style (atx, atx_closed, setext)
443
444# [MD004]
445# style = "asterisk"  # Unordered list style (asterisk, plus, dash, consistent)
446
447# [MD007]
448# indent = 4  # Unordered list indentation
449
450# [MD013]
451# line-length = 100  # Line length
452# code-blocks = false  # Exclude code blocks from line length check
453# tables = false  # Exclude tables from line length check
454# headings = true  # Include headings in line length check
455
456# [MD044]
457# names = ["rumdl", "Markdown", "GitHub"]  # Proper names that should be capitalized correctly
458# code-blocks = false  # Check code blocks for proper names (default: false, skips code blocks)
459"#;
460
461    // Write the default configuration to the file
462    match fs::write(path, default_config) {
463        Ok(_) => Ok(()),
464        Err(err) => Err(ConfigError::IoError {
465            source: err,
466            path: path.to_string(),
467        }),
468    }
469}
470
471/// Errors that can occur when loading configuration
472#[derive(Debug, thiserror::Error)]
473pub enum ConfigError {
474    /// Failed to read the configuration file
475    #[error("Failed to read config file at {path}: {source}")]
476    IoError { source: io::Error, path: String },
477
478    /// Failed to parse the configuration content (TOML or JSON)
479    #[error("Failed to parse config: {0}")]
480    ParseError(String),
481
482    /// Configuration file already exists
483    #[error("Configuration file already exists at {path}")]
484    FileExists { path: String },
485}
486
487/// Get a rule-specific configuration value
488/// Automatically tries both the original key and normalized variants (kebab-case ↔ snake_case)
489/// for better markdownlint compatibility
490pub fn get_rule_config_value<T: serde::de::DeserializeOwned>(config: &Config, rule_name: &str, key: &str) -> Option<T> {
491    let norm_rule_name = rule_name.to_ascii_uppercase(); // Use uppercase for lookup
492
493    let rule_config = config.rules.get(&norm_rule_name)?;
494
495    // Try multiple key variants to support both underscore and kebab-case formats
496    let key_variants = [
497        key.to_string(),       // Original key as provided
498        normalize_key(key),    // Normalized key (lowercase, kebab-case)
499        key.replace('-', "_"), // Convert kebab-case to snake_case
500        key.replace('_', "-"), // Convert snake_case to kebab-case
501    ];
502
503    // Try each variant until we find a match
504    for variant in &key_variants {
505        if let Some(value) = rule_config.values.get(variant)
506            && let Ok(result) = T::deserialize(value.clone())
507        {
508            return Some(result);
509        }
510    }
511
512    None
513}
514
515/// Generate default rumdl configuration for pyproject.toml
516pub fn generate_pyproject_config() -> String {
517    let config_content = r#"
518[tool.rumdl]
519# Global configuration options
520line-length = 100
521disable = []
522exclude = [
523    # Common directories to exclude
524    ".git",
525    ".github",
526    "node_modules",
527    "vendor",
528    "dist",
529    "build",
530]
531respect-gitignore = true
532
533# Rule-specific configurations (uncomment and modify as needed)
534
535# [tool.rumdl.MD003]
536# style = "atx"  # Heading style (atx, atx_closed, setext)
537
538# [tool.rumdl.MD004]
539# style = "asterisk"  # Unordered list style (asterisk, plus, dash, consistent)
540
541# [tool.rumdl.MD007]
542# indent = 4  # Unordered list indentation
543
544# [tool.rumdl.MD013]
545# line-length = 100  # Line length
546# code-blocks = false  # Exclude code blocks from line length check
547# tables = false  # Exclude tables from line length check
548# headings = true  # Include headings in line length check
549
550# [tool.rumdl.MD044]
551# names = ["rumdl", "Markdown", "GitHub"]  # Proper names that should be capitalized correctly
552# code-blocks = false  # Check code blocks for proper names (default: false, skips code blocks)
553"#;
554
555    config_content.to_string()
556}
557
558#[cfg(test)]
559mod tests {
560    use super::*;
561    use std::fs;
562    use tempfile::tempdir;
563
564    #[test]
565    fn test_flavor_loading() {
566        let temp_dir = tempdir().unwrap();
567        let config_path = temp_dir.path().join(".rumdl.toml");
568        let config_content = r#"
569[global]
570flavor = "mkdocs"
571disable = ["MD001"]
572"#;
573        fs::write(&config_path, config_content).unwrap();
574
575        // Load the config
576        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
577        let config: Config = sourced.into_validated_unchecked().into();
578
579        // Check that flavor was loaded
580        assert_eq!(config.global.flavor, MarkdownFlavor::MkDocs);
581        assert!(config.is_mkdocs_flavor());
582        assert!(config.is_mkdocs_project()); // Test backwards compatibility
583        assert_eq!(config.global.disable, vec!["MD001".to_string()]);
584    }
585
586    #[test]
587    fn test_pyproject_toml_root_level_config() {
588        let temp_dir = tempdir().unwrap();
589        let config_path = temp_dir.path().join("pyproject.toml");
590
591        // Create a test pyproject.toml with root-level configuration
592        let content = r#"
593[tool.rumdl]
594line-length = 120
595disable = ["MD033"]
596enable = ["MD001", "MD004"]
597include = ["docs/*.md"]
598exclude = ["node_modules"]
599respect-gitignore = true
600        "#;
601
602        fs::write(&config_path, content).unwrap();
603
604        // Load the config with skip_auto_discovery to avoid environment config files
605        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
606        let config: Config = sourced.into_validated_unchecked().into(); // Convert to plain config for assertions
607
608        // Check global settings
609        assert_eq!(config.global.disable, vec!["MD033".to_string()]);
610        assert_eq!(config.global.enable, vec!["MD001".to_string(), "MD004".to_string()]);
611        // Should now contain only the configured pattern since auto-discovery is disabled
612        assert_eq!(config.global.include, vec!["docs/*.md".to_string()]);
613        assert_eq!(config.global.exclude, vec!["node_modules".to_string()]);
614        assert!(config.global.respect_gitignore);
615
616        // Check line-length was correctly added to MD013
617        let line_length = get_rule_config_value::<usize>(&config, "MD013", "line-length");
618        assert_eq!(line_length, Some(120));
619    }
620
621    #[test]
622    fn test_pyproject_toml_snake_case_and_kebab_case() {
623        let temp_dir = tempdir().unwrap();
624        let config_path = temp_dir.path().join("pyproject.toml");
625
626        // Test with both kebab-case and snake_case variants
627        let content = r#"
628[tool.rumdl]
629line-length = 150
630respect_gitignore = true
631        "#;
632
633        fs::write(&config_path, content).unwrap();
634
635        // Load the config with skip_auto_discovery to avoid environment config files
636        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
637        let config: Config = sourced.into_validated_unchecked().into(); // Convert to plain config for assertions
638
639        // Check settings were correctly loaded
640        assert!(config.global.respect_gitignore);
641        let line_length = get_rule_config_value::<usize>(&config, "MD013", "line-length");
642        assert_eq!(line_length, Some(150));
643    }
644
645    #[test]
646    fn test_md013_key_normalization_in_rumdl_toml() {
647        let temp_dir = tempdir().unwrap();
648        let config_path = temp_dir.path().join(".rumdl.toml");
649        let config_content = r#"
650[MD013]
651line_length = 111
652line-length = 222
653"#;
654        fs::write(&config_path, config_content).unwrap();
655        // Load the config with skip_auto_discovery to avoid environment config files
656        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
657        let rule_cfg = sourced.rules.get("MD013").expect("MD013 rule config should exist");
658        // Now we should only get the explicitly configured key
659        let keys: Vec<_> = rule_cfg.values.keys().cloned().collect();
660        assert_eq!(keys, vec!["line-length"]);
661        let val = &rule_cfg.values["line-length"].value;
662        assert_eq!(val.as_integer(), Some(222));
663        // get_rule_config_value should retrieve the value for both snake_case and kebab-case
664        let config: Config = sourced.clone().into_validated_unchecked().into();
665        let v1 = get_rule_config_value::<usize>(&config, "MD013", "line_length");
666        let v2 = get_rule_config_value::<usize>(&config, "MD013", "line-length");
667        assert_eq!(v1, Some(222));
668        assert_eq!(v2, Some(222));
669    }
670
671    #[test]
672    fn test_md013_section_case_insensitivity() {
673        let temp_dir = tempdir().unwrap();
674        let config_path = temp_dir.path().join(".rumdl.toml");
675        let config_content = r#"
676[md013]
677line-length = 101
678
679[Md013]
680line-length = 102
681
682[MD013]
683line-length = 103
684"#;
685        fs::write(&config_path, config_content).unwrap();
686        // Load the config with skip_auto_discovery to avoid environment config files
687        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
688        let config: Config = sourced.clone().into_validated_unchecked().into();
689        // Only the last section should win, and be present
690        let rule_cfg = sourced.rules.get("MD013").expect("MD013 rule config should exist");
691        let keys: Vec<_> = rule_cfg.values.keys().cloned().collect();
692        assert_eq!(keys, vec!["line-length"]);
693        let val = &rule_cfg.values["line-length"].value;
694        assert_eq!(val.as_integer(), Some(103));
695        let v = get_rule_config_value::<usize>(&config, "MD013", "line-length");
696        assert_eq!(v, Some(103));
697    }
698
699    #[test]
700    fn test_md013_key_snake_and_kebab_case() {
701        let temp_dir = tempdir().unwrap();
702        let config_path = temp_dir.path().join(".rumdl.toml");
703        let config_content = r#"
704[MD013]
705line_length = 201
706line-length = 202
707"#;
708        fs::write(&config_path, config_content).unwrap();
709        // Load the config with skip_auto_discovery to avoid environment config files
710        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
711        let config: Config = sourced.clone().into_validated_unchecked().into();
712        let rule_cfg = sourced.rules.get("MD013").expect("MD013 rule config should exist");
713        let keys: Vec<_> = rule_cfg.values.keys().cloned().collect();
714        assert_eq!(keys, vec!["line-length"]);
715        let val = &rule_cfg.values["line-length"].value;
716        assert_eq!(val.as_integer(), Some(202));
717        let v1 = get_rule_config_value::<usize>(&config, "MD013", "line_length");
718        let v2 = get_rule_config_value::<usize>(&config, "MD013", "line-length");
719        assert_eq!(v1, Some(202));
720        assert_eq!(v2, Some(202));
721    }
722
723    #[test]
724    fn test_unknown_rule_section_is_ignored() {
725        let temp_dir = tempdir().unwrap();
726        let config_path = temp_dir.path().join(".rumdl.toml");
727        let config_content = r#"
728[MD999]
729foo = 1
730bar = 2
731[MD013]
732line-length = 303
733"#;
734        fs::write(&config_path, config_content).unwrap();
735        // Load the config with skip_auto_discovery to avoid environment config files
736        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
737        let config: Config = sourced.clone().into_validated_unchecked().into();
738        // MD999 should not be present
739        assert!(!sourced.rules.contains_key("MD999"));
740        // MD013 should be present and correct
741        let v = get_rule_config_value::<usize>(&config, "MD013", "line-length");
742        assert_eq!(v, Some(303));
743    }
744
745    #[test]
746    fn test_invalid_toml_syntax() {
747        let temp_dir = tempdir().unwrap();
748        let config_path = temp_dir.path().join(".rumdl.toml");
749
750        // Invalid TOML with unclosed string
751        let config_content = r#"
752[MD013]
753line-length = "unclosed string
754"#;
755        fs::write(&config_path, config_content).unwrap();
756
757        let result = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true);
758        assert!(result.is_err());
759        match result.unwrap_err() {
760            ConfigError::ParseError(msg) => {
761                // The actual error message from toml parser might vary
762                assert!(msg.contains("expected") || msg.contains("invalid") || msg.contains("unterminated"));
763            }
764            _ => panic!("Expected ParseError"),
765        }
766    }
767
768    #[test]
769    fn test_wrong_type_for_config_value() {
770        let temp_dir = tempdir().unwrap();
771        let config_path = temp_dir.path().join(".rumdl.toml");
772
773        // line-length should be a number, not a string
774        let config_content = r#"
775[MD013]
776line-length = "not a number"
777"#;
778        fs::write(&config_path, config_content).unwrap();
779
780        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
781        let config: Config = sourced.into_validated_unchecked().into();
782
783        // The value should be loaded as a string, not converted
784        let rule_config = config.rules.get("MD013").unwrap();
785        let value = rule_config.values.get("line-length").unwrap();
786        assert!(matches!(value, toml::Value::String(_)));
787    }
788
789    #[test]
790    fn test_empty_config_file() {
791        let temp_dir = tempdir().unwrap();
792        let config_path = temp_dir.path().join(".rumdl.toml");
793
794        // Empty file
795        fs::write(&config_path, "").unwrap();
796
797        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
798        let config: Config = sourced.into_validated_unchecked().into();
799
800        // Should have default values
801        assert_eq!(config.global.line_length.get(), 80);
802        assert!(config.global.respect_gitignore);
803        assert!(config.rules.is_empty());
804    }
805
806    #[test]
807    fn test_malformed_pyproject_toml() {
808        let temp_dir = tempdir().unwrap();
809        let config_path = temp_dir.path().join("pyproject.toml");
810
811        // Missing closing bracket
812        let content = r#"
813[tool.rumdl
814line-length = 120
815"#;
816        fs::write(&config_path, content).unwrap();
817
818        let result = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true);
819        assert!(result.is_err());
820    }
821
822    #[test]
823    fn test_conflicting_config_values() {
824        let temp_dir = tempdir().unwrap();
825        let config_path = temp_dir.path().join(".rumdl.toml");
826
827        // Both enable and disable the same rule - these need to be in a global section
828        let config_content = r#"
829[global]
830enable = ["MD013"]
831disable = ["MD013"]
832"#;
833        fs::write(&config_path, config_content).unwrap();
834
835        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
836        let config: Config = sourced.into_validated_unchecked().into();
837
838        // Conflict resolution: enable wins over disable
839        assert!(config.global.enable.contains(&"MD013".to_string()));
840        assert!(!config.global.disable.contains(&"MD013".to_string()));
841    }
842
843    #[test]
844    fn test_invalid_rule_names() {
845        let temp_dir = tempdir().unwrap();
846        let config_path = temp_dir.path().join(".rumdl.toml");
847
848        let config_content = r#"
849[global]
850enable = ["MD001", "NOT_A_RULE", "md002", "12345"]
851disable = ["MD-001", "MD_002"]
852"#;
853        fs::write(&config_path, config_content).unwrap();
854
855        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
856        let config: Config = sourced.into_validated_unchecked().into();
857
858        // All values should be preserved as-is
859        assert_eq!(config.global.enable.len(), 4);
860        assert_eq!(config.global.disable.len(), 2);
861    }
862
863    #[test]
864    fn test_deeply_nested_config() {
865        let temp_dir = tempdir().unwrap();
866        let config_path = temp_dir.path().join(".rumdl.toml");
867
868        // This should be ignored as we don't support nested tables within rule configs
869        let config_content = r#"
870[MD013]
871line-length = 100
872[MD013.nested]
873value = 42
874"#;
875        fs::write(&config_path, config_content).unwrap();
876
877        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
878        let config: Config = sourced.into_validated_unchecked().into();
879
880        let rule_config = config.rules.get("MD013").unwrap();
881        assert_eq!(
882            rule_config.values.get("line-length").unwrap(),
883            &toml::Value::Integer(100)
884        );
885        // Nested table should not be present
886        assert!(!rule_config.values.contains_key("nested"));
887    }
888
889    #[test]
890    fn test_unicode_in_config() {
891        let temp_dir = tempdir().unwrap();
892        let config_path = temp_dir.path().join(".rumdl.toml");
893
894        let config_content = r#"
895[global]
896include = ["文档/*.md", "ドキュメント/*.md"]
897exclude = ["测试/*", "🚀/*"]
898
899[MD013]
900line-length = 80
901message = "行太长了 🚨"
902"#;
903        fs::write(&config_path, config_content).unwrap();
904
905        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
906        let config: Config = sourced.into_validated_unchecked().into();
907
908        assert_eq!(config.global.include.len(), 2);
909        assert_eq!(config.global.exclude.len(), 2);
910        assert!(config.global.include[0].contains("文档"));
911        assert!(config.global.exclude[1].contains("🚀"));
912
913        let rule_config = config.rules.get("MD013").unwrap();
914        let message = rule_config.values.get("message").unwrap();
915        if let toml::Value::String(s) = message {
916            assert!(s.contains("行太长了"));
917            assert!(s.contains("🚨"));
918        }
919    }
920
921    #[test]
922    fn test_extremely_long_values() {
923        let temp_dir = tempdir().unwrap();
924        let config_path = temp_dir.path().join(".rumdl.toml");
925
926        let long_string = "a".repeat(10000);
927        let config_content = format!(
928            r#"
929[global]
930exclude = ["{long_string}"]
931
932[MD013]
933line-length = 999999999
934"#
935        );
936
937        fs::write(&config_path, config_content).unwrap();
938
939        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
940        let config: Config = sourced.into_validated_unchecked().into();
941
942        assert_eq!(config.global.exclude[0].len(), 10000);
943        let line_length = get_rule_config_value::<usize>(&config, "MD013", "line-length");
944        assert_eq!(line_length, Some(999999999));
945    }
946
947    #[test]
948    fn test_config_with_comments() {
949        let temp_dir = tempdir().unwrap();
950        let config_path = temp_dir.path().join(".rumdl.toml");
951
952        let config_content = r#"
953[global]
954# This is a comment
955enable = ["MD001"] # Enable MD001
956# disable = ["MD002"] # This is commented out
957
958[MD013] # Line length rule
959line-length = 100 # Set to 100 characters
960# ignored = true # This setting is commented out
961"#;
962        fs::write(&config_path, config_content).unwrap();
963
964        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
965        let config: Config = sourced.into_validated_unchecked().into();
966
967        assert_eq!(config.global.enable, vec!["MD001"]);
968        assert!(config.global.disable.is_empty()); // Commented out
969
970        let rule_config = config.rules.get("MD013").unwrap();
971        assert_eq!(rule_config.values.len(), 1); // Only line-length
972        assert!(!rule_config.values.contains_key("ignored"));
973    }
974
975    #[test]
976    fn test_arrays_in_rule_config() {
977        let temp_dir = tempdir().unwrap();
978        let config_path = temp_dir.path().join(".rumdl.toml");
979
980        let config_content = r#"
981[MD003]
982levels = [1, 2, 3]
983tags = ["important", "critical"]
984mixed = [1, "two", true]
985"#;
986        fs::write(&config_path, config_content).unwrap();
987
988        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
989        let config: Config = sourced.into_validated_unchecked().into();
990
991        // Arrays should now be properly parsed
992        let rule_config = config.rules.get("MD003").expect("MD003 config should exist");
993
994        // Check that arrays are present and correctly parsed
995        assert!(rule_config.values.contains_key("levels"));
996        assert!(rule_config.values.contains_key("tags"));
997        assert!(rule_config.values.contains_key("mixed"));
998
999        // Verify array contents
1000        if let Some(toml::Value::Array(levels)) = rule_config.values.get("levels") {
1001            assert_eq!(levels.len(), 3);
1002            assert_eq!(levels[0], toml::Value::Integer(1));
1003            assert_eq!(levels[1], toml::Value::Integer(2));
1004            assert_eq!(levels[2], toml::Value::Integer(3));
1005        } else {
1006            panic!("levels should be an array");
1007        }
1008
1009        if let Some(toml::Value::Array(tags)) = rule_config.values.get("tags") {
1010            assert_eq!(tags.len(), 2);
1011            assert_eq!(tags[0], toml::Value::String("important".to_string()));
1012            assert_eq!(tags[1], toml::Value::String("critical".to_string()));
1013        } else {
1014            panic!("tags should be an array");
1015        }
1016
1017        if let Some(toml::Value::Array(mixed)) = rule_config.values.get("mixed") {
1018            assert_eq!(mixed.len(), 3);
1019            assert_eq!(mixed[0], toml::Value::Integer(1));
1020            assert_eq!(mixed[1], toml::Value::String("two".to_string()));
1021            assert_eq!(mixed[2], toml::Value::Boolean(true));
1022        } else {
1023            panic!("mixed should be an array");
1024        }
1025    }
1026
1027    #[test]
1028    fn test_normalize_key_edge_cases() {
1029        // Rule names
1030        assert_eq!(normalize_key("MD001"), "MD001");
1031        assert_eq!(normalize_key("md001"), "MD001");
1032        assert_eq!(normalize_key("Md001"), "MD001");
1033        assert_eq!(normalize_key("mD001"), "MD001");
1034
1035        // Non-rule names
1036        assert_eq!(normalize_key("line_length"), "line-length");
1037        assert_eq!(normalize_key("line-length"), "line-length");
1038        assert_eq!(normalize_key("LINE_LENGTH"), "line-length");
1039        assert_eq!(normalize_key("respect_gitignore"), "respect-gitignore");
1040
1041        // Edge cases
1042        assert_eq!(normalize_key("MD"), "md"); // Too short to be a rule
1043        assert_eq!(normalize_key("MD00"), "md00"); // Too short
1044        assert_eq!(normalize_key("MD0001"), "md0001"); // Too long
1045        assert_eq!(normalize_key("MDabc"), "mdabc"); // Non-digit
1046        assert_eq!(normalize_key("MD00a"), "md00a"); // Partial digit
1047        assert_eq!(normalize_key(""), "");
1048        assert_eq!(normalize_key("_"), "-");
1049        assert_eq!(normalize_key("___"), "---");
1050    }
1051
1052    #[test]
1053    fn test_missing_config_file() {
1054        let temp_dir = tempdir().unwrap();
1055        let config_path = temp_dir.path().join("nonexistent.toml");
1056
1057        let result = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true);
1058        assert!(result.is_err());
1059        match result.unwrap_err() {
1060            ConfigError::IoError { .. } => {}
1061            _ => panic!("Expected IoError for missing file"),
1062        }
1063    }
1064
1065    #[test]
1066    #[cfg(unix)]
1067    fn test_permission_denied_config() {
1068        use std::os::unix::fs::PermissionsExt;
1069
1070        let temp_dir = tempdir().unwrap();
1071        let config_path = temp_dir.path().join(".rumdl.toml");
1072
1073        fs::write(&config_path, "enable = [\"MD001\"]").unwrap();
1074
1075        // Remove read permissions
1076        let mut perms = fs::metadata(&config_path).unwrap().permissions();
1077        perms.set_mode(0o000);
1078        fs::set_permissions(&config_path, perms).unwrap();
1079
1080        let result = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true);
1081
1082        // Restore permissions for cleanup
1083        let mut perms = fs::metadata(&config_path).unwrap().permissions();
1084        perms.set_mode(0o644);
1085        fs::set_permissions(&config_path, perms).unwrap();
1086
1087        assert!(result.is_err());
1088        match result.unwrap_err() {
1089            ConfigError::IoError { .. } => {}
1090            _ => panic!("Expected IoError for permission denied"),
1091        }
1092    }
1093
1094    #[test]
1095    fn test_circular_reference_detection() {
1096        // This test is more conceptual since TOML doesn't support circular references
1097        // But we test that deeply nested structures don't cause stack overflow
1098        let temp_dir = tempdir().unwrap();
1099        let config_path = temp_dir.path().join(".rumdl.toml");
1100
1101        let mut config_content = String::from("[MD001]\n");
1102        for i in 0..100 {
1103            config_content.push_str(&format!("key{i} = {i}\n"));
1104        }
1105
1106        fs::write(&config_path, config_content).unwrap();
1107
1108        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1109        let config: Config = sourced.into_validated_unchecked().into();
1110
1111        let rule_config = config.rules.get("MD001").unwrap();
1112        assert_eq!(rule_config.values.len(), 100);
1113    }
1114
1115    #[test]
1116    fn test_special_toml_values() {
1117        let temp_dir = tempdir().unwrap();
1118        let config_path = temp_dir.path().join(".rumdl.toml");
1119
1120        let config_content = r#"
1121[MD001]
1122infinity = inf
1123neg_infinity = -inf
1124not_a_number = nan
1125datetime = 1979-05-27T07:32:00Z
1126local_date = 1979-05-27
1127local_time = 07:32:00
1128"#;
1129        fs::write(&config_path, config_content).unwrap();
1130
1131        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1132        let config: Config = sourced.into_validated_unchecked().into();
1133
1134        // Some values might not be parsed due to parser limitations
1135        if let Some(rule_config) = config.rules.get("MD001") {
1136            // Check special float values if present
1137            if let Some(toml::Value::Float(f)) = rule_config.values.get("infinity") {
1138                assert!(f.is_infinite() && f.is_sign_positive());
1139            }
1140            if let Some(toml::Value::Float(f)) = rule_config.values.get("neg_infinity") {
1141                assert!(f.is_infinite() && f.is_sign_negative());
1142            }
1143            if let Some(toml::Value::Float(f)) = rule_config.values.get("not_a_number") {
1144                assert!(f.is_nan());
1145            }
1146
1147            // Check datetime values if present
1148            if let Some(val) = rule_config.values.get("datetime") {
1149                assert!(matches!(val, toml::Value::Datetime(_)));
1150            }
1151            // Note: local_date and local_time might not be parsed by the current implementation
1152        }
1153    }
1154
1155    #[test]
1156    fn test_default_config_passes_validation() {
1157        use crate::rules;
1158
1159        let temp_dir = tempdir().unwrap();
1160        let config_path = temp_dir.path().join(".rumdl.toml");
1161        let config_path_str = config_path.to_str().unwrap();
1162
1163        // Create the default config using the same function that `rumdl init` uses
1164        create_default_config(config_path_str).unwrap();
1165
1166        // Load it back as a SourcedConfig
1167        let sourced =
1168            SourcedConfig::load(Some(config_path_str), None).expect("Default config should load successfully");
1169
1170        // Create the rule registry
1171        let all_rules = rules::all_rules(&Config::default());
1172        let registry = RuleRegistry::from_rules(&all_rules);
1173
1174        // Validate the config
1175        let warnings = validate_config_sourced(&sourced, &registry);
1176
1177        // The default config should have no warnings
1178        if !warnings.is_empty() {
1179            for warning in &warnings {
1180                eprintln!("Config validation warning: {}", warning.message);
1181                if let Some(rule) = &warning.rule {
1182                    eprintln!("  Rule: {rule}");
1183                }
1184                if let Some(key) = &warning.key {
1185                    eprintln!("  Key: {key}");
1186                }
1187            }
1188        }
1189        assert!(
1190            warnings.is_empty(),
1191            "Default config from rumdl init should pass validation without warnings"
1192        );
1193    }
1194
1195    #[test]
1196    fn test_per_file_ignores_config_parsing() {
1197        let temp_dir = tempdir().unwrap();
1198        let config_path = temp_dir.path().join(".rumdl.toml");
1199        let config_content = r#"
1200[per-file-ignores]
1201"README.md" = ["MD033"]
1202"docs/**/*.md" = ["MD013", "MD033"]
1203"test/*.md" = ["MD041"]
1204"#;
1205        fs::write(&config_path, config_content).unwrap();
1206
1207        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1208        let config: Config = sourced.into_validated_unchecked().into();
1209
1210        // Verify per-file-ignores was loaded
1211        assert_eq!(config.per_file_ignores.len(), 3);
1212        assert_eq!(
1213            config.per_file_ignores.get("README.md"),
1214            Some(&vec!["MD033".to_string()])
1215        );
1216        assert_eq!(
1217            config.per_file_ignores.get("docs/**/*.md"),
1218            Some(&vec!["MD013".to_string(), "MD033".to_string()])
1219        );
1220        assert_eq!(
1221            config.per_file_ignores.get("test/*.md"),
1222            Some(&vec!["MD041".to_string()])
1223        );
1224    }
1225
1226    #[test]
1227    fn test_per_file_ignores_glob_matching() {
1228        use std::path::PathBuf;
1229
1230        let temp_dir = tempdir().unwrap();
1231        let config_path = temp_dir.path().join(".rumdl.toml");
1232        let config_content = r#"
1233[per-file-ignores]
1234"README.md" = ["MD033"]
1235"docs/**/*.md" = ["MD013"]
1236"**/test_*.md" = ["MD041"]
1237"#;
1238        fs::write(&config_path, config_content).unwrap();
1239
1240        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1241        let config: Config = sourced.into_validated_unchecked().into();
1242
1243        // Test exact match
1244        let ignored = config.get_ignored_rules_for_file(&PathBuf::from("README.md"));
1245        assert!(ignored.contains("MD033"));
1246        assert_eq!(ignored.len(), 1);
1247
1248        // Test glob pattern matching
1249        let ignored = config.get_ignored_rules_for_file(&PathBuf::from("docs/api/overview.md"));
1250        assert!(ignored.contains("MD013"));
1251        assert_eq!(ignored.len(), 1);
1252
1253        // Test recursive glob pattern
1254        let ignored = config.get_ignored_rules_for_file(&PathBuf::from("tests/fixtures/test_example.md"));
1255        assert!(ignored.contains("MD041"));
1256        assert_eq!(ignored.len(), 1);
1257
1258        // Test non-matching path
1259        let ignored = config.get_ignored_rules_for_file(&PathBuf::from("other/file.md"));
1260        assert!(ignored.is_empty());
1261    }
1262
1263    #[test]
1264    fn test_per_file_ignores_pyproject_toml() {
1265        let temp_dir = tempdir().unwrap();
1266        let config_path = temp_dir.path().join("pyproject.toml");
1267        let config_content = r#"
1268[tool.rumdl]
1269[tool.rumdl.per-file-ignores]
1270"README.md" = ["MD033", "MD013"]
1271"generated/*.md" = ["MD041"]
1272"#;
1273        fs::write(&config_path, config_content).unwrap();
1274
1275        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1276        let config: Config = sourced.into_validated_unchecked().into();
1277
1278        // Verify per-file-ignores was loaded from pyproject.toml
1279        assert_eq!(config.per_file_ignores.len(), 2);
1280        assert_eq!(
1281            config.per_file_ignores.get("README.md"),
1282            Some(&vec!["MD033".to_string(), "MD013".to_string()])
1283        );
1284        assert_eq!(
1285            config.per_file_ignores.get("generated/*.md"),
1286            Some(&vec!["MD041".to_string()])
1287        );
1288    }
1289
1290    #[test]
1291    fn test_per_file_ignores_multiple_patterns_match() {
1292        use std::path::PathBuf;
1293
1294        let temp_dir = tempdir().unwrap();
1295        let config_path = temp_dir.path().join(".rumdl.toml");
1296        let config_content = r#"
1297[per-file-ignores]
1298"docs/**/*.md" = ["MD013"]
1299"**/api/*.md" = ["MD033"]
1300"docs/api/overview.md" = ["MD041"]
1301"#;
1302        fs::write(&config_path, config_content).unwrap();
1303
1304        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1305        let config: Config = sourced.into_validated_unchecked().into();
1306
1307        // File matches multiple patterns - should get union of all rules
1308        let ignored = config.get_ignored_rules_for_file(&PathBuf::from("docs/api/overview.md"));
1309        assert_eq!(ignored.len(), 3);
1310        assert!(ignored.contains("MD013"));
1311        assert!(ignored.contains("MD033"));
1312        assert!(ignored.contains("MD041"));
1313    }
1314
1315    #[test]
1316    fn test_per_file_ignores_rule_name_normalization() {
1317        use std::path::PathBuf;
1318
1319        let temp_dir = tempdir().unwrap();
1320        let config_path = temp_dir.path().join(".rumdl.toml");
1321        let config_content = r#"
1322[per-file-ignores]
1323"README.md" = ["md033", "MD013", "Md041"]
1324"#;
1325        fs::write(&config_path, config_content).unwrap();
1326
1327        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1328        let config: Config = sourced.into_validated_unchecked().into();
1329
1330        // All rule names should be normalized to uppercase
1331        let ignored = config.get_ignored_rules_for_file(&PathBuf::from("README.md"));
1332        assert_eq!(ignored.len(), 3);
1333        assert!(ignored.contains("MD033"));
1334        assert!(ignored.contains("MD013"));
1335        assert!(ignored.contains("MD041"));
1336    }
1337
1338    #[test]
1339    fn test_per_file_ignores_invalid_glob_pattern() {
1340        use std::path::PathBuf;
1341
1342        let temp_dir = tempdir().unwrap();
1343        let config_path = temp_dir.path().join(".rumdl.toml");
1344        let config_content = r#"
1345[per-file-ignores]
1346"[invalid" = ["MD033"]
1347"valid/*.md" = ["MD013"]
1348"#;
1349        fs::write(&config_path, config_content).unwrap();
1350
1351        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1352        let config: Config = sourced.into_validated_unchecked().into();
1353
1354        // Invalid pattern should be skipped, valid pattern should work
1355        let ignored = config.get_ignored_rules_for_file(&PathBuf::from("valid/test.md"));
1356        assert!(ignored.contains("MD013"));
1357
1358        // Invalid pattern should not cause issues
1359        let ignored2 = config.get_ignored_rules_for_file(&PathBuf::from("[invalid"));
1360        assert!(ignored2.is_empty());
1361    }
1362
1363    #[test]
1364    fn test_per_file_ignores_empty_section() {
1365        use std::path::PathBuf;
1366
1367        let temp_dir = tempdir().unwrap();
1368        let config_path = temp_dir.path().join(".rumdl.toml");
1369        let config_content = r#"
1370[global]
1371disable = ["MD001"]
1372
1373[per-file-ignores]
1374"#;
1375        fs::write(&config_path, config_content).unwrap();
1376
1377        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1378        let config: Config = sourced.into_validated_unchecked().into();
1379
1380        // Empty per-file-ignores should work fine
1381        assert_eq!(config.per_file_ignores.len(), 0);
1382        let ignored = config.get_ignored_rules_for_file(&PathBuf::from("README.md"));
1383        assert!(ignored.is_empty());
1384    }
1385
1386    #[test]
1387    fn test_per_file_ignores_with_underscores_in_pyproject() {
1388        let temp_dir = tempdir().unwrap();
1389        let config_path = temp_dir.path().join("pyproject.toml");
1390        let config_content = r#"
1391[tool.rumdl]
1392[tool.rumdl.per_file_ignores]
1393"README.md" = ["MD033"]
1394"#;
1395        fs::write(&config_path, config_content).unwrap();
1396
1397        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1398        let config: Config = sourced.into_validated_unchecked().into();
1399
1400        // Should support both per-file-ignores and per_file_ignores
1401        assert_eq!(config.per_file_ignores.len(), 1);
1402        assert_eq!(
1403            config.per_file_ignores.get("README.md"),
1404            Some(&vec!["MD033".to_string()])
1405        );
1406    }
1407
1408    #[test]
1409    fn test_per_file_ignores_absolute_path_matching() {
1410        // Regression test for issue #208: per-file-ignores should work with absolute paths
1411        // This is critical for GitHub Actions which uses absolute paths like $GITHUB_WORKSPACE
1412        use std::path::PathBuf;
1413
1414        let temp_dir = tempdir().unwrap();
1415        let config_path = temp_dir.path().join(".rumdl.toml");
1416
1417        // Create a subdirectory and file to match against
1418        let github_dir = temp_dir.path().join(".github");
1419        fs::create_dir_all(&github_dir).unwrap();
1420        let test_file = github_dir.join("pull_request_template.md");
1421        fs::write(&test_file, "Test content").unwrap();
1422
1423        let config_content = r#"
1424[per-file-ignores]
1425".github/pull_request_template.md" = ["MD041"]
1426"docs/**/*.md" = ["MD013"]
1427"#;
1428        fs::write(&config_path, config_content).unwrap();
1429
1430        let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1431        let config: Config = sourced.into_validated_unchecked().into();
1432
1433        // Test with absolute path (like GitHub Actions would use)
1434        let absolute_path = test_file.canonicalize().unwrap();
1435        let ignored = config.get_ignored_rules_for_file(&absolute_path);
1436        assert!(
1437            ignored.contains("MD041"),
1438            "Should match absolute path {absolute_path:?} against relative pattern"
1439        );
1440        assert_eq!(ignored.len(), 1);
1441
1442        // Also verify relative path still works
1443        let relative_path = PathBuf::from(".github/pull_request_template.md");
1444        let ignored = config.get_ignored_rules_for_file(&relative_path);
1445        assert!(ignored.contains("MD041"), "Should match relative path");
1446    }
1447
1448    #[test]
1449    fn test_generate_json_schema() {
1450        use schemars::schema_for;
1451        use std::env;
1452
1453        let schema = schema_for!(Config);
1454        let schema_json = serde_json::to_string_pretty(&schema).expect("Failed to serialize schema");
1455
1456        // Write schema to file if RUMDL_UPDATE_SCHEMA env var is set
1457        if env::var("RUMDL_UPDATE_SCHEMA").is_ok() {
1458            let schema_path = env::current_dir().unwrap().join("rumdl.schema.json");
1459            fs::write(&schema_path, &schema_json).expect("Failed to write schema file");
1460            println!("Schema written to: {}", schema_path.display());
1461        }
1462
1463        // Basic validation that schema was generated
1464        assert!(schema_json.contains("\"title\": \"Config\""));
1465        assert!(schema_json.contains("\"global\""));
1466        assert!(schema_json.contains("\"per-file-ignores\""));
1467    }
1468
1469    #[test]
1470    fn test_user_config_loaded_with_explicit_project_config() {
1471        // Regression test for issue #131: User config should always be loaded as base layer,
1472        // even when an explicit project config path is provided
1473        let temp_dir = tempdir().unwrap();
1474
1475        // Create a fake user config directory
1476        // Note: user_configuration_path_impl adds /rumdl to the config dir
1477        let user_config_dir = temp_dir.path().join("user_config");
1478        let rumdl_config_dir = user_config_dir.join("rumdl");
1479        fs::create_dir_all(&rumdl_config_dir).unwrap();
1480        let user_config_path = rumdl_config_dir.join("rumdl.toml");
1481
1482        // User config disables MD013 and MD041
1483        let user_config_content = r#"
1484[global]
1485disable = ["MD013", "MD041"]
1486line-length = 100
1487"#;
1488        fs::write(&user_config_path, user_config_content).unwrap();
1489
1490        // Create a project config that enables MD001
1491        let project_config_path = temp_dir.path().join("project").join("pyproject.toml");
1492        fs::create_dir_all(project_config_path.parent().unwrap()).unwrap();
1493        let project_config_content = r#"
1494[tool.rumdl]
1495enable = ["MD001"]
1496"#;
1497        fs::write(&project_config_path, project_config_content).unwrap();
1498
1499        // Load config with explicit project path, passing user_config_dir
1500        let sourced = SourcedConfig::load_with_discovery_impl(
1501            Some(project_config_path.to_str().unwrap()),
1502            None,
1503            false,
1504            Some(&user_config_dir),
1505        )
1506        .unwrap();
1507
1508        let config: Config = sourced.into_validated_unchecked().into();
1509
1510        // User config settings should be preserved
1511        assert!(
1512            config.global.disable.contains(&"MD013".to_string()),
1513            "User config disabled rules should be preserved"
1514        );
1515        assert!(
1516            config.global.disable.contains(&"MD041".to_string()),
1517            "User config disabled rules should be preserved"
1518        );
1519
1520        // Project config settings should also be applied (merged on top)
1521        assert!(
1522            config.global.enable.contains(&"MD001".to_string()),
1523            "Project config enabled rules should be applied"
1524        );
1525    }
1526
1527    #[test]
1528    fn test_typestate_validate_method() {
1529        use tempfile::tempdir;
1530
1531        let temp_dir = tempdir().expect("Failed to create temporary directory");
1532        let config_path = temp_dir.path().join("test.toml");
1533
1534        // Create config with an unknown rule option to trigger a validation warning
1535        let config_content = r#"
1536[global]
1537enable = ["MD001"]
1538
1539[MD013]
1540line_length = 80
1541unknown_option = true
1542"#;
1543        std::fs::write(&config_path, config_content).expect("Failed to write config");
1544
1545        // Load config - this returns SourcedConfig<ConfigLoaded>
1546        let loaded = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true)
1547            .expect("Should load config");
1548
1549        // Create a rule registry for validation
1550        let default_config = Config::default();
1551        let all_rules = crate::rules::all_rules(&default_config);
1552        let registry = RuleRegistry::from_rules(&all_rules);
1553
1554        // Validate - this transitions to SourcedConfig<ConfigValidated>
1555        let validated = loaded.validate(&registry).expect("Should validate config");
1556
1557        // Check that validation warnings were captured for the unknown option
1558        // Note: The validation checks rule options against the rule's schema
1559        let has_unknown_option_warning = validated
1560            .validation_warnings
1561            .iter()
1562            .any(|w| w.message.contains("unknown_option") || w.message.contains("Unknown option"));
1563
1564        // Print warnings for debugging if assertion fails
1565        if !has_unknown_option_warning {
1566            for w in &validated.validation_warnings {
1567                eprintln!("Warning: {}", w.message);
1568            }
1569        }
1570        assert!(
1571            has_unknown_option_warning,
1572            "Should have warning for unknown option. Got {} warnings: {:?}",
1573            validated.validation_warnings.len(),
1574            validated
1575                .validation_warnings
1576                .iter()
1577                .map(|w| &w.message)
1578                .collect::<Vec<_>>()
1579        );
1580
1581        // Now we can convert to Config (this would be a compile error with ConfigLoaded)
1582        let config: Config = validated.into();
1583
1584        // Verify the config values are correct
1585        assert!(config.global.enable.contains(&"MD001".to_string()));
1586    }
1587
1588    #[test]
1589    fn test_typestate_validate_into_convenience_method() {
1590        use tempfile::tempdir;
1591
1592        let temp_dir = tempdir().expect("Failed to create temporary directory");
1593        let config_path = temp_dir.path().join("test.toml");
1594
1595        let config_content = r#"
1596[global]
1597enable = ["MD022"]
1598
1599[MD022]
1600lines_above = 2
1601"#;
1602        std::fs::write(&config_path, config_content).expect("Failed to write config");
1603
1604        let loaded = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true)
1605            .expect("Should load config");
1606
1607        let default_config = Config::default();
1608        let all_rules = crate::rules::all_rules(&default_config);
1609        let registry = RuleRegistry::from_rules(&all_rules);
1610
1611        // Use the convenience method that validates and converts in one step
1612        let (config, warnings) = loaded.validate_into(&registry).expect("Should validate and convert");
1613
1614        // Should have no warnings for valid config
1615        assert!(warnings.is_empty(), "Should have no warnings for valid config");
1616
1617        // Config should be usable
1618        assert!(config.global.enable.contains(&"MD022".to_string()));
1619    }
1620}
1621
1622/// Configuration source with clear precedence hierarchy.
1623///
1624/// Precedence order (lower values override higher values):
1625/// - Default (0): Built-in defaults
1626/// - UserConfig (1): User-level ~/.config/rumdl/rumdl.toml
1627/// - PyprojectToml (2): Project-level pyproject.toml
1628/// - ProjectConfig (3): Project-level .rumdl.toml (most specific)
1629/// - Cli (4): Command-line flags (highest priority)
1630#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1631pub enum ConfigSource {
1632    /// Built-in default configuration
1633    Default,
1634    /// User-level configuration from ~/.config/rumdl/rumdl.toml
1635    UserConfig,
1636    /// Project-level configuration from pyproject.toml
1637    PyprojectToml,
1638    /// Project-level configuration from .rumdl.toml or rumdl.toml
1639    ProjectConfig,
1640    /// Command-line flags (highest precedence)
1641    Cli,
1642}
1643
1644#[derive(Debug, Clone)]
1645pub struct ConfigOverride<T> {
1646    pub value: T,
1647    pub source: ConfigSource,
1648    pub file: Option<String>,
1649    pub line: Option<usize>,
1650}
1651
1652#[derive(Debug, Clone)]
1653pub struct SourcedValue<T> {
1654    pub value: T,
1655    pub source: ConfigSource,
1656    pub overrides: Vec<ConfigOverride<T>>,
1657}
1658
1659impl<T: Clone> SourcedValue<T> {
1660    pub fn new(value: T, source: ConfigSource) -> Self {
1661        Self {
1662            value: value.clone(),
1663            source,
1664            overrides: vec![ConfigOverride {
1665                value,
1666                source,
1667                file: None,
1668                line: None,
1669            }],
1670        }
1671    }
1672
1673    /// Merges a new override into this SourcedValue based on source precedence.
1674    /// If the new source has higher or equal precedence, the value and source are updated,
1675    /// and the new override is added to the history.
1676    pub fn merge_override(
1677        &mut self,
1678        new_value: T,
1679        new_source: ConfigSource,
1680        new_file: Option<String>,
1681        new_line: Option<usize>,
1682    ) {
1683        // Helper function to get precedence, defined locally or globally
1684        fn source_precedence(src: ConfigSource) -> u8 {
1685            match src {
1686                ConfigSource::Default => 0,
1687                ConfigSource::UserConfig => 1,
1688                ConfigSource::PyprojectToml => 2,
1689                ConfigSource::ProjectConfig => 3,
1690                ConfigSource::Cli => 4,
1691            }
1692        }
1693
1694        if source_precedence(new_source) >= source_precedence(self.source) {
1695            self.value = new_value.clone();
1696            self.source = new_source;
1697            self.overrides.push(ConfigOverride {
1698                value: new_value,
1699                source: new_source,
1700                file: new_file,
1701                line: new_line,
1702            });
1703        }
1704    }
1705
1706    pub fn push_override(&mut self, value: T, source: ConfigSource, file: Option<String>, line: Option<usize>) {
1707        // This is essentially merge_override without the precedence check
1708        // We might consolidate these later, but keep separate for now during refactor
1709        self.value = value.clone();
1710        self.source = source;
1711        self.overrides.push(ConfigOverride {
1712            value,
1713            source,
1714            file,
1715            line,
1716        });
1717    }
1718}
1719
1720impl<T: Clone + Eq + std::hash::Hash> SourcedValue<Vec<T>> {
1721    /// Merges a new value using union semantics (for arrays like `disable`)
1722    /// Values from both sources are combined, with deduplication
1723    pub fn merge_union(
1724        &mut self,
1725        new_value: Vec<T>,
1726        new_source: ConfigSource,
1727        new_file: Option<String>,
1728        new_line: Option<usize>,
1729    ) {
1730        fn source_precedence(src: ConfigSource) -> u8 {
1731            match src {
1732                ConfigSource::Default => 0,
1733                ConfigSource::UserConfig => 1,
1734                ConfigSource::PyprojectToml => 2,
1735                ConfigSource::ProjectConfig => 3,
1736                ConfigSource::Cli => 4,
1737            }
1738        }
1739
1740        if source_precedence(new_source) >= source_precedence(self.source) {
1741            // Union: combine values from both sources with deduplication
1742            let mut combined = self.value.clone();
1743            for item in new_value.iter() {
1744                if !combined.contains(item) {
1745                    combined.push(item.clone());
1746                }
1747            }
1748
1749            self.value = combined;
1750            self.source = new_source;
1751            self.overrides.push(ConfigOverride {
1752                value: new_value,
1753                source: new_source,
1754                file: new_file,
1755                line: new_line,
1756            });
1757        }
1758    }
1759}
1760
1761#[derive(Debug, Clone)]
1762pub struct SourcedGlobalConfig {
1763    pub enable: SourcedValue<Vec<String>>,
1764    pub disable: SourcedValue<Vec<String>>,
1765    pub exclude: SourcedValue<Vec<String>>,
1766    pub include: SourcedValue<Vec<String>>,
1767    pub respect_gitignore: SourcedValue<bool>,
1768    pub line_length: SourcedValue<LineLength>,
1769    pub output_format: Option<SourcedValue<String>>,
1770    pub fixable: SourcedValue<Vec<String>>,
1771    pub unfixable: SourcedValue<Vec<String>>,
1772    pub flavor: SourcedValue<MarkdownFlavor>,
1773    pub force_exclude: SourcedValue<bool>,
1774    pub cache_dir: Option<SourcedValue<String>>,
1775    pub cache: SourcedValue<bool>,
1776}
1777
1778impl Default for SourcedGlobalConfig {
1779    fn default() -> Self {
1780        SourcedGlobalConfig {
1781            enable: SourcedValue::new(Vec::new(), ConfigSource::Default),
1782            disable: SourcedValue::new(Vec::new(), ConfigSource::Default),
1783            exclude: SourcedValue::new(Vec::new(), ConfigSource::Default),
1784            include: SourcedValue::new(Vec::new(), ConfigSource::Default),
1785            respect_gitignore: SourcedValue::new(true, ConfigSource::Default),
1786            line_length: SourcedValue::new(LineLength::default(), ConfigSource::Default),
1787            output_format: None,
1788            fixable: SourcedValue::new(Vec::new(), ConfigSource::Default),
1789            unfixable: SourcedValue::new(Vec::new(), ConfigSource::Default),
1790            flavor: SourcedValue::new(MarkdownFlavor::default(), ConfigSource::Default),
1791            force_exclude: SourcedValue::new(false, ConfigSource::Default),
1792            cache_dir: None,
1793            cache: SourcedValue::new(true, ConfigSource::Default),
1794        }
1795    }
1796}
1797
1798#[derive(Debug, Default, Clone)]
1799pub struct SourcedRuleConfig {
1800    pub severity: Option<SourcedValue<crate::rule::Severity>>,
1801    pub values: BTreeMap<String, SourcedValue<toml::Value>>,
1802}
1803
1804/// Represents configuration loaded from a single source file, with provenance.
1805/// Used as an intermediate step before merging into the final SourcedConfig.
1806#[derive(Debug, Clone)]
1807pub struct SourcedConfigFragment {
1808    pub global: SourcedGlobalConfig,
1809    pub per_file_ignores: SourcedValue<HashMap<String, Vec<String>>>,
1810    pub rules: BTreeMap<String, SourcedRuleConfig>,
1811    pub unknown_keys: Vec<(String, String, Option<String>)>, // (section, key, file_path)
1812                                                             // Note: loaded_files is tracked globally in SourcedConfig.
1813}
1814
1815impl Default for SourcedConfigFragment {
1816    fn default() -> Self {
1817        Self {
1818            global: SourcedGlobalConfig::default(),
1819            per_file_ignores: SourcedValue::new(HashMap::new(), ConfigSource::Default),
1820            rules: BTreeMap::new(),
1821            unknown_keys: Vec::new(),
1822        }
1823    }
1824}
1825
1826/// Configuration with provenance tracking for values.
1827///
1828/// The `State` type parameter encodes the validation state:
1829/// - `ConfigLoaded`: Config has been loaded but not validated
1830/// - `ConfigValidated`: Config has been validated and can be converted to `Config`
1831///
1832/// # Typestate Pattern
1833///
1834/// This uses the typestate pattern to ensure validation happens before conversion:
1835///
1836/// ```ignore
1837/// let loaded: SourcedConfig<ConfigLoaded> = SourcedConfig::load_with_discovery(...)?;
1838/// let validated: SourcedConfig<ConfigValidated> = loaded.validate(&registry)?;
1839/// let config: Config = validated.into();  // Only works on ConfigValidated!
1840/// ```
1841///
1842/// Attempting to convert a `ConfigLoaded` config directly to `Config` is a compile error.
1843#[derive(Debug, Clone)]
1844pub struct SourcedConfig<State = ConfigLoaded> {
1845    pub global: SourcedGlobalConfig,
1846    pub per_file_ignores: SourcedValue<HashMap<String, Vec<String>>>,
1847    pub rules: BTreeMap<String, SourcedRuleConfig>,
1848    pub loaded_files: Vec<String>,
1849    pub unknown_keys: Vec<(String, String, Option<String>)>, // (section, key, file_path)
1850    /// Project root directory (parent of config file), used for resolving relative paths
1851    pub project_root: Option<std::path::PathBuf>,
1852    /// Validation warnings (populated after validate() is called)
1853    pub validation_warnings: Vec<ConfigValidationWarning>,
1854    /// Phantom data for the state type parameter
1855    _state: PhantomData<State>,
1856}
1857
1858impl Default for SourcedConfig<ConfigLoaded> {
1859    fn default() -> Self {
1860        Self {
1861            global: SourcedGlobalConfig::default(),
1862            per_file_ignores: SourcedValue::new(HashMap::new(), ConfigSource::Default),
1863            rules: BTreeMap::new(),
1864            loaded_files: Vec::new(),
1865            unknown_keys: Vec::new(),
1866            project_root: None,
1867            validation_warnings: Vec::new(),
1868            _state: PhantomData,
1869        }
1870    }
1871}
1872
1873impl SourcedConfig<ConfigLoaded> {
1874    /// Merges another SourcedConfigFragment into this SourcedConfig.
1875    /// Uses source precedence to determine which values take effect.
1876    fn merge(&mut self, fragment: SourcedConfigFragment) {
1877        // Merge global config
1878        // Enable uses replace semantics (project can enforce rules)
1879        self.global.enable.merge_override(
1880            fragment.global.enable.value,
1881            fragment.global.enable.source,
1882            fragment.global.enable.overrides.first().and_then(|o| o.file.clone()),
1883            fragment.global.enable.overrides.first().and_then(|o| o.line),
1884        );
1885
1886        // Disable uses union semantics (user can add to project disables)
1887        self.global.disable.merge_union(
1888            fragment.global.disable.value,
1889            fragment.global.disable.source,
1890            fragment.global.disable.overrides.first().and_then(|o| o.file.clone()),
1891            fragment.global.disable.overrides.first().and_then(|o| o.line),
1892        );
1893
1894        // Conflict resolution: Enable overrides disable
1895        // Remove any rules from disable that appear in enable
1896        self.global
1897            .disable
1898            .value
1899            .retain(|rule| !self.global.enable.value.contains(rule));
1900        self.global.include.merge_override(
1901            fragment.global.include.value,
1902            fragment.global.include.source,
1903            fragment.global.include.overrides.first().and_then(|o| o.file.clone()),
1904            fragment.global.include.overrides.first().and_then(|o| o.line),
1905        );
1906        self.global.exclude.merge_override(
1907            fragment.global.exclude.value,
1908            fragment.global.exclude.source,
1909            fragment.global.exclude.overrides.first().and_then(|o| o.file.clone()),
1910            fragment.global.exclude.overrides.first().and_then(|o| o.line),
1911        );
1912        self.global.respect_gitignore.merge_override(
1913            fragment.global.respect_gitignore.value,
1914            fragment.global.respect_gitignore.source,
1915            fragment
1916                .global
1917                .respect_gitignore
1918                .overrides
1919                .first()
1920                .and_then(|o| o.file.clone()),
1921            fragment.global.respect_gitignore.overrides.first().and_then(|o| o.line),
1922        );
1923        self.global.line_length.merge_override(
1924            fragment.global.line_length.value,
1925            fragment.global.line_length.source,
1926            fragment
1927                .global
1928                .line_length
1929                .overrides
1930                .first()
1931                .and_then(|o| o.file.clone()),
1932            fragment.global.line_length.overrides.first().and_then(|o| o.line),
1933        );
1934        self.global.fixable.merge_override(
1935            fragment.global.fixable.value,
1936            fragment.global.fixable.source,
1937            fragment.global.fixable.overrides.first().and_then(|o| o.file.clone()),
1938            fragment.global.fixable.overrides.first().and_then(|o| o.line),
1939        );
1940        self.global.unfixable.merge_override(
1941            fragment.global.unfixable.value,
1942            fragment.global.unfixable.source,
1943            fragment.global.unfixable.overrides.first().and_then(|o| o.file.clone()),
1944            fragment.global.unfixable.overrides.first().and_then(|o| o.line),
1945        );
1946
1947        // Merge flavor
1948        self.global.flavor.merge_override(
1949            fragment.global.flavor.value,
1950            fragment.global.flavor.source,
1951            fragment.global.flavor.overrides.first().and_then(|o| o.file.clone()),
1952            fragment.global.flavor.overrides.first().and_then(|o| o.line),
1953        );
1954
1955        // Merge force_exclude
1956        self.global.force_exclude.merge_override(
1957            fragment.global.force_exclude.value,
1958            fragment.global.force_exclude.source,
1959            fragment
1960                .global
1961                .force_exclude
1962                .overrides
1963                .first()
1964                .and_then(|o| o.file.clone()),
1965            fragment.global.force_exclude.overrides.first().and_then(|o| o.line),
1966        );
1967
1968        // Merge output_format if present
1969        if let Some(output_format_fragment) = fragment.global.output_format {
1970            if let Some(ref mut output_format) = self.global.output_format {
1971                output_format.merge_override(
1972                    output_format_fragment.value,
1973                    output_format_fragment.source,
1974                    output_format_fragment.overrides.first().and_then(|o| o.file.clone()),
1975                    output_format_fragment.overrides.first().and_then(|o| o.line),
1976                );
1977            } else {
1978                self.global.output_format = Some(output_format_fragment);
1979            }
1980        }
1981
1982        // Merge cache_dir if present
1983        if let Some(cache_dir_fragment) = fragment.global.cache_dir {
1984            if let Some(ref mut cache_dir) = self.global.cache_dir {
1985                cache_dir.merge_override(
1986                    cache_dir_fragment.value,
1987                    cache_dir_fragment.source,
1988                    cache_dir_fragment.overrides.first().and_then(|o| o.file.clone()),
1989                    cache_dir_fragment.overrides.first().and_then(|o| o.line),
1990                );
1991            } else {
1992                self.global.cache_dir = Some(cache_dir_fragment);
1993            }
1994        }
1995
1996        // Merge cache if not default (only override when explicitly set)
1997        if fragment.global.cache.source != ConfigSource::Default {
1998            self.global.cache.merge_override(
1999                fragment.global.cache.value,
2000                fragment.global.cache.source,
2001                fragment.global.cache.overrides.first().and_then(|o| o.file.clone()),
2002                fragment.global.cache.overrides.first().and_then(|o| o.line),
2003            );
2004        }
2005
2006        // Merge per_file_ignores
2007        self.per_file_ignores.merge_override(
2008            fragment.per_file_ignores.value,
2009            fragment.per_file_ignores.source,
2010            fragment.per_file_ignores.overrides.first().and_then(|o| o.file.clone()),
2011            fragment.per_file_ignores.overrides.first().and_then(|o| o.line),
2012        );
2013
2014        // Merge rule configs
2015        for (rule_name, rule_fragment) in fragment.rules {
2016            let norm_rule_name = rule_name.to_ascii_uppercase(); // Normalize to uppercase for case-insensitivity
2017            let rule_entry = self.rules.entry(norm_rule_name).or_default();
2018
2019            // Merge severity if present in fragment
2020            if let Some(severity_fragment) = rule_fragment.severity {
2021                if let Some(ref mut existing_severity) = rule_entry.severity {
2022                    existing_severity.merge_override(
2023                        severity_fragment.value,
2024                        severity_fragment.source,
2025                        severity_fragment.overrides.first().and_then(|o| o.file.clone()),
2026                        severity_fragment.overrides.first().and_then(|o| o.line),
2027                    );
2028                } else {
2029                    rule_entry.severity = Some(severity_fragment);
2030                }
2031            }
2032
2033            // Merge values
2034            for (key, sourced_value_fragment) in rule_fragment.values {
2035                let sv_entry = rule_entry
2036                    .values
2037                    .entry(key.clone())
2038                    .or_insert_with(|| SourcedValue::new(sourced_value_fragment.value.clone(), ConfigSource::Default));
2039                let file_from_fragment = sourced_value_fragment.overrides.first().and_then(|o| o.file.clone());
2040                let line_from_fragment = sourced_value_fragment.overrides.first().and_then(|o| o.line);
2041                sv_entry.merge_override(
2042                    sourced_value_fragment.value,  // Use the value from the fragment
2043                    sourced_value_fragment.source, // Use the source from the fragment
2044                    file_from_fragment,            // Pass the file path from the fragment override
2045                    line_from_fragment,            // Pass the line number from the fragment override
2046                );
2047            }
2048        }
2049
2050        // Merge unknown_keys from fragment
2051        for (section, key, file_path) in fragment.unknown_keys {
2052            // Deduplicate: only add if not already present
2053            if !self.unknown_keys.iter().any(|(s, k, _)| s == &section && k == &key) {
2054                self.unknown_keys.push((section, key, file_path));
2055            }
2056        }
2057    }
2058
2059    /// Load and merge configurations from files and CLI overrides.
2060    pub fn load(config_path: Option<&str>, cli_overrides: Option<&SourcedGlobalConfig>) -> Result<Self, ConfigError> {
2061        Self::load_with_discovery(config_path, cli_overrides, false)
2062    }
2063
2064    /// Finds project root by walking up from start_dir looking for .git directory.
2065    /// Falls back to start_dir if no .git found.
2066    fn find_project_root_from(start_dir: &Path) -> std::path::PathBuf {
2067        let mut current = start_dir.to_path_buf();
2068        const MAX_DEPTH: usize = 100;
2069
2070        for _ in 0..MAX_DEPTH {
2071            if current.join(".git").exists() {
2072                log::debug!("[rumdl-config] Found .git at: {}", current.display());
2073                return current;
2074            }
2075
2076            match current.parent() {
2077                Some(parent) => current = parent.to_path_buf(),
2078                None => break,
2079            }
2080        }
2081
2082        // No .git found, use start_dir as project root
2083        log::debug!(
2084            "[rumdl-config] No .git found, using config location as project root: {}",
2085            start_dir.display()
2086        );
2087        start_dir.to_path_buf()
2088    }
2089
2090    /// Discover configuration file by traversing up the directory tree.
2091    /// Returns the first configuration file found.
2092    /// Discovers config file and returns both the config path and project root.
2093    /// Returns: (config_file_path, project_root_path)
2094    /// Project root is the directory containing .git, or config parent as fallback.
2095    fn discover_config_upward() -> Option<(std::path::PathBuf, std::path::PathBuf)> {
2096        use std::env;
2097
2098        const CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml", ".config/rumdl.toml", "pyproject.toml"];
2099        const MAX_DEPTH: usize = 100; // Prevent infinite traversal
2100
2101        let start_dir = match env::current_dir() {
2102            Ok(dir) => dir,
2103            Err(e) => {
2104                log::debug!("[rumdl-config] Failed to get current directory: {e}");
2105                return None;
2106            }
2107        };
2108
2109        let mut current_dir = start_dir.clone();
2110        let mut depth = 0;
2111        let mut found_config: Option<(std::path::PathBuf, std::path::PathBuf)> = None;
2112
2113        loop {
2114            if depth >= MAX_DEPTH {
2115                log::debug!("[rumdl-config] Maximum traversal depth reached");
2116                break;
2117            }
2118
2119            log::debug!("[rumdl-config] Searching for config in: {}", current_dir.display());
2120
2121            // Check for config files in order of precedence (only if not already found)
2122            if found_config.is_none() {
2123                for config_name in CONFIG_FILES {
2124                    let config_path = current_dir.join(config_name);
2125
2126                    if config_path.exists() {
2127                        // For pyproject.toml, verify it contains [tool.rumdl] section
2128                        if *config_name == "pyproject.toml" {
2129                            if let Ok(content) = std::fs::read_to_string(&config_path) {
2130                                if content.contains("[tool.rumdl]") || content.contains("tool.rumdl") {
2131                                    log::debug!("[rumdl-config] Found config file: {}", config_path.display());
2132                                    // Store config, but continue looking for .git
2133                                    found_config = Some((config_path.clone(), current_dir.clone()));
2134                                    break;
2135                                }
2136                                log::debug!("[rumdl-config] Found pyproject.toml but no [tool.rumdl] section");
2137                                continue;
2138                            }
2139                        } else {
2140                            log::debug!("[rumdl-config] Found config file: {}", config_path.display());
2141                            // Store config, but continue looking for .git
2142                            found_config = Some((config_path.clone(), current_dir.clone()));
2143                            break;
2144                        }
2145                    }
2146                }
2147            }
2148
2149            // Check for .git directory (stop boundary)
2150            if current_dir.join(".git").exists() {
2151                log::debug!("[rumdl-config] Stopping at .git directory");
2152                break;
2153            }
2154
2155            // Move to parent directory
2156            match current_dir.parent() {
2157                Some(parent) => {
2158                    current_dir = parent.to_owned();
2159                    depth += 1;
2160                }
2161                None => {
2162                    log::debug!("[rumdl-config] Reached filesystem root");
2163                    break;
2164                }
2165            }
2166        }
2167
2168        // If config found, determine project root by walking up from config location
2169        if let Some((config_path, config_dir)) = found_config {
2170            let project_root = Self::find_project_root_from(&config_dir);
2171            return Some((config_path, project_root));
2172        }
2173
2174        None
2175    }
2176
2177    /// Discover markdownlint configuration file by traversing up the directory tree.
2178    /// Similar to discover_config_upward but for .markdownlint.yaml/json files.
2179    /// Returns the path to the config file if found.
2180    fn discover_markdownlint_config_upward() -> Option<std::path::PathBuf> {
2181        use std::env;
2182
2183        const MAX_DEPTH: usize = 100;
2184
2185        let start_dir = match env::current_dir() {
2186            Ok(dir) => dir,
2187            Err(e) => {
2188                log::debug!("[rumdl-config] Failed to get current directory for markdownlint discovery: {e}");
2189                return None;
2190            }
2191        };
2192
2193        let mut current_dir = start_dir.clone();
2194        let mut depth = 0;
2195
2196        loop {
2197            if depth >= MAX_DEPTH {
2198                log::debug!("[rumdl-config] Maximum traversal depth reached for markdownlint discovery");
2199                break;
2200            }
2201
2202            log::debug!(
2203                "[rumdl-config] Searching for markdownlint config in: {}",
2204                current_dir.display()
2205            );
2206
2207            // Check for markdownlint config files in order of precedence
2208            for config_name in MARKDOWNLINT_CONFIG_FILES {
2209                let config_path = current_dir.join(config_name);
2210                if config_path.exists() {
2211                    log::debug!("[rumdl-config] Found markdownlint config: {}", config_path.display());
2212                    return Some(config_path);
2213                }
2214            }
2215
2216            // Check for .git directory (stop boundary)
2217            if current_dir.join(".git").exists() {
2218                log::debug!("[rumdl-config] Stopping markdownlint search at .git directory");
2219                break;
2220            }
2221
2222            // Move to parent directory
2223            match current_dir.parent() {
2224                Some(parent) => {
2225                    current_dir = parent.to_owned();
2226                    depth += 1;
2227                }
2228                None => {
2229                    log::debug!("[rumdl-config] Reached filesystem root during markdownlint search");
2230                    break;
2231                }
2232            }
2233        }
2234
2235        None
2236    }
2237
2238    /// Internal implementation that accepts config directory for testing
2239    fn user_configuration_path_impl(config_dir: &Path) -> Option<std::path::PathBuf> {
2240        let config_dir = config_dir.join("rumdl");
2241
2242        // Check for config files in precedence order (same as project discovery)
2243        const USER_CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml", "pyproject.toml"];
2244
2245        log::debug!(
2246            "[rumdl-config] Checking for user configuration in: {}",
2247            config_dir.display()
2248        );
2249
2250        for filename in USER_CONFIG_FILES {
2251            let config_path = config_dir.join(filename);
2252
2253            if config_path.exists() {
2254                // For pyproject.toml, verify it contains [tool.rumdl] section
2255                if *filename == "pyproject.toml" {
2256                    if let Ok(content) = std::fs::read_to_string(&config_path) {
2257                        if content.contains("[tool.rumdl]") || content.contains("tool.rumdl") {
2258                            log::debug!("[rumdl-config] Found user configuration at: {}", config_path.display());
2259                            return Some(config_path);
2260                        }
2261                        log::debug!("[rumdl-config] Found user pyproject.toml but no [tool.rumdl] section");
2262                        continue;
2263                    }
2264                } else {
2265                    log::debug!("[rumdl-config] Found user configuration at: {}", config_path.display());
2266                    return Some(config_path);
2267                }
2268            }
2269        }
2270
2271        log::debug!(
2272            "[rumdl-config] No user configuration found in: {}",
2273            config_dir.display()
2274        );
2275        None
2276    }
2277
2278    /// Discover user-level configuration file from platform-specific config directory.
2279    /// Returns the first configuration file found in the user config directory.
2280    #[cfg(feature = "native")]
2281    fn user_configuration_path() -> Option<std::path::PathBuf> {
2282        use etcetera::{BaseStrategy, choose_base_strategy};
2283
2284        match choose_base_strategy() {
2285            Ok(strategy) => {
2286                let config_dir = strategy.config_dir();
2287                Self::user_configuration_path_impl(&config_dir)
2288            }
2289            Err(e) => {
2290                log::debug!("[rumdl-config] Failed to determine user config directory: {e}");
2291                None
2292            }
2293        }
2294    }
2295
2296    /// Stub for WASM builds - user config not supported
2297    #[cfg(not(feature = "native"))]
2298    fn user_configuration_path() -> Option<std::path::PathBuf> {
2299        None
2300    }
2301
2302    /// Internal implementation that accepts user config directory for testing
2303    #[doc(hidden)]
2304    pub fn load_with_discovery_impl(
2305        config_path: Option<&str>,
2306        cli_overrides: Option<&SourcedGlobalConfig>,
2307        skip_auto_discovery: bool,
2308        user_config_dir: Option<&Path>,
2309    ) -> Result<Self, ConfigError> {
2310        use std::env;
2311        log::debug!("[rumdl-config] Current working directory: {:?}", env::current_dir());
2312        if config_path.is_none() {
2313            if skip_auto_discovery {
2314                log::debug!("[rumdl-config] Skipping auto-discovery due to --no-config flag");
2315            } else {
2316                log::debug!("[rumdl-config] No explicit config_path provided, will search default locations");
2317            }
2318        } else {
2319            log::debug!("[rumdl-config] Explicit config_path provided: {config_path:?}");
2320        }
2321        let mut sourced_config = SourcedConfig::default();
2322
2323        // 1. Always load user configuration first (unless auto-discovery is disabled)
2324        // User config serves as the base layer that project configs build upon
2325        if !skip_auto_discovery {
2326            let user_config_path = if let Some(dir) = user_config_dir {
2327                Self::user_configuration_path_impl(dir)
2328            } else {
2329                Self::user_configuration_path()
2330            };
2331
2332            if let Some(user_config_path) = user_config_path {
2333                let path_str = user_config_path.display().to_string();
2334                let filename = user_config_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
2335
2336                log::debug!("[rumdl-config] Loading user configuration file: {path_str}");
2337
2338                if filename == "pyproject.toml" {
2339                    let content = std::fs::read_to_string(&user_config_path).map_err(|e| ConfigError::IoError {
2340                        source: e,
2341                        path: path_str.clone(),
2342                    })?;
2343                    if let Some(fragment) = parse_pyproject_toml(&content, &path_str)? {
2344                        sourced_config.merge(fragment);
2345                        sourced_config.loaded_files.push(path_str);
2346                    }
2347                } else {
2348                    let content = std::fs::read_to_string(&user_config_path).map_err(|e| ConfigError::IoError {
2349                        source: e,
2350                        path: path_str.clone(),
2351                    })?;
2352                    let fragment = parse_rumdl_toml(&content, &path_str, ConfigSource::UserConfig)?;
2353                    sourced_config.merge(fragment);
2354                    sourced_config.loaded_files.push(path_str);
2355                }
2356            } else {
2357                log::debug!("[rumdl-config] No user configuration file found");
2358            }
2359        }
2360
2361        // 2. Load explicit config path if provided (overrides user config)
2362        if let Some(path) = config_path {
2363            let path_obj = Path::new(path);
2364            let filename = path_obj.file_name().and_then(|name| name.to_str()).unwrap_or("");
2365            log::debug!("[rumdl-config] Trying to load config file: {filename}");
2366            let path_str = path.to_string();
2367
2368            // Find project root by walking up from config location looking for .git
2369            if let Some(config_parent) = path_obj.parent() {
2370                let project_root = Self::find_project_root_from(config_parent);
2371                log::debug!(
2372                    "[rumdl-config] Project root (from explicit config): {}",
2373                    project_root.display()
2374                );
2375                sourced_config.project_root = Some(project_root);
2376            }
2377
2378            // Known markdownlint config files
2379            const MARKDOWNLINT_FILENAMES: &[&str] = &[".markdownlint.json", ".markdownlint.yaml", ".markdownlint.yml"];
2380
2381            if filename == "pyproject.toml" || filename == ".rumdl.toml" || filename == "rumdl.toml" {
2382                let content = std::fs::read_to_string(path).map_err(|e| ConfigError::IoError {
2383                    source: e,
2384                    path: path_str.clone(),
2385                })?;
2386                if filename == "pyproject.toml" {
2387                    if let Some(fragment) = parse_pyproject_toml(&content, &path_str)? {
2388                        sourced_config.merge(fragment);
2389                        sourced_config.loaded_files.push(path_str.clone());
2390                    }
2391                } else {
2392                    let fragment = parse_rumdl_toml(&content, &path_str, ConfigSource::ProjectConfig)?;
2393                    sourced_config.merge(fragment);
2394                    sourced_config.loaded_files.push(path_str.clone());
2395                }
2396            } else if MARKDOWNLINT_FILENAMES.contains(&filename)
2397                || path_str.ends_with(".json")
2398                || path_str.ends_with(".jsonc")
2399                || path_str.ends_with(".yaml")
2400                || path_str.ends_with(".yml")
2401            {
2402                // Parse as markdownlint config (JSON/YAML)
2403                let fragment = load_from_markdownlint(&path_str)?;
2404                sourced_config.merge(fragment);
2405                sourced_config.loaded_files.push(path_str.clone());
2406                // markdownlint is fallback only
2407            } else {
2408                // Try TOML only
2409                let content = std::fs::read_to_string(path).map_err(|e| ConfigError::IoError {
2410                    source: e,
2411                    path: path_str.clone(),
2412                })?;
2413                let fragment = parse_rumdl_toml(&content, &path_str, ConfigSource::ProjectConfig)?;
2414                sourced_config.merge(fragment);
2415                sourced_config.loaded_files.push(path_str.clone());
2416            }
2417        }
2418
2419        // 3. Perform auto-discovery for project config if not skipped AND no explicit config path
2420        if !skip_auto_discovery && config_path.is_none() {
2421            // Look for project configuration files (override user config)
2422            if let Some((config_file, project_root)) = Self::discover_config_upward() {
2423                let path_str = config_file.display().to_string();
2424                let filename = config_file.file_name().and_then(|n| n.to_str()).unwrap_or("");
2425
2426                log::debug!("[rumdl-config] Loading discovered config file: {path_str}");
2427                log::debug!("[rumdl-config] Project root: {}", project_root.display());
2428
2429                // Store project root for cache directory resolution
2430                sourced_config.project_root = Some(project_root);
2431
2432                if filename == "pyproject.toml" {
2433                    let content = std::fs::read_to_string(&config_file).map_err(|e| ConfigError::IoError {
2434                        source: e,
2435                        path: path_str.clone(),
2436                    })?;
2437                    if let Some(fragment) = parse_pyproject_toml(&content, &path_str)? {
2438                        sourced_config.merge(fragment);
2439                        sourced_config.loaded_files.push(path_str);
2440                    }
2441                } else if filename == ".rumdl.toml" || filename == "rumdl.toml" {
2442                    let content = std::fs::read_to_string(&config_file).map_err(|e| ConfigError::IoError {
2443                        source: e,
2444                        path: path_str.clone(),
2445                    })?;
2446                    let fragment = parse_rumdl_toml(&content, &path_str, ConfigSource::ProjectConfig)?;
2447                    sourced_config.merge(fragment);
2448                    sourced_config.loaded_files.push(path_str);
2449                }
2450            } else {
2451                log::debug!("[rumdl-config] No configuration file found via upward traversal");
2452
2453                // If no project config found, fallback to markdownlint config via upward traversal
2454                if let Some(config_path) = Self::discover_markdownlint_config_upward() {
2455                    let path_str = config_path.display().to_string();
2456                    match load_from_markdownlint(&path_str) {
2457                        Ok(fragment) => {
2458                            sourced_config.merge(fragment);
2459                            sourced_config.loaded_files.push(path_str);
2460                        }
2461                        Err(_e) => {
2462                            log::debug!("[rumdl-config] Failed to load markdownlint config");
2463                        }
2464                    }
2465                } else {
2466                    log::debug!("[rumdl-config] No markdownlint configuration file found");
2467                }
2468            }
2469        }
2470
2471        // 4. Apply CLI overrides (highest precedence)
2472        if let Some(cli) = cli_overrides {
2473            sourced_config
2474                .global
2475                .enable
2476                .merge_override(cli.enable.value.clone(), ConfigSource::Cli, None, None);
2477            sourced_config
2478                .global
2479                .disable
2480                .merge_override(cli.disable.value.clone(), ConfigSource::Cli, None, None);
2481            sourced_config
2482                .global
2483                .exclude
2484                .merge_override(cli.exclude.value.clone(), ConfigSource::Cli, None, None);
2485            sourced_config
2486                .global
2487                .include
2488                .merge_override(cli.include.value.clone(), ConfigSource::Cli, None, None);
2489            sourced_config.global.respect_gitignore.merge_override(
2490                cli.respect_gitignore.value,
2491                ConfigSource::Cli,
2492                None,
2493                None,
2494            );
2495            sourced_config
2496                .global
2497                .fixable
2498                .merge_override(cli.fixable.value.clone(), ConfigSource::Cli, None, None);
2499            sourced_config
2500                .global
2501                .unfixable
2502                .merge_override(cli.unfixable.value.clone(), ConfigSource::Cli, None, None);
2503            // No rule-specific CLI overrides implemented yet
2504        }
2505
2506        // Unknown keys are now collected during parsing and validated via validate_config_sourced()
2507
2508        Ok(sourced_config)
2509    }
2510
2511    /// Load and merge configurations from files and CLI overrides.
2512    /// If skip_auto_discovery is true, only explicit config paths are loaded.
2513    pub fn load_with_discovery(
2514        config_path: Option<&str>,
2515        cli_overrides: Option<&SourcedGlobalConfig>,
2516        skip_auto_discovery: bool,
2517    ) -> Result<Self, ConfigError> {
2518        Self::load_with_discovery_impl(config_path, cli_overrides, skip_auto_discovery, None)
2519    }
2520
2521    /// Validate the configuration against a rule registry.
2522    ///
2523    /// This method transitions the config from `ConfigLoaded` to `ConfigValidated` state,
2524    /// enabling conversion to `Config`. Validation warnings are stored in the config
2525    /// and can be displayed to the user.
2526    ///
2527    /// # Example
2528    ///
2529    /// ```ignore
2530    /// let loaded = SourcedConfig::load_with_discovery(path, None, false)?;
2531    /// let validated = loaded.validate(&registry)?;
2532    /// let config: Config = validated.into();
2533    /// ```
2534    pub fn validate(self, registry: &RuleRegistry) -> Result<SourcedConfig<ConfigValidated>, ConfigError> {
2535        let warnings = validate_config_sourced_internal(&self, registry);
2536
2537        Ok(SourcedConfig {
2538            global: self.global,
2539            per_file_ignores: self.per_file_ignores,
2540            rules: self.rules,
2541            loaded_files: self.loaded_files,
2542            unknown_keys: self.unknown_keys,
2543            project_root: self.project_root,
2544            validation_warnings: warnings,
2545            _state: PhantomData,
2546        })
2547    }
2548
2549    /// Validate and convert to Config in one step (convenience method).
2550    ///
2551    /// This combines `validate()` and `into()` for callers who want the
2552    /// validation warnings separately.
2553    pub fn validate_into(self, registry: &RuleRegistry) -> Result<(Config, Vec<ConfigValidationWarning>), ConfigError> {
2554        let validated = self.validate(registry)?;
2555        let warnings = validated.validation_warnings.clone();
2556        Ok((validated.into(), warnings))
2557    }
2558
2559    /// Skip validation and convert directly to ConfigValidated state.
2560    ///
2561    /// # Safety
2562    ///
2563    /// This method bypasses validation. Use only when:
2564    /// - You've already validated via `validate_config_sourced()`
2565    /// - You're in test code that doesn't need validation
2566    /// - You're migrating legacy code and will add proper validation later
2567    ///
2568    /// Prefer `validate()` for new code.
2569    pub fn into_validated_unchecked(self) -> SourcedConfig<ConfigValidated> {
2570        SourcedConfig {
2571            global: self.global,
2572            per_file_ignores: self.per_file_ignores,
2573            rules: self.rules,
2574            loaded_files: self.loaded_files,
2575            unknown_keys: self.unknown_keys,
2576            project_root: self.project_root,
2577            validation_warnings: Vec::new(),
2578            _state: PhantomData,
2579        }
2580    }
2581}
2582
2583/// Convert a validated configuration to the final Config type.
2584///
2585/// This implementation only exists for `SourcedConfig<ConfigValidated>`,
2586/// ensuring that validation must occur before conversion.
2587impl From<SourcedConfig<ConfigValidated>> for Config {
2588    fn from(sourced: SourcedConfig<ConfigValidated>) -> Self {
2589        let mut rules = BTreeMap::new();
2590        for (rule_name, sourced_rule_cfg) in sourced.rules {
2591            // Normalize rule name to uppercase for case-insensitive lookup
2592            let normalized_rule_name = rule_name.to_ascii_uppercase();
2593            let severity = sourced_rule_cfg.severity.map(|sv| sv.value);
2594            let mut values = BTreeMap::new();
2595            for (key, sourced_val) in sourced_rule_cfg.values {
2596                values.insert(key, sourced_val.value);
2597            }
2598            rules.insert(normalized_rule_name, RuleConfig { severity, values });
2599        }
2600        #[allow(deprecated)]
2601        let global = GlobalConfig {
2602            enable: sourced.global.enable.value,
2603            disable: sourced.global.disable.value,
2604            exclude: sourced.global.exclude.value,
2605            include: sourced.global.include.value,
2606            respect_gitignore: sourced.global.respect_gitignore.value,
2607            line_length: sourced.global.line_length.value,
2608            output_format: sourced.global.output_format.as_ref().map(|v| v.value.clone()),
2609            fixable: sourced.global.fixable.value,
2610            unfixable: sourced.global.unfixable.value,
2611            flavor: sourced.global.flavor.value,
2612            force_exclude: sourced.global.force_exclude.value,
2613            cache_dir: sourced.global.cache_dir.as_ref().map(|v| v.value.clone()),
2614            cache: sourced.global.cache.value,
2615        };
2616        Config {
2617            global,
2618            per_file_ignores: sourced.per_file_ignores.value,
2619            rules,
2620            project_root: sourced.project_root,
2621        }
2622    }
2623}
2624
2625/// Registry of all known rules and their config schemas
2626pub struct RuleRegistry {
2627    /// Map of rule name (e.g. "MD013") to set of valid config keys and their TOML value types
2628    pub rule_schemas: std::collections::BTreeMap<String, toml::map::Map<String, toml::Value>>,
2629    /// Map of rule name to config key aliases
2630    pub rule_aliases: std::collections::BTreeMap<String, std::collections::HashMap<String, String>>,
2631}
2632
2633impl RuleRegistry {
2634    /// Build a registry from a list of rules
2635    pub fn from_rules(rules: &[Box<dyn Rule>]) -> Self {
2636        let mut rule_schemas = std::collections::BTreeMap::new();
2637        let mut rule_aliases = std::collections::BTreeMap::new();
2638
2639        for rule in rules {
2640            let norm_name = if let Some((name, toml::Value::Table(table))) = rule.default_config_section() {
2641                let norm_name = normalize_key(&name); // Normalize the name from default_config_section
2642                rule_schemas.insert(norm_name.clone(), table);
2643                norm_name
2644            } else {
2645                let norm_name = normalize_key(rule.name()); // Normalize the name from rule.name()
2646                rule_schemas.insert(norm_name.clone(), toml::map::Map::new());
2647                norm_name
2648            };
2649
2650            // Store aliases if the rule provides them
2651            if let Some(aliases) = rule.config_aliases() {
2652                rule_aliases.insert(norm_name, aliases);
2653            }
2654        }
2655
2656        RuleRegistry {
2657            rule_schemas,
2658            rule_aliases,
2659        }
2660    }
2661
2662    /// Get all known rule names
2663    pub fn rule_names(&self) -> std::collections::BTreeSet<String> {
2664        self.rule_schemas.keys().cloned().collect()
2665    }
2666
2667    /// Get the valid configuration keys for a rule, including both original and normalized variants
2668    pub fn config_keys_for(&self, rule: &str) -> Option<std::collections::BTreeSet<String>> {
2669        self.rule_schemas.get(rule).map(|schema| {
2670            let mut all_keys = std::collections::BTreeSet::new();
2671
2672            // Always allow 'severity' for any rule
2673            all_keys.insert("severity".to_string());
2674
2675            // Add original keys from schema
2676            for key in schema.keys() {
2677                all_keys.insert(key.clone());
2678            }
2679
2680            // Add normalized variants for markdownlint compatibility
2681            for key in schema.keys() {
2682                // Add kebab-case variant
2683                all_keys.insert(key.replace('_', "-"));
2684                // Add snake_case variant
2685                all_keys.insert(key.replace('-', "_"));
2686                // Add normalized variant
2687                all_keys.insert(normalize_key(key));
2688            }
2689
2690            // Add any aliases defined by the rule
2691            if let Some(aliases) = self.rule_aliases.get(rule) {
2692                for alias_key in aliases.keys() {
2693                    all_keys.insert(alias_key.clone());
2694                    // Also add normalized variants of the alias
2695                    all_keys.insert(alias_key.replace('_', "-"));
2696                    all_keys.insert(alias_key.replace('-', "_"));
2697                    all_keys.insert(normalize_key(alias_key));
2698                }
2699            }
2700
2701            all_keys
2702        })
2703    }
2704
2705    /// Get the expected value type for a rule's configuration key, trying variants
2706    pub fn expected_value_for(&self, rule: &str, key: &str) -> Option<&toml::Value> {
2707        if let Some(schema) = self.rule_schemas.get(rule) {
2708            // Check if this key is an alias
2709            if let Some(aliases) = self.rule_aliases.get(rule)
2710                && let Some(canonical_key) = aliases.get(key)
2711            {
2712                // Use the canonical key for schema lookup
2713                if let Some(value) = schema.get(canonical_key) {
2714                    return Some(value);
2715                }
2716            }
2717
2718            // Try the original key
2719            if let Some(value) = schema.get(key) {
2720                return Some(value);
2721            }
2722
2723            // Try key variants
2724            let key_variants = [
2725                key.replace('-', "_"), // Convert kebab-case to snake_case
2726                key.replace('_', "-"), // Convert snake_case to kebab-case
2727                normalize_key(key),    // Normalized key (lowercase, kebab-case)
2728            ];
2729
2730            for variant in &key_variants {
2731                if let Some(value) = schema.get(variant) {
2732                    return Some(value);
2733                }
2734            }
2735        }
2736        None
2737    }
2738
2739    /// Resolve any rule name (canonical or alias) to its canonical form
2740    /// Returns None if the rule name is not recognized
2741    ///
2742    /// Resolution order:
2743    /// 1. Direct canonical name match
2744    /// 2. Static aliases (built-in markdownlint aliases)
2745    pub fn resolve_rule_name(&self, name: &str) -> Option<String> {
2746        // Try normalized canonical name first
2747        let normalized = normalize_key(name);
2748        if self.rule_schemas.contains_key(&normalized) {
2749            return Some(normalized);
2750        }
2751
2752        // Try static alias resolution (O(1) perfect hash lookup)
2753        resolve_rule_name_alias(name).map(|s| s.to_string())
2754    }
2755}
2756
2757/// Compile-time perfect hash map for O(1) rule alias lookups
2758/// Uses phf for zero-cost abstraction - compiles to direct jumps
2759static RULE_ALIAS_MAP: phf::Map<&'static str, &'static str> = phf::phf_map! {
2760    // Canonical names (identity mapping for consistency)
2761    "MD001" => "MD001",
2762    "MD003" => "MD003",
2763    "MD004" => "MD004",
2764    "MD005" => "MD005",
2765    "MD007" => "MD007",
2766    "MD008" => "MD008",
2767    "MD009" => "MD009",
2768    "MD010" => "MD010",
2769    "MD011" => "MD011",
2770    "MD012" => "MD012",
2771    "MD013" => "MD013",
2772    "MD014" => "MD014",
2773    "MD015" => "MD015",
2774    "MD018" => "MD018",
2775    "MD019" => "MD019",
2776    "MD020" => "MD020",
2777    "MD021" => "MD021",
2778    "MD022" => "MD022",
2779    "MD023" => "MD023",
2780    "MD024" => "MD024",
2781    "MD025" => "MD025",
2782    "MD026" => "MD026",
2783    "MD027" => "MD027",
2784    "MD028" => "MD028",
2785    "MD029" => "MD029",
2786    "MD030" => "MD030",
2787    "MD031" => "MD031",
2788    "MD032" => "MD032",
2789    "MD033" => "MD033",
2790    "MD034" => "MD034",
2791    "MD035" => "MD035",
2792    "MD036" => "MD036",
2793    "MD037" => "MD037",
2794    "MD038" => "MD038",
2795    "MD039" => "MD039",
2796    "MD040" => "MD040",
2797    "MD041" => "MD041",
2798    "MD042" => "MD042",
2799    "MD043" => "MD043",
2800    "MD044" => "MD044",
2801    "MD045" => "MD045",
2802    "MD046" => "MD046",
2803    "MD047" => "MD047",
2804    "MD048" => "MD048",
2805    "MD049" => "MD049",
2806    "MD050" => "MD050",
2807    "MD051" => "MD051",
2808    "MD052" => "MD052",
2809    "MD053" => "MD053",
2810    "MD054" => "MD054",
2811    "MD055" => "MD055",
2812    "MD056" => "MD056",
2813    "MD057" => "MD057",
2814    "MD058" => "MD058",
2815    "MD059" => "MD059",
2816    "MD060" => "MD060",
2817    "MD061" => "MD061",
2818
2819    // Aliases (hyphen format)
2820    "HEADING-INCREMENT" => "MD001",
2821    "HEADING-STYLE" => "MD003",
2822    "UL-STYLE" => "MD004",
2823    "LIST-INDENT" => "MD005",
2824    "UL-INDENT" => "MD007",
2825    "NO-TRAILING-SPACES" => "MD009",
2826    "NO-HARD-TABS" => "MD010",
2827    "NO-REVERSED-LINKS" => "MD011",
2828    "NO-MULTIPLE-BLANKS" => "MD012",
2829    "LINE-LENGTH" => "MD013",
2830    "COMMANDS-SHOW-OUTPUT" => "MD014",
2831    "NO-MISSING-SPACE-AFTER-LIST-MARKER" => "MD015",
2832    "NO-MISSING-SPACE-ATX" => "MD018",
2833    "NO-MULTIPLE-SPACE-ATX" => "MD019",
2834    "NO-MISSING-SPACE-CLOSED-ATX" => "MD020",
2835    "NO-MULTIPLE-SPACE-CLOSED-ATX" => "MD021",
2836    "BLANKS-AROUND-HEADINGS" => "MD022",
2837    "HEADING-START-LEFT" => "MD023",
2838    "NO-DUPLICATE-HEADING" => "MD024",
2839    "SINGLE-TITLE" => "MD025",
2840    "SINGLE-H1" => "MD025",
2841    "NO-TRAILING-PUNCTUATION" => "MD026",
2842    "NO-MULTIPLE-SPACE-BLOCKQUOTE" => "MD027",
2843    "NO-BLANKS-BLOCKQUOTE" => "MD028",
2844    "OL-PREFIX" => "MD029",
2845    "LIST-MARKER-SPACE" => "MD030",
2846    "BLANKS-AROUND-FENCES" => "MD031",
2847    "BLANKS-AROUND-LISTS" => "MD032",
2848    "NO-INLINE-HTML" => "MD033",
2849    "NO-BARE-URLS" => "MD034",
2850    "HR-STYLE" => "MD035",
2851    "NO-EMPHASIS-AS-HEADING" => "MD036",
2852    "NO-SPACE-IN-EMPHASIS" => "MD037",
2853    "NO-SPACE-IN-CODE" => "MD038",
2854    "NO-SPACE-IN-LINKS" => "MD039",
2855    "FENCED-CODE-LANGUAGE" => "MD040",
2856    "FIRST-LINE-HEADING" => "MD041",
2857    "FIRST-LINE-H1" => "MD041",
2858    "NO-EMPTY-LINKS" => "MD042",
2859    "REQUIRED-HEADINGS" => "MD043",
2860    "PROPER-NAMES" => "MD044",
2861    "NO-ALT-TEXT" => "MD045",
2862    "CODE-BLOCK-STYLE" => "MD046",
2863    "SINGLE-TRAILING-NEWLINE" => "MD047",
2864    "CODE-FENCE-STYLE" => "MD048",
2865    "EMPHASIS-STYLE" => "MD049",
2866    "STRONG-STYLE" => "MD050",
2867    "LINK-FRAGMENTS" => "MD051",
2868    "REFERENCE-LINKS-IMAGES" => "MD052",
2869    "LINK-IMAGE-REFERENCE-DEFINITIONS" => "MD053",
2870    "LINK-IMAGE-STYLE" => "MD054",
2871    "TABLE-PIPE-STYLE" => "MD055",
2872    "TABLE-COLUMN-COUNT" => "MD056",
2873    "EXISTING-RELATIVE-LINKS" => "MD057",
2874    "BLANKS-AROUND-TABLES" => "MD058",
2875    "TABLE-CELL-ALIGNMENT" => "MD059",
2876    "TABLE-FORMAT" => "MD060",
2877    "FORBIDDEN-TERMS" => "MD061",
2878};
2879
2880/// Resolve a rule name alias to its canonical form with O(1) perfect hash lookup
2881/// Converts rule aliases (like "ul-style", "line-length") to canonical IDs (like "MD004", "MD013")
2882/// Returns None if the rule name is not recognized
2883pub(crate) fn resolve_rule_name_alias(key: &str) -> Option<&'static str> {
2884    // Normalize: uppercase and replace underscores with hyphens
2885    let normalized_key = key.to_ascii_uppercase().replace('_', "-");
2886
2887    // O(1) perfect hash lookup
2888    RULE_ALIAS_MAP.get(normalized_key.as_str()).copied()
2889}
2890
2891/// Represents a config validation warning or error
2892#[derive(Debug, Clone)]
2893pub struct ConfigValidationWarning {
2894    pub message: String,
2895    pub rule: Option<String>,
2896    pub key: Option<String>,
2897}
2898
2899/// Internal validation function that works with any SourcedConfig state.
2900/// This is used by both the public `validate_config_sourced` and the typestate `validate()` method.
2901fn validate_config_sourced_internal<S>(
2902    sourced: &SourcedConfig<S>,
2903    registry: &RuleRegistry,
2904) -> Vec<ConfigValidationWarning> {
2905    validate_config_sourced_impl(&sourced.rules, &sourced.unknown_keys, registry)
2906}
2907
2908/// Core validation implementation that doesn't depend on SourcedConfig type parameter.
2909fn validate_config_sourced_impl(
2910    rules: &BTreeMap<String, SourcedRuleConfig>,
2911    unknown_keys: &[(String, String, Option<String>)],
2912    registry: &RuleRegistry,
2913) -> Vec<ConfigValidationWarning> {
2914    let mut warnings = Vec::new();
2915    let known_rules = registry.rule_names();
2916    // 1. Unknown rules
2917    for rule in rules.keys() {
2918        if !known_rules.contains(rule) {
2919            // Include both canonical names AND aliases for fuzzy matching
2920            let all_rule_names: Vec<String> = RULE_ALIAS_MAP.keys().map(|s| s.to_string()).collect();
2921            let message = if let Some(suggestion) = suggest_similar_key(rule, &all_rule_names) {
2922                // Convert alias suggestions to lowercase for better UX (MD001 stays uppercase, ul-style becomes lowercase)
2923                let formatted_suggestion = if suggestion.starts_with("MD") {
2924                    suggestion
2925                } else {
2926                    suggestion.to_lowercase()
2927                };
2928                format!("Unknown rule in config: {rule} (did you mean: {formatted_suggestion}?)")
2929            } else {
2930                format!("Unknown rule in config: {rule}")
2931            };
2932            warnings.push(ConfigValidationWarning {
2933                message,
2934                rule: Some(rule.clone()),
2935                key: None,
2936            });
2937        }
2938    }
2939    // 2. Unknown options and type mismatches
2940    for (rule, rule_cfg) in rules {
2941        if let Some(valid_keys) = registry.config_keys_for(rule) {
2942            for key in rule_cfg.values.keys() {
2943                if !valid_keys.contains(key) {
2944                    let valid_keys_vec: Vec<String> = valid_keys.iter().cloned().collect();
2945                    let message = if let Some(suggestion) = suggest_similar_key(key, &valid_keys_vec) {
2946                        format!("Unknown option for rule {rule}: {key} (did you mean: {suggestion}?)")
2947                    } else {
2948                        format!("Unknown option for rule {rule}: {key}")
2949                    };
2950                    warnings.push(ConfigValidationWarning {
2951                        message,
2952                        rule: Some(rule.clone()),
2953                        key: Some(key.clone()),
2954                    });
2955                } else {
2956                    // Type check: compare type of value to type of default
2957                    if let Some(expected) = registry.expected_value_for(rule, key) {
2958                        let actual = &rule_cfg.values[key].value;
2959                        if !toml_value_type_matches(expected, actual) {
2960                            warnings.push(ConfigValidationWarning {
2961                                message: format!(
2962                                    "Type mismatch for {}.{}: expected {}, got {}",
2963                                    rule,
2964                                    key,
2965                                    toml_type_name(expected),
2966                                    toml_type_name(actual)
2967                                ),
2968                                rule: Some(rule.clone()),
2969                                key: Some(key.clone()),
2970                            });
2971                        }
2972                    }
2973                }
2974            }
2975        }
2976    }
2977    // 3. Unknown global options (from unknown_keys)
2978    let known_global_keys = vec![
2979        "enable".to_string(),
2980        "disable".to_string(),
2981        "include".to_string(),
2982        "exclude".to_string(),
2983        "respect-gitignore".to_string(),
2984        "line-length".to_string(),
2985        "fixable".to_string(),
2986        "unfixable".to_string(),
2987        "flavor".to_string(),
2988        "force-exclude".to_string(),
2989        "output-format".to_string(),
2990        "cache-dir".to_string(),
2991        "cache".to_string(),
2992    ];
2993
2994    for (section, key, file_path) in unknown_keys {
2995        if section.contains("[global]") || section.contains("[tool.rumdl]") {
2996            let message = if let Some(suggestion) = suggest_similar_key(key, &known_global_keys) {
2997                if let Some(path) = file_path {
2998                    format!("Unknown global option in {path}: {key} (did you mean: {suggestion}?)")
2999                } else {
3000                    format!("Unknown global option: {key} (did you mean: {suggestion}?)")
3001                }
3002            } else if let Some(path) = file_path {
3003                format!("Unknown global option in {path}: {key}")
3004            } else {
3005                format!("Unknown global option: {key}")
3006            };
3007            warnings.push(ConfigValidationWarning {
3008                message,
3009                rule: None,
3010                key: Some(key.clone()),
3011            });
3012        } else if !key.is_empty() {
3013            // This is an unknown rule section (key is empty means it's a section header)
3014            continue;
3015        } else {
3016            // Unknown rule section - suggest similar rule names
3017            let rule_name = section.trim_matches(|c| c == '[' || c == ']');
3018            let all_rule_names: Vec<String> = RULE_ALIAS_MAP.keys().map(|s| s.to_string()).collect();
3019            let message = if let Some(suggestion) = suggest_similar_key(rule_name, &all_rule_names) {
3020                // Convert alias suggestions to lowercase for better UX (MD001 stays uppercase, ul-style becomes lowercase)
3021                let formatted_suggestion = if suggestion.starts_with("MD") {
3022                    suggestion
3023                } else {
3024                    suggestion.to_lowercase()
3025                };
3026                if let Some(path) = file_path {
3027                    format!("Unknown rule in {path}: {rule_name} (did you mean: {formatted_suggestion}?)")
3028                } else {
3029                    format!("Unknown rule in config: {rule_name} (did you mean: {formatted_suggestion}?)")
3030                }
3031            } else if let Some(path) = file_path {
3032                format!("Unknown rule in {path}: {rule_name}")
3033            } else {
3034                format!("Unknown rule in config: {rule_name}")
3035            };
3036            warnings.push(ConfigValidationWarning {
3037                message,
3038                rule: None,
3039                key: None,
3040            });
3041        }
3042    }
3043    warnings
3044}
3045
3046/// Validate a loaded config against the rule registry, using SourcedConfig for unknown key tracking.
3047///
3048/// This is the legacy API that works with `SourcedConfig<ConfigLoaded>`.
3049/// For new code, prefer using `sourced.validate(&registry)` which returns a
3050/// `SourcedConfig<ConfigValidated>` that can be converted to `Config`.
3051pub fn validate_config_sourced(
3052    sourced: &SourcedConfig<ConfigLoaded>,
3053    registry: &RuleRegistry,
3054) -> Vec<ConfigValidationWarning> {
3055    validate_config_sourced_internal(sourced, registry)
3056}
3057
3058/// Validate a config that has already been validated (no-op, returns stored warnings).
3059///
3060/// This exists for API consistency - validated configs already have their warnings stored.
3061pub fn validate_config_sourced_validated(
3062    sourced: &SourcedConfig<ConfigValidated>,
3063    _registry: &RuleRegistry,
3064) -> Vec<ConfigValidationWarning> {
3065    sourced.validation_warnings.clone()
3066}
3067
3068fn toml_type_name(val: &toml::Value) -> &'static str {
3069    match val {
3070        toml::Value::String(_) => "string",
3071        toml::Value::Integer(_) => "integer",
3072        toml::Value::Float(_) => "float",
3073        toml::Value::Boolean(_) => "boolean",
3074        toml::Value::Array(_) => "array",
3075        toml::Value::Table(_) => "table",
3076        toml::Value::Datetime(_) => "datetime",
3077    }
3078}
3079
3080/// Calculate Levenshtein distance between two strings (simple implementation)
3081fn levenshtein_distance(s1: &str, s2: &str) -> usize {
3082    let len1 = s1.len();
3083    let len2 = s2.len();
3084
3085    if len1 == 0 {
3086        return len2;
3087    }
3088    if len2 == 0 {
3089        return len1;
3090    }
3091
3092    let s1_chars: Vec<char> = s1.chars().collect();
3093    let s2_chars: Vec<char> = s2.chars().collect();
3094
3095    let mut prev_row: Vec<usize> = (0..=len2).collect();
3096    let mut curr_row = vec![0; len2 + 1];
3097
3098    for i in 1..=len1 {
3099        curr_row[0] = i;
3100        for j in 1..=len2 {
3101            let cost = if s1_chars[i - 1] == s2_chars[j - 1] { 0 } else { 1 };
3102            curr_row[j] = (prev_row[j] + 1)          // deletion
3103                .min(curr_row[j - 1] + 1)            // insertion
3104                .min(prev_row[j - 1] + cost); // substitution
3105        }
3106        std::mem::swap(&mut prev_row, &mut curr_row);
3107    }
3108
3109    prev_row[len2]
3110}
3111
3112/// Suggest a similar key from a list of valid keys using fuzzy matching
3113fn suggest_similar_key(unknown: &str, valid_keys: &[String]) -> Option<String> {
3114    let unknown_lower = unknown.to_lowercase();
3115    let max_distance = 2.max(unknown.len() / 3); // Allow up to 2 edits or 30% of string length
3116
3117    let mut best_match: Option<(String, usize)> = None;
3118
3119    for valid in valid_keys {
3120        let valid_lower = valid.to_lowercase();
3121        let distance = levenshtein_distance(&unknown_lower, &valid_lower);
3122
3123        if distance <= max_distance {
3124            if let Some((_, best_dist)) = &best_match {
3125                if distance < *best_dist {
3126                    best_match = Some((valid.clone(), distance));
3127                }
3128            } else {
3129                best_match = Some((valid.clone(), distance));
3130            }
3131        }
3132    }
3133
3134    best_match.map(|(key, _)| key)
3135}
3136
3137fn toml_value_type_matches(expected: &toml::Value, actual: &toml::Value) -> bool {
3138    use toml::Value::*;
3139    match (expected, actual) {
3140        (String(_), String(_)) => true,
3141        (Integer(_), Integer(_)) => true,
3142        (Float(_), Float(_)) => true,
3143        (Boolean(_), Boolean(_)) => true,
3144        (Array(_), Array(_)) => true,
3145        (Table(_), Table(_)) => true,
3146        (Datetime(_), Datetime(_)) => true,
3147        // Allow integer for float
3148        (Float(_), Integer(_)) => true,
3149        _ => false,
3150    }
3151}
3152
3153/// Parses pyproject.toml content and extracts the [tool.rumdl] section if present.
3154fn parse_pyproject_toml(content: &str, path: &str) -> Result<Option<SourcedConfigFragment>, ConfigError> {
3155    let doc: toml::Value =
3156        toml::from_str(content).map_err(|e| ConfigError::ParseError(format!("{path}: Failed to parse TOML: {e}")))?;
3157    let mut fragment = SourcedConfigFragment::default();
3158    let source = ConfigSource::PyprojectToml;
3159    let file = Some(path.to_string());
3160
3161    // Create rule registry for alias resolution
3162    let all_rules = rules::all_rules(&Config::default());
3163    let registry = RuleRegistry::from_rules(&all_rules);
3164
3165    // 1. Handle [tool.rumdl] and [tool.rumdl.global] sections
3166    if let Some(rumdl_config) = doc.get("tool").and_then(|t| t.get("rumdl"))
3167        && let Some(rumdl_table) = rumdl_config.as_table()
3168    {
3169        // Helper function to extract global config from a table
3170        let extract_global_config = |fragment: &mut SourcedConfigFragment, table: &toml::value::Table| {
3171            // Extract global options from the given table
3172            if let Some(enable) = table.get("enable")
3173                && let Ok(values) = Vec::<String>::deserialize(enable.clone())
3174            {
3175                // Resolve rule name aliases (e.g., "ul-style" -> "MD004")
3176                let normalized_values = values
3177                    .into_iter()
3178                    .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3179                    .collect();
3180                fragment
3181                    .global
3182                    .enable
3183                    .push_override(normalized_values, source, file.clone(), None);
3184            }
3185
3186            if let Some(disable) = table.get("disable")
3187                && let Ok(values) = Vec::<String>::deserialize(disable.clone())
3188            {
3189                // Resolve rule name aliases
3190                let normalized_values: Vec<String> = values
3191                    .into_iter()
3192                    .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3193                    .collect();
3194                fragment
3195                    .global
3196                    .disable
3197                    .push_override(normalized_values, source, file.clone(), None);
3198            }
3199
3200            if let Some(include) = table.get("include")
3201                && let Ok(values) = Vec::<String>::deserialize(include.clone())
3202            {
3203                fragment
3204                    .global
3205                    .include
3206                    .push_override(values, source, file.clone(), None);
3207            }
3208
3209            if let Some(exclude) = table.get("exclude")
3210                && let Ok(values) = Vec::<String>::deserialize(exclude.clone())
3211            {
3212                fragment
3213                    .global
3214                    .exclude
3215                    .push_override(values, source, file.clone(), None);
3216            }
3217
3218            if let Some(respect_gitignore) = table
3219                .get("respect-gitignore")
3220                .or_else(|| table.get("respect_gitignore"))
3221                && let Ok(value) = bool::deserialize(respect_gitignore.clone())
3222            {
3223                fragment
3224                    .global
3225                    .respect_gitignore
3226                    .push_override(value, source, file.clone(), None);
3227            }
3228
3229            if let Some(force_exclude) = table.get("force-exclude").or_else(|| table.get("force_exclude"))
3230                && let Ok(value) = bool::deserialize(force_exclude.clone())
3231            {
3232                fragment
3233                    .global
3234                    .force_exclude
3235                    .push_override(value, source, file.clone(), None);
3236            }
3237
3238            if let Some(output_format) = table.get("output-format").or_else(|| table.get("output_format"))
3239                && let Ok(value) = String::deserialize(output_format.clone())
3240            {
3241                if fragment.global.output_format.is_none() {
3242                    fragment.global.output_format = Some(SourcedValue::new(value.clone(), source));
3243                } else {
3244                    fragment
3245                        .global
3246                        .output_format
3247                        .as_mut()
3248                        .unwrap()
3249                        .push_override(value, source, file.clone(), None);
3250                }
3251            }
3252
3253            if let Some(fixable) = table.get("fixable")
3254                && let Ok(values) = Vec::<String>::deserialize(fixable.clone())
3255            {
3256                let normalized_values = values
3257                    .into_iter()
3258                    .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3259                    .collect();
3260                fragment
3261                    .global
3262                    .fixable
3263                    .push_override(normalized_values, source, file.clone(), None);
3264            }
3265
3266            if let Some(unfixable) = table.get("unfixable")
3267                && let Ok(values) = Vec::<String>::deserialize(unfixable.clone())
3268            {
3269                let normalized_values = values
3270                    .into_iter()
3271                    .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3272                    .collect();
3273                fragment
3274                    .global
3275                    .unfixable
3276                    .push_override(normalized_values, source, file.clone(), None);
3277            }
3278
3279            if let Some(flavor) = table.get("flavor")
3280                && let Ok(value) = MarkdownFlavor::deserialize(flavor.clone())
3281            {
3282                fragment.global.flavor.push_override(value, source, file.clone(), None);
3283            }
3284
3285            // Handle line-length special case - this should set the global line_length
3286            if let Some(line_length) = table.get("line-length").or_else(|| table.get("line_length"))
3287                && let Ok(value) = u64::deserialize(line_length.clone())
3288            {
3289                fragment
3290                    .global
3291                    .line_length
3292                    .push_override(LineLength::new(value as usize), source, file.clone(), None);
3293
3294                // Also add to MD013 rule config for backward compatibility
3295                let norm_md013_key = normalize_key("MD013");
3296                let rule_entry = fragment.rules.entry(norm_md013_key).or_default();
3297                let norm_line_length_key = normalize_key("line-length");
3298                let sv = rule_entry
3299                    .values
3300                    .entry(norm_line_length_key)
3301                    .or_insert_with(|| SourcedValue::new(line_length.clone(), ConfigSource::Default));
3302                sv.push_override(line_length.clone(), source, file.clone(), None);
3303            }
3304
3305            if let Some(cache_dir) = table.get("cache-dir").or_else(|| table.get("cache_dir"))
3306                && let Ok(value) = String::deserialize(cache_dir.clone())
3307            {
3308                if fragment.global.cache_dir.is_none() {
3309                    fragment.global.cache_dir = Some(SourcedValue::new(value.clone(), source));
3310                } else {
3311                    fragment
3312                        .global
3313                        .cache_dir
3314                        .as_mut()
3315                        .unwrap()
3316                        .push_override(value, source, file.clone(), None);
3317                }
3318            }
3319
3320            if let Some(cache) = table.get("cache")
3321                && let Ok(value) = bool::deserialize(cache.clone())
3322            {
3323                fragment.global.cache.push_override(value, source, file.clone(), None);
3324            }
3325        };
3326
3327        // First, check for [tool.rumdl.global] section
3328        if let Some(global_table) = rumdl_table.get("global").and_then(|g| g.as_table()) {
3329            extract_global_config(&mut fragment, global_table);
3330        }
3331
3332        // Also extract global options from [tool.rumdl] directly (for flat structure)
3333        extract_global_config(&mut fragment, rumdl_table);
3334
3335        // --- Extract per-file-ignores configurations ---
3336        // Check both hyphenated and underscored versions for compatibility
3337        let per_file_ignores_key = rumdl_table
3338            .get("per-file-ignores")
3339            .or_else(|| rumdl_table.get("per_file_ignores"));
3340
3341        if let Some(per_file_ignores_value) = per_file_ignores_key
3342            && let Some(per_file_table) = per_file_ignores_value.as_table()
3343        {
3344            let mut per_file_map = HashMap::new();
3345            for (pattern, rules_value) in per_file_table {
3346                if let Ok(rules) = Vec::<String>::deserialize(rules_value.clone()) {
3347                    let normalized_rules = rules
3348                        .into_iter()
3349                        .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3350                        .collect();
3351                    per_file_map.insert(pattern.clone(), normalized_rules);
3352                } else {
3353                    log::warn!(
3354                        "[WARN] Expected array for per-file-ignores pattern '{pattern}' in {path}, found {rules_value:?}"
3355                    );
3356                }
3357            }
3358            fragment
3359                .per_file_ignores
3360                .push_override(per_file_map, source, file.clone(), None);
3361        }
3362
3363        // --- Extract rule-specific configurations ---
3364        for (key, value) in rumdl_table {
3365            let norm_rule_key = normalize_key(key);
3366
3367            // Skip keys already handled as global or special cases
3368            // Note: Only skip these if they're NOT tables (rule sections are tables)
3369            let is_global_key = [
3370                "enable",
3371                "disable",
3372                "include",
3373                "exclude",
3374                "respect_gitignore",
3375                "respect-gitignore",
3376                "force_exclude",
3377                "force-exclude",
3378                "output_format",
3379                "output-format",
3380                "fixable",
3381                "unfixable",
3382                "per-file-ignores",
3383                "per_file_ignores",
3384                "global",
3385                "flavor",
3386                "cache_dir",
3387                "cache-dir",
3388                "cache",
3389            ]
3390            .contains(&norm_rule_key.as_str());
3391
3392            // Special handling for line-length: could be global config OR rule section
3393            let is_line_length_global =
3394                (norm_rule_key == "line-length" || norm_rule_key == "line_length") && !value.is_table();
3395
3396            if is_global_key || is_line_length_global {
3397                continue;
3398            }
3399
3400            // Try to resolve as a rule name (handles both canonical names and aliases)
3401            if let Some(resolved_rule_name) = registry.resolve_rule_name(key)
3402                && value.is_table()
3403                && let Some(rule_config_table) = value.as_table()
3404            {
3405                let rule_entry = fragment.rules.entry(resolved_rule_name.clone()).or_default();
3406                for (rk, rv) in rule_config_table {
3407                    let norm_rk = normalize_key(rk);
3408
3409                    // Special handling for severity - store in rule_entry.severity
3410                    if norm_rk == "severity" {
3411                        if let Ok(severity) = crate::rule::Severity::deserialize(rv.clone()) {
3412                            if rule_entry.severity.is_none() {
3413                                rule_entry.severity = Some(SourcedValue::new(severity, source));
3414                            } else {
3415                                rule_entry.severity.as_mut().unwrap().push_override(
3416                                    severity,
3417                                    source,
3418                                    file.clone(),
3419                                    None,
3420                                );
3421                            }
3422                        }
3423                        continue; // Skip regular value processing for severity
3424                    }
3425
3426                    let toml_val = rv.clone();
3427
3428                    let sv = rule_entry
3429                        .values
3430                        .entry(norm_rk.clone())
3431                        .or_insert_with(|| SourcedValue::new(toml_val.clone(), ConfigSource::Default));
3432                    sv.push_override(toml_val, source, file.clone(), None);
3433                }
3434            } else if registry.resolve_rule_name(key).is_none() {
3435                // Key is not a global/special key and not a recognized rule name
3436                // Track unknown keys under [tool.rumdl] for validation
3437                fragment
3438                    .unknown_keys
3439                    .push(("[tool.rumdl]".to_string(), key.to_string(), Some(path.to_string())));
3440            }
3441        }
3442    }
3443
3444    // 2. Handle [tool.rumdl.MDxxx] sections as rule-specific config (nested under [tool])
3445    if let Some(tool_table) = doc.get("tool").and_then(|t| t.as_table()) {
3446        for (key, value) in tool_table.iter() {
3447            if let Some(rule_name) = key.strip_prefix("rumdl.") {
3448                // Try to resolve as a rule name (handles both canonical names and aliases)
3449                if let Some(resolved_rule_name) = registry.resolve_rule_name(rule_name) {
3450                    if let Some(rule_table) = value.as_table() {
3451                        let rule_entry = fragment.rules.entry(resolved_rule_name.clone()).or_default();
3452                        for (rk, rv) in rule_table {
3453                            let norm_rk = normalize_key(rk);
3454
3455                            // Special handling for severity - store in rule_entry.severity
3456                            if norm_rk == "severity" {
3457                                if let Ok(severity) = crate::rule::Severity::deserialize(rv.clone()) {
3458                                    if rule_entry.severity.is_none() {
3459                                        rule_entry.severity = Some(SourcedValue::new(severity, source));
3460                                    } else {
3461                                        rule_entry.severity.as_mut().unwrap().push_override(
3462                                            severity,
3463                                            source,
3464                                            file.clone(),
3465                                            None,
3466                                        );
3467                                    }
3468                                }
3469                                continue; // Skip regular value processing for severity
3470                            }
3471
3472                            let toml_val = rv.clone();
3473                            let sv = rule_entry
3474                                .values
3475                                .entry(norm_rk.clone())
3476                                .or_insert_with(|| SourcedValue::new(toml_val.clone(), source));
3477                            sv.push_override(toml_val, source, file.clone(), None);
3478                        }
3479                    }
3480                } else if rule_name.to_ascii_uppercase().starts_with("MD")
3481                    || rule_name.chars().any(|c| c.is_alphabetic())
3482                {
3483                    // Track unknown rule sections like [tool.rumdl.MD999] or [tool.rumdl.unknown-rule]
3484                    fragment.unknown_keys.push((
3485                        format!("[tool.rumdl.{rule_name}]"),
3486                        String::new(),
3487                        Some(path.to_string()),
3488                    ));
3489                }
3490            }
3491        }
3492    }
3493
3494    // 3. Handle [tool.rumdl.MDxxx] sections as top-level keys (e.g., [tool.rumdl.MD007] or [tool.rumdl.line-length])
3495    if let Some(doc_table) = doc.as_table() {
3496        for (key, value) in doc_table.iter() {
3497            if let Some(rule_name) = key.strip_prefix("tool.rumdl.") {
3498                // Try to resolve as a rule name (handles both canonical names and aliases)
3499                if let Some(resolved_rule_name) = registry.resolve_rule_name(rule_name) {
3500                    if let Some(rule_table) = value.as_table() {
3501                        let rule_entry = fragment.rules.entry(resolved_rule_name.clone()).or_default();
3502                        for (rk, rv) in rule_table {
3503                            let norm_rk = normalize_key(rk);
3504
3505                            // Special handling for severity - store in rule_entry.severity
3506                            if norm_rk == "severity" {
3507                                if let Ok(severity) = crate::rule::Severity::deserialize(rv.clone()) {
3508                                    if rule_entry.severity.is_none() {
3509                                        rule_entry.severity = Some(SourcedValue::new(severity, source));
3510                                    } else {
3511                                        rule_entry.severity.as_mut().unwrap().push_override(
3512                                            severity,
3513                                            source,
3514                                            file.clone(),
3515                                            None,
3516                                        );
3517                                    }
3518                                }
3519                                continue; // Skip regular value processing for severity
3520                            }
3521
3522                            let toml_val = rv.clone();
3523                            let sv = rule_entry
3524                                .values
3525                                .entry(norm_rk.clone())
3526                                .or_insert_with(|| SourcedValue::new(toml_val.clone(), source));
3527                            sv.push_override(toml_val, source, file.clone(), None);
3528                        }
3529                    }
3530                } else if rule_name.to_ascii_uppercase().starts_with("MD")
3531                    || rule_name.chars().any(|c| c.is_alphabetic())
3532                {
3533                    // Track unknown rule sections like [tool.rumdl.MD999] or [tool.rumdl.unknown-rule]
3534                    fragment.unknown_keys.push((
3535                        format!("[tool.rumdl.{rule_name}]"),
3536                        String::new(),
3537                        Some(path.to_string()),
3538                    ));
3539                }
3540            }
3541        }
3542    }
3543
3544    // Only return Some(fragment) if any config was found
3545    let has_any = !fragment.global.enable.value.is_empty()
3546        || !fragment.global.disable.value.is_empty()
3547        || !fragment.global.include.value.is_empty()
3548        || !fragment.global.exclude.value.is_empty()
3549        || !fragment.global.fixable.value.is_empty()
3550        || !fragment.global.unfixable.value.is_empty()
3551        || fragment.global.output_format.is_some()
3552        || fragment.global.cache_dir.is_some()
3553        || !fragment.global.cache.value
3554        || !fragment.per_file_ignores.value.is_empty()
3555        || !fragment.rules.is_empty();
3556    if has_any { Ok(Some(fragment)) } else { Ok(None) }
3557}
3558
3559/// Parses rumdl.toml / .rumdl.toml content.
3560fn parse_rumdl_toml(content: &str, path: &str, source: ConfigSource) -> Result<SourcedConfigFragment, ConfigError> {
3561    let doc = content
3562        .parse::<DocumentMut>()
3563        .map_err(|e| ConfigError::ParseError(format!("{path}: Failed to parse TOML: {e}")))?;
3564    let mut fragment = SourcedConfigFragment::default();
3565    // source parameter provided by caller
3566    let file = Some(path.to_string());
3567
3568    // Define known rules before the loop
3569    let all_rules = rules::all_rules(&Config::default());
3570    let registry = RuleRegistry::from_rules(&all_rules);
3571
3572    // Handle [global] section
3573    if let Some(global_item) = doc.get("global")
3574        && let Some(global_table) = global_item.as_table()
3575    {
3576        for (key, value_item) in global_table.iter() {
3577            let norm_key = normalize_key(key);
3578            match norm_key.as_str() {
3579                "enable" | "disable" | "include" | "exclude" => {
3580                    if let Some(toml_edit::Value::Array(formatted_array)) = value_item.as_value() {
3581                        // Corrected: Iterate directly over the Formatted<Array>
3582                        let values: Vec<String> = formatted_array
3583                                .iter()
3584                                .filter_map(|item| item.as_str()) // Extract strings
3585                                .map(|s| s.to_string())
3586                                .collect();
3587
3588                        // Resolve rule name aliases for enable/disable (e.g., "ul-style" -> "MD004")
3589                        let final_values = if norm_key == "enable" || norm_key == "disable" {
3590                            values
3591                                .into_iter()
3592                                .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3593                                .collect()
3594                        } else {
3595                            values
3596                        };
3597
3598                        match norm_key.as_str() {
3599                            "enable" => fragment
3600                                .global
3601                                .enable
3602                                .push_override(final_values, source, file.clone(), None),
3603                            "disable" => {
3604                                fragment
3605                                    .global
3606                                    .disable
3607                                    .push_override(final_values, source, file.clone(), None)
3608                            }
3609                            "include" => {
3610                                fragment
3611                                    .global
3612                                    .include
3613                                    .push_override(final_values, source, file.clone(), None)
3614                            }
3615                            "exclude" => {
3616                                fragment
3617                                    .global
3618                                    .exclude
3619                                    .push_override(final_values, source, file.clone(), None)
3620                            }
3621                            _ => unreachable!("Outer match guarantees only enable/disable/include/exclude"),
3622                        }
3623                    } else {
3624                        log::warn!(
3625                            "[WARN] Expected array for global key '{}' in {}, found {}",
3626                            key,
3627                            path,
3628                            value_item.type_name()
3629                        );
3630                    }
3631                }
3632                "respect_gitignore" | "respect-gitignore" => {
3633                    // Handle both cases
3634                    if let Some(toml_edit::Value::Boolean(formatted_bool)) = value_item.as_value() {
3635                        let val = *formatted_bool.value();
3636                        fragment
3637                            .global
3638                            .respect_gitignore
3639                            .push_override(val, source, file.clone(), None);
3640                    } else {
3641                        log::warn!(
3642                            "[WARN] Expected boolean for global key '{}' in {}, found {}",
3643                            key,
3644                            path,
3645                            value_item.type_name()
3646                        );
3647                    }
3648                }
3649                "force_exclude" | "force-exclude" => {
3650                    // Handle both cases
3651                    if let Some(toml_edit::Value::Boolean(formatted_bool)) = value_item.as_value() {
3652                        let val = *formatted_bool.value();
3653                        fragment
3654                            .global
3655                            .force_exclude
3656                            .push_override(val, source, file.clone(), None);
3657                    } else {
3658                        log::warn!(
3659                            "[WARN] Expected boolean for global key '{}' in {}, found {}",
3660                            key,
3661                            path,
3662                            value_item.type_name()
3663                        );
3664                    }
3665                }
3666                "line_length" | "line-length" => {
3667                    // Handle both cases
3668                    if let Some(toml_edit::Value::Integer(formatted_int)) = value_item.as_value() {
3669                        let val = LineLength::new(*formatted_int.value() as usize);
3670                        fragment
3671                            .global
3672                            .line_length
3673                            .push_override(val, source, file.clone(), None);
3674                    } else {
3675                        log::warn!(
3676                            "[WARN] Expected integer for global key '{}' in {}, found {}",
3677                            key,
3678                            path,
3679                            value_item.type_name()
3680                        );
3681                    }
3682                }
3683                "output_format" | "output-format" => {
3684                    // Handle both cases
3685                    if let Some(toml_edit::Value::String(formatted_string)) = value_item.as_value() {
3686                        let val = formatted_string.value().clone();
3687                        if fragment.global.output_format.is_none() {
3688                            fragment.global.output_format = Some(SourcedValue::new(val.clone(), source));
3689                        } else {
3690                            fragment.global.output_format.as_mut().unwrap().push_override(
3691                                val,
3692                                source,
3693                                file.clone(),
3694                                None,
3695                            );
3696                        }
3697                    } else {
3698                        log::warn!(
3699                            "[WARN] Expected string for global key '{}' in {}, found {}",
3700                            key,
3701                            path,
3702                            value_item.type_name()
3703                        );
3704                    }
3705                }
3706                "cache_dir" | "cache-dir" => {
3707                    // Handle both cases
3708                    if let Some(toml_edit::Value::String(formatted_string)) = value_item.as_value() {
3709                        let val = formatted_string.value().clone();
3710                        if fragment.global.cache_dir.is_none() {
3711                            fragment.global.cache_dir = Some(SourcedValue::new(val.clone(), source));
3712                        } else {
3713                            fragment
3714                                .global
3715                                .cache_dir
3716                                .as_mut()
3717                                .unwrap()
3718                                .push_override(val, source, file.clone(), None);
3719                        }
3720                    } else {
3721                        log::warn!(
3722                            "[WARN] Expected string for global key '{}' in {}, found {}",
3723                            key,
3724                            path,
3725                            value_item.type_name()
3726                        );
3727                    }
3728                }
3729                "cache" => {
3730                    if let Some(toml_edit::Value::Boolean(b)) = value_item.as_value() {
3731                        let val = *b.value();
3732                        fragment.global.cache.push_override(val, source, file.clone(), None);
3733                    } else {
3734                        log::warn!(
3735                            "[WARN] Expected boolean for global key '{}' in {}, found {}",
3736                            key,
3737                            path,
3738                            value_item.type_name()
3739                        );
3740                    }
3741                }
3742                "fixable" => {
3743                    if let Some(toml_edit::Value::Array(formatted_array)) = value_item.as_value() {
3744                        let values: Vec<String> = formatted_array
3745                            .iter()
3746                            .filter_map(|item| item.as_str())
3747                            .map(normalize_key)
3748                            .collect();
3749                        fragment
3750                            .global
3751                            .fixable
3752                            .push_override(values, source, file.clone(), None);
3753                    } else {
3754                        log::warn!(
3755                            "[WARN] Expected array for global key '{}' in {}, found {}",
3756                            key,
3757                            path,
3758                            value_item.type_name()
3759                        );
3760                    }
3761                }
3762                "unfixable" => {
3763                    if let Some(toml_edit::Value::Array(formatted_array)) = value_item.as_value() {
3764                        let values: Vec<String> = formatted_array
3765                            .iter()
3766                            .filter_map(|item| item.as_str())
3767                            .map(|s| registry.resolve_rule_name(s).unwrap_or_else(|| normalize_key(s)))
3768                            .collect();
3769                        fragment
3770                            .global
3771                            .unfixable
3772                            .push_override(values, source, file.clone(), None);
3773                    } else {
3774                        log::warn!(
3775                            "[WARN] Expected array for global key '{}' in {}, found {}",
3776                            key,
3777                            path,
3778                            value_item.type_name()
3779                        );
3780                    }
3781                }
3782                "flavor" => {
3783                    if let Some(toml_edit::Value::String(formatted_string)) = value_item.as_value() {
3784                        let val = formatted_string.value();
3785                        if let Ok(flavor) = MarkdownFlavor::from_str(val) {
3786                            fragment.global.flavor.push_override(flavor, source, file.clone(), None);
3787                        } else {
3788                            log::warn!("[WARN] Unknown markdown flavor '{val}' in {path}");
3789                        }
3790                    } else {
3791                        log::warn!(
3792                            "[WARN] Expected string for global key '{}' in {}, found {}",
3793                            key,
3794                            path,
3795                            value_item.type_name()
3796                        );
3797                    }
3798                }
3799                _ => {
3800                    // Track unknown global keys for validation
3801                    fragment
3802                        .unknown_keys
3803                        .push(("[global]".to_string(), key.to_string(), Some(path.to_string())));
3804                    log::warn!("[WARN] Unknown key in [global] section of {path}: {key}");
3805                }
3806            }
3807        }
3808    }
3809
3810    // Handle [per-file-ignores] section
3811    if let Some(per_file_item) = doc.get("per-file-ignores")
3812        && let Some(per_file_table) = per_file_item.as_table()
3813    {
3814        let mut per_file_map = HashMap::new();
3815        for (pattern, value_item) in per_file_table.iter() {
3816            if let Some(toml_edit::Value::Array(formatted_array)) = value_item.as_value() {
3817                let rules: Vec<String> = formatted_array
3818                    .iter()
3819                    .filter_map(|item| item.as_str())
3820                    .map(|s| registry.resolve_rule_name(s).unwrap_or_else(|| normalize_key(s)))
3821                    .collect();
3822                per_file_map.insert(pattern.to_string(), rules);
3823            } else {
3824                let type_name = value_item.type_name();
3825                log::warn!(
3826                    "[WARN] Expected array for per-file-ignores pattern '{pattern}' in {path}, found {type_name}"
3827                );
3828            }
3829        }
3830        fragment
3831            .per_file_ignores
3832            .push_override(per_file_map, source, file.clone(), None);
3833    }
3834
3835    // Rule-specific: all other top-level tables
3836    for (key, item) in doc.iter() {
3837        // Skip known special sections
3838        if key == "global" || key == "per-file-ignores" {
3839            continue;
3840        }
3841
3842        // Resolve rule name (handles both canonical names like "MD004" and aliases like "ul-style")
3843        let norm_rule_name = if let Some(resolved) = registry.resolve_rule_name(key) {
3844            resolved
3845        } else {
3846            // Unknown rule - always track it for validation and suggestions
3847            fragment
3848                .unknown_keys
3849                .push((format!("[{key}]"), String::new(), Some(path.to_string())));
3850            continue;
3851        };
3852
3853        if let Some(tbl) = item.as_table() {
3854            let rule_entry = fragment.rules.entry(norm_rule_name.clone()).or_default();
3855            for (rk, rv_item) in tbl.iter() {
3856                let norm_rk = normalize_key(rk);
3857
3858                // Special handling for severity - store in rule_entry.severity
3859                if norm_rk == "severity" {
3860                    if let Some(toml_edit::Value::String(formatted_string)) = rv_item.as_value() {
3861                        let severity_str = formatted_string.value();
3862                        match crate::rule::Severity::deserialize(toml::Value::String(severity_str.to_string())) {
3863                            Ok(severity) => {
3864                                if rule_entry.severity.is_none() {
3865                                    rule_entry.severity = Some(SourcedValue::new(severity, source));
3866                                } else {
3867                                    rule_entry.severity.as_mut().unwrap().push_override(
3868                                        severity,
3869                                        source,
3870                                        file.clone(),
3871                                        None,
3872                                    );
3873                                }
3874                            }
3875                            Err(_) => {
3876                                log::warn!(
3877                                    "[WARN] Invalid severity '{severity_str}' for rule {norm_rule_name} in {path}. Valid values: error, warning"
3878                                );
3879                            }
3880                        }
3881                    }
3882                    continue; // Skip regular value processing for severity
3883                }
3884
3885                let maybe_toml_val: Option<toml::Value> = match rv_item.as_value() {
3886                    Some(toml_edit::Value::String(formatted)) => Some(toml::Value::String(formatted.value().clone())),
3887                    Some(toml_edit::Value::Integer(formatted)) => Some(toml::Value::Integer(*formatted.value())),
3888                    Some(toml_edit::Value::Float(formatted)) => Some(toml::Value::Float(*formatted.value())),
3889                    Some(toml_edit::Value::Boolean(formatted)) => Some(toml::Value::Boolean(*formatted.value())),
3890                    Some(toml_edit::Value::Datetime(formatted)) => Some(toml::Value::Datetime(*formatted.value())),
3891                    Some(toml_edit::Value::Array(formatted_array)) => {
3892                        // Convert toml_edit Array to toml::Value::Array
3893                        let mut values = Vec::new();
3894                        for item in formatted_array.iter() {
3895                            match item {
3896                                toml_edit::Value::String(formatted) => {
3897                                    values.push(toml::Value::String(formatted.value().clone()))
3898                                }
3899                                toml_edit::Value::Integer(formatted) => {
3900                                    values.push(toml::Value::Integer(*formatted.value()))
3901                                }
3902                                toml_edit::Value::Float(formatted) => {
3903                                    values.push(toml::Value::Float(*formatted.value()))
3904                                }
3905                                toml_edit::Value::Boolean(formatted) => {
3906                                    values.push(toml::Value::Boolean(*formatted.value()))
3907                                }
3908                                toml_edit::Value::Datetime(formatted) => {
3909                                    values.push(toml::Value::Datetime(*formatted.value()))
3910                                }
3911                                _ => {
3912                                    log::warn!(
3913                                        "[WARN] Skipping unsupported array element type in key '{norm_rule_name}.{norm_rk}' in {path}"
3914                                    );
3915                                }
3916                            }
3917                        }
3918                        Some(toml::Value::Array(values))
3919                    }
3920                    Some(toml_edit::Value::InlineTable(_)) => {
3921                        log::warn!(
3922                            "[WARN] Skipping inline table value for key '{norm_rule_name}.{norm_rk}' in {path}. Table conversion not yet fully implemented in parser."
3923                        );
3924                        None
3925                    }
3926                    None => {
3927                        log::warn!(
3928                            "[WARN] Skipping non-value item for key '{norm_rule_name}.{norm_rk}' in {path}. Expected simple value."
3929                        );
3930                        None
3931                    }
3932                };
3933                if let Some(toml_val) = maybe_toml_val {
3934                    let sv = rule_entry
3935                        .values
3936                        .entry(norm_rk.clone())
3937                        .or_insert_with(|| SourcedValue::new(toml_val.clone(), ConfigSource::Default));
3938                    sv.push_override(toml_val, source, file.clone(), None);
3939                }
3940            }
3941        } else if item.is_value() {
3942            log::warn!("[WARN] Ignoring top-level value key in {path}: '{key}'. Expected a table like [{key}].");
3943        }
3944    }
3945
3946    Ok(fragment)
3947}
3948
3949/// Loads and converts a markdownlint config file (.json or .yaml) into a SourcedConfigFragment.
3950fn load_from_markdownlint(path: &str) -> Result<SourcedConfigFragment, ConfigError> {
3951    // Use the unified loader from markdownlint_config.rs
3952    let ml_config = crate::markdownlint_config::load_markdownlint_config(path)
3953        .map_err(|e| ConfigError::ParseError(format!("{path}: {e}")))?;
3954    Ok(ml_config.map_to_sourced_rumdl_config_fragment(Some(path)))
3955}
3956
3957#[cfg(test)]
3958#[path = "config_intelligent_merge_tests.rs"]
3959mod config_intelligent_merge_tests;