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_project_config_is_standalone() {
1471        // Ruff model: Project config is standalone, user config is NOT merged
1472        // This ensures reproducibility across machines and CI/local consistency
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 NOT be present (Ruff model: project is standalone)
1511        assert!(
1512            !config.global.disable.contains(&"MD013".to_string()),
1513            "User config should NOT be merged with project config"
1514        );
1515        assert!(
1516            !config.global.disable.contains(&"MD041".to_string()),
1517            "User config should NOT be merged with project config"
1518        );
1519
1520        // Project config settings should be applied
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_user_config_as_fallback_when_no_project_config() {
1529        // Ruff model: User config is used as fallback when no project config exists
1530        use std::env;
1531
1532        let temp_dir = tempdir().unwrap();
1533        let original_dir = env::current_dir().unwrap();
1534
1535        // Create a fake user config directory
1536        let user_config_dir = temp_dir.path().join("user_config");
1537        let rumdl_config_dir = user_config_dir.join("rumdl");
1538        fs::create_dir_all(&rumdl_config_dir).unwrap();
1539        let user_config_path = rumdl_config_dir.join("rumdl.toml");
1540
1541        // User config with specific settings
1542        let user_config_content = r#"
1543[global]
1544disable = ["MD013", "MD041"]
1545line-length = 88
1546"#;
1547        fs::write(&user_config_path, user_config_content).unwrap();
1548
1549        // Create a project directory WITHOUT any config
1550        let project_dir = temp_dir.path().join("project_no_config");
1551        fs::create_dir_all(&project_dir).unwrap();
1552
1553        // Change to project directory
1554        env::set_current_dir(&project_dir).unwrap();
1555
1556        // Load config - should use user config as fallback
1557        let sourced = SourcedConfig::load_with_discovery_impl(None, None, false, Some(&user_config_dir)).unwrap();
1558
1559        let config: Config = sourced.into_validated_unchecked().into();
1560
1561        // User config should be loaded as fallback
1562        assert!(
1563            config.global.disable.contains(&"MD013".to_string()),
1564            "User config should be loaded as fallback when no project config"
1565        );
1566        assert!(
1567            config.global.disable.contains(&"MD041".to_string()),
1568            "User config should be loaded as fallback when no project config"
1569        );
1570        assert_eq!(
1571            config.global.line_length.get(),
1572            88,
1573            "User config line-length should be loaded as fallback"
1574        );
1575
1576        env::set_current_dir(original_dir).unwrap();
1577    }
1578
1579    #[test]
1580    fn test_typestate_validate_method() {
1581        use tempfile::tempdir;
1582
1583        let temp_dir = tempdir().expect("Failed to create temporary directory");
1584        let config_path = temp_dir.path().join("test.toml");
1585
1586        // Create config with an unknown rule option to trigger a validation warning
1587        let config_content = r#"
1588[global]
1589enable = ["MD001"]
1590
1591[MD013]
1592line_length = 80
1593unknown_option = true
1594"#;
1595        std::fs::write(&config_path, config_content).expect("Failed to write config");
1596
1597        // Load config - this returns SourcedConfig<ConfigLoaded>
1598        let loaded = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true)
1599            .expect("Should load config");
1600
1601        // Create a rule registry for validation
1602        let default_config = Config::default();
1603        let all_rules = crate::rules::all_rules(&default_config);
1604        let registry = RuleRegistry::from_rules(&all_rules);
1605
1606        // Validate - this transitions to SourcedConfig<ConfigValidated>
1607        let validated = loaded.validate(&registry).expect("Should validate config");
1608
1609        // Check that validation warnings were captured for the unknown option
1610        // Note: The validation checks rule options against the rule's schema
1611        let has_unknown_option_warning = validated
1612            .validation_warnings
1613            .iter()
1614            .any(|w| w.message.contains("unknown_option") || w.message.contains("Unknown option"));
1615
1616        // Print warnings for debugging if assertion fails
1617        if !has_unknown_option_warning {
1618            for w in &validated.validation_warnings {
1619                eprintln!("Warning: {}", w.message);
1620            }
1621        }
1622        assert!(
1623            has_unknown_option_warning,
1624            "Should have warning for unknown option. Got {} warnings: {:?}",
1625            validated.validation_warnings.len(),
1626            validated
1627                .validation_warnings
1628                .iter()
1629                .map(|w| &w.message)
1630                .collect::<Vec<_>>()
1631        );
1632
1633        // Now we can convert to Config (this would be a compile error with ConfigLoaded)
1634        let config: Config = validated.into();
1635
1636        // Verify the config values are correct
1637        assert!(config.global.enable.contains(&"MD001".to_string()));
1638    }
1639
1640    #[test]
1641    fn test_typestate_validate_into_convenience_method() {
1642        use tempfile::tempdir;
1643
1644        let temp_dir = tempdir().expect("Failed to create temporary directory");
1645        let config_path = temp_dir.path().join("test.toml");
1646
1647        let config_content = r#"
1648[global]
1649enable = ["MD022"]
1650
1651[MD022]
1652lines_above = 2
1653"#;
1654        std::fs::write(&config_path, config_content).expect("Failed to write config");
1655
1656        let loaded = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true)
1657            .expect("Should load config");
1658
1659        let default_config = Config::default();
1660        let all_rules = crate::rules::all_rules(&default_config);
1661        let registry = RuleRegistry::from_rules(&all_rules);
1662
1663        // Use the convenience method that validates and converts in one step
1664        let (config, warnings) = loaded.validate_into(&registry).expect("Should validate and convert");
1665
1666        // Should have no warnings for valid config
1667        assert!(warnings.is_empty(), "Should have no warnings for valid config");
1668
1669        // Config should be usable
1670        assert!(config.global.enable.contains(&"MD022".to_string()));
1671    }
1672
1673    #[test]
1674    fn test_resolve_rule_name_canonical() {
1675        // Canonical IDs should resolve to themselves
1676        assert_eq!(resolve_rule_name("MD001"), "MD001");
1677        assert_eq!(resolve_rule_name("MD013"), "MD013");
1678        assert_eq!(resolve_rule_name("MD069"), "MD069");
1679    }
1680
1681    #[test]
1682    fn test_resolve_rule_name_aliases() {
1683        // Aliases should resolve to canonical IDs
1684        assert_eq!(resolve_rule_name("heading-increment"), "MD001");
1685        assert_eq!(resolve_rule_name("line-length"), "MD013");
1686        assert_eq!(resolve_rule_name("no-bare-urls"), "MD034");
1687        assert_eq!(resolve_rule_name("ul-style"), "MD004");
1688    }
1689
1690    #[test]
1691    fn test_resolve_rule_name_case_insensitive() {
1692        // Case should not matter
1693        assert_eq!(resolve_rule_name("HEADING-INCREMENT"), "MD001");
1694        assert_eq!(resolve_rule_name("Heading-Increment"), "MD001");
1695        assert_eq!(resolve_rule_name("md001"), "MD001");
1696        assert_eq!(resolve_rule_name("MD001"), "MD001");
1697    }
1698
1699    #[test]
1700    fn test_resolve_rule_name_underscore_to_hyphen() {
1701        // Underscores should be converted to hyphens
1702        assert_eq!(resolve_rule_name("heading_increment"), "MD001");
1703        assert_eq!(resolve_rule_name("line_length"), "MD013");
1704        assert_eq!(resolve_rule_name("no_bare_urls"), "MD034");
1705    }
1706
1707    #[test]
1708    fn test_resolve_rule_name_unknown() {
1709        // Unknown names should fall back to normalization
1710        assert_eq!(resolve_rule_name("custom-rule"), "custom-rule");
1711        assert_eq!(resolve_rule_name("CUSTOM_RULE"), "custom-rule");
1712        assert_eq!(resolve_rule_name("md999"), "MD999"); // Looks like an MD rule
1713    }
1714
1715    #[test]
1716    fn test_resolve_rule_names_basic() {
1717        let result = resolve_rule_names("MD001,line-length,heading-increment");
1718        assert!(result.contains("MD001"));
1719        assert!(result.contains("MD013")); // line-length
1720        // Note: heading-increment also resolves to MD001, so set should contain MD001 and MD013
1721        assert_eq!(result.len(), 2);
1722    }
1723
1724    #[test]
1725    fn test_resolve_rule_names_with_whitespace() {
1726        let result = resolve_rule_names("  MD001 , line-length , MD034  ");
1727        assert!(result.contains("MD001"));
1728        assert!(result.contains("MD013"));
1729        assert!(result.contains("MD034"));
1730        assert_eq!(result.len(), 3);
1731    }
1732
1733    #[test]
1734    fn test_resolve_rule_names_empty_entries() {
1735        let result = resolve_rule_names("MD001,,MD013,");
1736        assert!(result.contains("MD001"));
1737        assert!(result.contains("MD013"));
1738        assert_eq!(result.len(), 2);
1739    }
1740
1741    #[test]
1742    fn test_resolve_rule_names_empty_string() {
1743        let result = resolve_rule_names("");
1744        assert!(result.is_empty());
1745    }
1746
1747    #[test]
1748    fn test_resolve_rule_names_mixed() {
1749        // Mix of canonical IDs, aliases, and unknown
1750        let result = resolve_rule_names("MD001,line-length,custom-rule");
1751        assert!(result.contains("MD001"));
1752        assert!(result.contains("MD013"));
1753        assert!(result.contains("custom-rule"));
1754        assert_eq!(result.len(), 3);
1755    }
1756}
1757
1758/// Configuration source with clear precedence hierarchy.
1759///
1760/// Precedence order (lower values override higher values):
1761/// - Default (0): Built-in defaults
1762/// - UserConfig (1): User-level ~/.config/rumdl/rumdl.toml
1763/// - PyprojectToml (2): Project-level pyproject.toml
1764/// - ProjectConfig (3): Project-level .rumdl.toml (most specific)
1765/// - Cli (4): Command-line flags (highest priority)
1766#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1767pub enum ConfigSource {
1768    /// Built-in default configuration
1769    Default,
1770    /// User-level configuration from ~/.config/rumdl/rumdl.toml
1771    UserConfig,
1772    /// Project-level configuration from pyproject.toml
1773    PyprojectToml,
1774    /// Project-level configuration from .rumdl.toml or rumdl.toml
1775    ProjectConfig,
1776    /// Command-line flags (highest precedence)
1777    Cli,
1778}
1779
1780#[derive(Debug, Clone)]
1781pub struct ConfigOverride<T> {
1782    pub value: T,
1783    pub source: ConfigSource,
1784    pub file: Option<String>,
1785    pub line: Option<usize>,
1786}
1787
1788#[derive(Debug, Clone)]
1789pub struct SourcedValue<T> {
1790    pub value: T,
1791    pub source: ConfigSource,
1792    pub overrides: Vec<ConfigOverride<T>>,
1793}
1794
1795impl<T: Clone> SourcedValue<T> {
1796    pub fn new(value: T, source: ConfigSource) -> Self {
1797        Self {
1798            value: value.clone(),
1799            source,
1800            overrides: vec![ConfigOverride {
1801                value,
1802                source,
1803                file: None,
1804                line: None,
1805            }],
1806        }
1807    }
1808
1809    /// Merges a new override into this SourcedValue based on source precedence.
1810    /// If the new source has higher or equal precedence, the value and source are updated,
1811    /// and the new override is added to the history.
1812    pub fn merge_override(
1813        &mut self,
1814        new_value: T,
1815        new_source: ConfigSource,
1816        new_file: Option<String>,
1817        new_line: Option<usize>,
1818    ) {
1819        // Helper function to get precedence, defined locally or globally
1820        fn source_precedence(src: ConfigSource) -> u8 {
1821            match src {
1822                ConfigSource::Default => 0,
1823                ConfigSource::UserConfig => 1,
1824                ConfigSource::PyprojectToml => 2,
1825                ConfigSource::ProjectConfig => 3,
1826                ConfigSource::Cli => 4,
1827            }
1828        }
1829
1830        if source_precedence(new_source) >= source_precedence(self.source) {
1831            self.value = new_value.clone();
1832            self.source = new_source;
1833            self.overrides.push(ConfigOverride {
1834                value: new_value,
1835                source: new_source,
1836                file: new_file,
1837                line: new_line,
1838            });
1839        }
1840    }
1841
1842    pub fn push_override(&mut self, value: T, source: ConfigSource, file: Option<String>, line: Option<usize>) {
1843        // This is essentially merge_override without the precedence check
1844        // We might consolidate these later, but keep separate for now during refactor
1845        self.value = value.clone();
1846        self.source = source;
1847        self.overrides.push(ConfigOverride {
1848            value,
1849            source,
1850            file,
1851            line,
1852        });
1853    }
1854}
1855
1856impl<T: Clone + Eq + std::hash::Hash> SourcedValue<Vec<T>> {
1857    /// Merges a new value using union semantics (for arrays like `disable`)
1858    /// Values from both sources are combined, with deduplication
1859    pub fn merge_union(
1860        &mut self,
1861        new_value: Vec<T>,
1862        new_source: ConfigSource,
1863        new_file: Option<String>,
1864        new_line: Option<usize>,
1865    ) {
1866        fn source_precedence(src: ConfigSource) -> u8 {
1867            match src {
1868                ConfigSource::Default => 0,
1869                ConfigSource::UserConfig => 1,
1870                ConfigSource::PyprojectToml => 2,
1871                ConfigSource::ProjectConfig => 3,
1872                ConfigSource::Cli => 4,
1873            }
1874        }
1875
1876        if source_precedence(new_source) >= source_precedence(self.source) {
1877            // Union: combine values from both sources with deduplication
1878            let mut combined = self.value.clone();
1879            for item in new_value.iter() {
1880                if !combined.contains(item) {
1881                    combined.push(item.clone());
1882                }
1883            }
1884
1885            self.value = combined;
1886            self.source = new_source;
1887            self.overrides.push(ConfigOverride {
1888                value: new_value,
1889                source: new_source,
1890                file: new_file,
1891                line: new_line,
1892            });
1893        }
1894    }
1895}
1896
1897#[derive(Debug, Clone)]
1898pub struct SourcedGlobalConfig {
1899    pub enable: SourcedValue<Vec<String>>,
1900    pub disable: SourcedValue<Vec<String>>,
1901    pub exclude: SourcedValue<Vec<String>>,
1902    pub include: SourcedValue<Vec<String>>,
1903    pub respect_gitignore: SourcedValue<bool>,
1904    pub line_length: SourcedValue<LineLength>,
1905    pub output_format: Option<SourcedValue<String>>,
1906    pub fixable: SourcedValue<Vec<String>>,
1907    pub unfixable: SourcedValue<Vec<String>>,
1908    pub flavor: SourcedValue<MarkdownFlavor>,
1909    pub force_exclude: SourcedValue<bool>,
1910    pub cache_dir: Option<SourcedValue<String>>,
1911    pub cache: SourcedValue<bool>,
1912}
1913
1914impl Default for SourcedGlobalConfig {
1915    fn default() -> Self {
1916        SourcedGlobalConfig {
1917            enable: SourcedValue::new(Vec::new(), ConfigSource::Default),
1918            disable: SourcedValue::new(Vec::new(), ConfigSource::Default),
1919            exclude: SourcedValue::new(Vec::new(), ConfigSource::Default),
1920            include: SourcedValue::new(Vec::new(), ConfigSource::Default),
1921            respect_gitignore: SourcedValue::new(true, ConfigSource::Default),
1922            line_length: SourcedValue::new(LineLength::default(), ConfigSource::Default),
1923            output_format: None,
1924            fixable: SourcedValue::new(Vec::new(), ConfigSource::Default),
1925            unfixable: SourcedValue::new(Vec::new(), ConfigSource::Default),
1926            flavor: SourcedValue::new(MarkdownFlavor::default(), ConfigSource::Default),
1927            force_exclude: SourcedValue::new(false, ConfigSource::Default),
1928            cache_dir: None,
1929            cache: SourcedValue::new(true, ConfigSource::Default),
1930        }
1931    }
1932}
1933
1934#[derive(Debug, Default, Clone)]
1935pub struct SourcedRuleConfig {
1936    pub severity: Option<SourcedValue<crate::rule::Severity>>,
1937    pub values: BTreeMap<String, SourcedValue<toml::Value>>,
1938}
1939
1940/// Represents configuration loaded from a single source file, with provenance.
1941/// Used as an intermediate step before merging into the final SourcedConfig.
1942#[derive(Debug, Clone)]
1943pub struct SourcedConfigFragment {
1944    pub global: SourcedGlobalConfig,
1945    pub per_file_ignores: SourcedValue<HashMap<String, Vec<String>>>,
1946    pub rules: BTreeMap<String, SourcedRuleConfig>,
1947    pub unknown_keys: Vec<(String, String, Option<String>)>, // (section, key, file_path)
1948                                                             // Note: loaded_files is tracked globally in SourcedConfig.
1949}
1950
1951impl Default for SourcedConfigFragment {
1952    fn default() -> Self {
1953        Self {
1954            global: SourcedGlobalConfig::default(),
1955            per_file_ignores: SourcedValue::new(HashMap::new(), ConfigSource::Default),
1956            rules: BTreeMap::new(),
1957            unknown_keys: Vec::new(),
1958        }
1959    }
1960}
1961
1962/// Configuration with provenance tracking for values.
1963///
1964/// The `State` type parameter encodes the validation state:
1965/// - `ConfigLoaded`: Config has been loaded but not validated
1966/// - `ConfigValidated`: Config has been validated and can be converted to `Config`
1967///
1968/// # Typestate Pattern
1969///
1970/// This uses the typestate pattern to ensure validation happens before conversion:
1971///
1972/// ```ignore
1973/// let loaded: SourcedConfig<ConfigLoaded> = SourcedConfig::load_with_discovery(...)?;
1974/// let validated: SourcedConfig<ConfigValidated> = loaded.validate(&registry)?;
1975/// let config: Config = validated.into();  // Only works on ConfigValidated!
1976/// ```
1977///
1978/// Attempting to convert a `ConfigLoaded` config directly to `Config` is a compile error.
1979#[derive(Debug, Clone)]
1980pub struct SourcedConfig<State = ConfigLoaded> {
1981    pub global: SourcedGlobalConfig,
1982    pub per_file_ignores: SourcedValue<HashMap<String, Vec<String>>>,
1983    pub rules: BTreeMap<String, SourcedRuleConfig>,
1984    pub loaded_files: Vec<String>,
1985    pub unknown_keys: Vec<(String, String, Option<String>)>, // (section, key, file_path)
1986    /// Project root directory (parent of config file), used for resolving relative paths
1987    pub project_root: Option<std::path::PathBuf>,
1988    /// Validation warnings (populated after validate() is called)
1989    pub validation_warnings: Vec<ConfigValidationWarning>,
1990    /// Phantom data for the state type parameter
1991    _state: PhantomData<State>,
1992}
1993
1994impl Default for SourcedConfig<ConfigLoaded> {
1995    fn default() -> Self {
1996        Self {
1997            global: SourcedGlobalConfig::default(),
1998            per_file_ignores: SourcedValue::new(HashMap::new(), ConfigSource::Default),
1999            rules: BTreeMap::new(),
2000            loaded_files: Vec::new(),
2001            unknown_keys: Vec::new(),
2002            project_root: None,
2003            validation_warnings: Vec::new(),
2004            _state: PhantomData,
2005        }
2006    }
2007}
2008
2009impl SourcedConfig<ConfigLoaded> {
2010    /// Merges another SourcedConfigFragment into this SourcedConfig.
2011    /// Uses source precedence to determine which values take effect.
2012    fn merge(&mut self, fragment: SourcedConfigFragment) {
2013        // Merge global config
2014        // Enable uses replace semantics (project can enforce rules)
2015        self.global.enable.merge_override(
2016            fragment.global.enable.value,
2017            fragment.global.enable.source,
2018            fragment.global.enable.overrides.first().and_then(|o| o.file.clone()),
2019            fragment.global.enable.overrides.first().and_then(|o| o.line),
2020        );
2021
2022        // Disable uses union semantics (user can add to project disables)
2023        self.global.disable.merge_union(
2024            fragment.global.disable.value,
2025            fragment.global.disable.source,
2026            fragment.global.disable.overrides.first().and_then(|o| o.file.clone()),
2027            fragment.global.disable.overrides.first().and_then(|o| o.line),
2028        );
2029
2030        // Conflict resolution: Enable overrides disable
2031        // Remove any rules from disable that appear in enable
2032        self.global
2033            .disable
2034            .value
2035            .retain(|rule| !self.global.enable.value.contains(rule));
2036        self.global.include.merge_override(
2037            fragment.global.include.value,
2038            fragment.global.include.source,
2039            fragment.global.include.overrides.first().and_then(|o| o.file.clone()),
2040            fragment.global.include.overrides.first().and_then(|o| o.line),
2041        );
2042        self.global.exclude.merge_override(
2043            fragment.global.exclude.value,
2044            fragment.global.exclude.source,
2045            fragment.global.exclude.overrides.first().and_then(|o| o.file.clone()),
2046            fragment.global.exclude.overrides.first().and_then(|o| o.line),
2047        );
2048        self.global.respect_gitignore.merge_override(
2049            fragment.global.respect_gitignore.value,
2050            fragment.global.respect_gitignore.source,
2051            fragment
2052                .global
2053                .respect_gitignore
2054                .overrides
2055                .first()
2056                .and_then(|o| o.file.clone()),
2057            fragment.global.respect_gitignore.overrides.first().and_then(|o| o.line),
2058        );
2059        self.global.line_length.merge_override(
2060            fragment.global.line_length.value,
2061            fragment.global.line_length.source,
2062            fragment
2063                .global
2064                .line_length
2065                .overrides
2066                .first()
2067                .and_then(|o| o.file.clone()),
2068            fragment.global.line_length.overrides.first().and_then(|o| o.line),
2069        );
2070        self.global.fixable.merge_override(
2071            fragment.global.fixable.value,
2072            fragment.global.fixable.source,
2073            fragment.global.fixable.overrides.first().and_then(|o| o.file.clone()),
2074            fragment.global.fixable.overrides.first().and_then(|o| o.line),
2075        );
2076        self.global.unfixable.merge_override(
2077            fragment.global.unfixable.value,
2078            fragment.global.unfixable.source,
2079            fragment.global.unfixable.overrides.first().and_then(|o| o.file.clone()),
2080            fragment.global.unfixable.overrides.first().and_then(|o| o.line),
2081        );
2082
2083        // Merge flavor
2084        self.global.flavor.merge_override(
2085            fragment.global.flavor.value,
2086            fragment.global.flavor.source,
2087            fragment.global.flavor.overrides.first().and_then(|o| o.file.clone()),
2088            fragment.global.flavor.overrides.first().and_then(|o| o.line),
2089        );
2090
2091        // Merge force_exclude
2092        self.global.force_exclude.merge_override(
2093            fragment.global.force_exclude.value,
2094            fragment.global.force_exclude.source,
2095            fragment
2096                .global
2097                .force_exclude
2098                .overrides
2099                .first()
2100                .and_then(|o| o.file.clone()),
2101            fragment.global.force_exclude.overrides.first().and_then(|o| o.line),
2102        );
2103
2104        // Merge output_format if present
2105        if let Some(output_format_fragment) = fragment.global.output_format {
2106            if let Some(ref mut output_format) = self.global.output_format {
2107                output_format.merge_override(
2108                    output_format_fragment.value,
2109                    output_format_fragment.source,
2110                    output_format_fragment.overrides.first().and_then(|o| o.file.clone()),
2111                    output_format_fragment.overrides.first().and_then(|o| o.line),
2112                );
2113            } else {
2114                self.global.output_format = Some(output_format_fragment);
2115            }
2116        }
2117
2118        // Merge cache_dir if present
2119        if let Some(cache_dir_fragment) = fragment.global.cache_dir {
2120            if let Some(ref mut cache_dir) = self.global.cache_dir {
2121                cache_dir.merge_override(
2122                    cache_dir_fragment.value,
2123                    cache_dir_fragment.source,
2124                    cache_dir_fragment.overrides.first().and_then(|o| o.file.clone()),
2125                    cache_dir_fragment.overrides.first().and_then(|o| o.line),
2126                );
2127            } else {
2128                self.global.cache_dir = Some(cache_dir_fragment);
2129            }
2130        }
2131
2132        // Merge cache if not default (only override when explicitly set)
2133        if fragment.global.cache.source != ConfigSource::Default {
2134            self.global.cache.merge_override(
2135                fragment.global.cache.value,
2136                fragment.global.cache.source,
2137                fragment.global.cache.overrides.first().and_then(|o| o.file.clone()),
2138                fragment.global.cache.overrides.first().and_then(|o| o.line),
2139            );
2140        }
2141
2142        // Merge per_file_ignores
2143        self.per_file_ignores.merge_override(
2144            fragment.per_file_ignores.value,
2145            fragment.per_file_ignores.source,
2146            fragment.per_file_ignores.overrides.first().and_then(|o| o.file.clone()),
2147            fragment.per_file_ignores.overrides.first().and_then(|o| o.line),
2148        );
2149
2150        // Merge rule configs
2151        for (rule_name, rule_fragment) in fragment.rules {
2152            let norm_rule_name = rule_name.to_ascii_uppercase(); // Normalize to uppercase for case-insensitivity
2153            let rule_entry = self.rules.entry(norm_rule_name).or_default();
2154
2155            // Merge severity if present in fragment
2156            if let Some(severity_fragment) = rule_fragment.severity {
2157                if let Some(ref mut existing_severity) = rule_entry.severity {
2158                    existing_severity.merge_override(
2159                        severity_fragment.value,
2160                        severity_fragment.source,
2161                        severity_fragment.overrides.first().and_then(|o| o.file.clone()),
2162                        severity_fragment.overrides.first().and_then(|o| o.line),
2163                    );
2164                } else {
2165                    rule_entry.severity = Some(severity_fragment);
2166                }
2167            }
2168
2169            // Merge values
2170            for (key, sourced_value_fragment) in rule_fragment.values {
2171                let sv_entry = rule_entry
2172                    .values
2173                    .entry(key.clone())
2174                    .or_insert_with(|| SourcedValue::new(sourced_value_fragment.value.clone(), ConfigSource::Default));
2175                let file_from_fragment = sourced_value_fragment.overrides.first().and_then(|o| o.file.clone());
2176                let line_from_fragment = sourced_value_fragment.overrides.first().and_then(|o| o.line);
2177                sv_entry.merge_override(
2178                    sourced_value_fragment.value,  // Use the value from the fragment
2179                    sourced_value_fragment.source, // Use the source from the fragment
2180                    file_from_fragment,            // Pass the file path from the fragment override
2181                    line_from_fragment,            // Pass the line number from the fragment override
2182                );
2183            }
2184        }
2185
2186        // Merge unknown_keys from fragment
2187        for (section, key, file_path) in fragment.unknown_keys {
2188            // Deduplicate: only add if not already present
2189            if !self.unknown_keys.iter().any(|(s, k, _)| s == &section && k == &key) {
2190                self.unknown_keys.push((section, key, file_path));
2191            }
2192        }
2193    }
2194
2195    /// Load and merge configurations from files and CLI overrides.
2196    pub fn load(config_path: Option<&str>, cli_overrides: Option<&SourcedGlobalConfig>) -> Result<Self, ConfigError> {
2197        Self::load_with_discovery(config_path, cli_overrides, false)
2198    }
2199
2200    /// Finds project root by walking up from start_dir looking for .git directory.
2201    /// Falls back to start_dir if no .git found.
2202    fn find_project_root_from(start_dir: &Path) -> std::path::PathBuf {
2203        let mut current = start_dir.to_path_buf();
2204        const MAX_DEPTH: usize = 100;
2205
2206        for _ in 0..MAX_DEPTH {
2207            if current.join(".git").exists() {
2208                log::debug!("[rumdl-config] Found .git at: {}", current.display());
2209                return current;
2210            }
2211
2212            match current.parent() {
2213                Some(parent) => current = parent.to_path_buf(),
2214                None => break,
2215            }
2216        }
2217
2218        // No .git found, use start_dir as project root
2219        log::debug!(
2220            "[rumdl-config] No .git found, using config location as project root: {}",
2221            start_dir.display()
2222        );
2223        start_dir.to_path_buf()
2224    }
2225
2226    /// Discover configuration file by traversing up the directory tree.
2227    /// Returns the first configuration file found.
2228    /// Discovers config file and returns both the config path and project root.
2229    /// Returns: (config_file_path, project_root_path)
2230    /// Project root is the directory containing .git, or config parent as fallback.
2231    fn discover_config_upward() -> Option<(std::path::PathBuf, std::path::PathBuf)> {
2232        use std::env;
2233
2234        const CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml", ".config/rumdl.toml", "pyproject.toml"];
2235        const MAX_DEPTH: usize = 100; // Prevent infinite traversal
2236
2237        let start_dir = match env::current_dir() {
2238            Ok(dir) => dir,
2239            Err(e) => {
2240                log::debug!("[rumdl-config] Failed to get current directory: {e}");
2241                return None;
2242            }
2243        };
2244
2245        let mut current_dir = start_dir.clone();
2246        let mut depth = 0;
2247        let mut found_config: Option<(std::path::PathBuf, std::path::PathBuf)> = None;
2248
2249        loop {
2250            if depth >= MAX_DEPTH {
2251                log::debug!("[rumdl-config] Maximum traversal depth reached");
2252                break;
2253            }
2254
2255            log::debug!("[rumdl-config] Searching for config in: {}", current_dir.display());
2256
2257            // Check for config files in order of precedence (only if not already found)
2258            if found_config.is_none() {
2259                for config_name in CONFIG_FILES {
2260                    let config_path = current_dir.join(config_name);
2261
2262                    if config_path.exists() {
2263                        // For pyproject.toml, verify it contains [tool.rumdl] section
2264                        if *config_name == "pyproject.toml" {
2265                            if let Ok(content) = std::fs::read_to_string(&config_path) {
2266                                if content.contains("[tool.rumdl]") || content.contains("tool.rumdl") {
2267                                    log::debug!("[rumdl-config] Found config file: {}", config_path.display());
2268                                    // Store config, but continue looking for .git
2269                                    found_config = Some((config_path.clone(), current_dir.clone()));
2270                                    break;
2271                                }
2272                                log::debug!("[rumdl-config] Found pyproject.toml but no [tool.rumdl] section");
2273                                continue;
2274                            }
2275                        } else {
2276                            log::debug!("[rumdl-config] Found config file: {}", config_path.display());
2277                            // Store config, but continue looking for .git
2278                            found_config = Some((config_path.clone(), current_dir.clone()));
2279                            break;
2280                        }
2281                    }
2282                }
2283            }
2284
2285            // Check for .git directory (stop boundary)
2286            if current_dir.join(".git").exists() {
2287                log::debug!("[rumdl-config] Stopping at .git directory");
2288                break;
2289            }
2290
2291            // Move to parent directory
2292            match current_dir.parent() {
2293                Some(parent) => {
2294                    current_dir = parent.to_owned();
2295                    depth += 1;
2296                }
2297                None => {
2298                    log::debug!("[rumdl-config] Reached filesystem root");
2299                    break;
2300                }
2301            }
2302        }
2303
2304        // If config found, determine project root by walking up from config location
2305        if let Some((config_path, config_dir)) = found_config {
2306            let project_root = Self::find_project_root_from(&config_dir);
2307            return Some((config_path, project_root));
2308        }
2309
2310        None
2311    }
2312
2313    /// Discover markdownlint configuration file by traversing up the directory tree.
2314    /// Similar to discover_config_upward but for .markdownlint.yaml/json files.
2315    /// Returns the path to the config file if found.
2316    fn discover_markdownlint_config_upward() -> Option<std::path::PathBuf> {
2317        use std::env;
2318
2319        const MAX_DEPTH: usize = 100;
2320
2321        let start_dir = match env::current_dir() {
2322            Ok(dir) => dir,
2323            Err(e) => {
2324                log::debug!("[rumdl-config] Failed to get current directory for markdownlint discovery: {e}");
2325                return None;
2326            }
2327        };
2328
2329        let mut current_dir = start_dir.clone();
2330        let mut depth = 0;
2331
2332        loop {
2333            if depth >= MAX_DEPTH {
2334                log::debug!("[rumdl-config] Maximum traversal depth reached for markdownlint discovery");
2335                break;
2336            }
2337
2338            log::debug!(
2339                "[rumdl-config] Searching for markdownlint config in: {}",
2340                current_dir.display()
2341            );
2342
2343            // Check for markdownlint config files in order of precedence
2344            for config_name in MARKDOWNLINT_CONFIG_FILES {
2345                let config_path = current_dir.join(config_name);
2346                if config_path.exists() {
2347                    log::debug!("[rumdl-config] Found markdownlint config: {}", config_path.display());
2348                    return Some(config_path);
2349                }
2350            }
2351
2352            // Check for .git directory (stop boundary)
2353            if current_dir.join(".git").exists() {
2354                log::debug!("[rumdl-config] Stopping markdownlint search at .git directory");
2355                break;
2356            }
2357
2358            // Move to parent directory
2359            match current_dir.parent() {
2360                Some(parent) => {
2361                    current_dir = parent.to_owned();
2362                    depth += 1;
2363                }
2364                None => {
2365                    log::debug!("[rumdl-config] Reached filesystem root during markdownlint search");
2366                    break;
2367                }
2368            }
2369        }
2370
2371        None
2372    }
2373
2374    /// Internal implementation that accepts config directory for testing
2375    fn user_configuration_path_impl(config_dir: &Path) -> Option<std::path::PathBuf> {
2376        let config_dir = config_dir.join("rumdl");
2377
2378        // Check for config files in precedence order (same as project discovery)
2379        const USER_CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml", "pyproject.toml"];
2380
2381        log::debug!(
2382            "[rumdl-config] Checking for user configuration in: {}",
2383            config_dir.display()
2384        );
2385
2386        for filename in USER_CONFIG_FILES {
2387            let config_path = config_dir.join(filename);
2388
2389            if config_path.exists() {
2390                // For pyproject.toml, verify it contains [tool.rumdl] section
2391                if *filename == "pyproject.toml" {
2392                    if let Ok(content) = std::fs::read_to_string(&config_path) {
2393                        if content.contains("[tool.rumdl]") || content.contains("tool.rumdl") {
2394                            log::debug!("[rumdl-config] Found user configuration at: {}", config_path.display());
2395                            return Some(config_path);
2396                        }
2397                        log::debug!("[rumdl-config] Found user pyproject.toml but no [tool.rumdl] section");
2398                        continue;
2399                    }
2400                } else {
2401                    log::debug!("[rumdl-config] Found user configuration at: {}", config_path.display());
2402                    return Some(config_path);
2403                }
2404            }
2405        }
2406
2407        log::debug!(
2408            "[rumdl-config] No user configuration found in: {}",
2409            config_dir.display()
2410        );
2411        None
2412    }
2413
2414    /// Discover user-level configuration file from platform-specific config directory.
2415    /// Returns the first configuration file found in the user config directory.
2416    #[cfg(feature = "native")]
2417    fn user_configuration_path() -> Option<std::path::PathBuf> {
2418        use etcetera::{BaseStrategy, choose_base_strategy};
2419
2420        match choose_base_strategy() {
2421            Ok(strategy) => {
2422                let config_dir = strategy.config_dir();
2423                Self::user_configuration_path_impl(&config_dir)
2424            }
2425            Err(e) => {
2426                log::debug!("[rumdl-config] Failed to determine user config directory: {e}");
2427                None
2428            }
2429        }
2430    }
2431
2432    /// Stub for WASM builds - user config not supported
2433    #[cfg(not(feature = "native"))]
2434    fn user_configuration_path() -> Option<std::path::PathBuf> {
2435        None
2436    }
2437
2438    /// Load an explicit config file (standalone, no user config merging)
2439    fn load_explicit_config(sourced_config: &mut Self, path: &str) -> Result<(), ConfigError> {
2440        let path_obj = Path::new(path);
2441        let filename = path_obj.file_name().and_then(|name| name.to_str()).unwrap_or("");
2442        let path_str = path.to_string();
2443
2444        log::debug!("[rumdl-config] Loading explicit config file: {filename}");
2445
2446        // Find project root by walking up from config location looking for .git
2447        if let Some(config_parent) = path_obj.parent() {
2448            let project_root = Self::find_project_root_from(config_parent);
2449            log::debug!(
2450                "[rumdl-config] Project root (from explicit config): {}",
2451                project_root.display()
2452            );
2453            sourced_config.project_root = Some(project_root);
2454        }
2455
2456        // Known markdownlint config files
2457        const MARKDOWNLINT_FILENAMES: &[&str] = &[".markdownlint.json", ".markdownlint.yaml", ".markdownlint.yml"];
2458
2459        if filename == "pyproject.toml" || filename == ".rumdl.toml" || filename == "rumdl.toml" {
2460            let content = std::fs::read_to_string(path).map_err(|e| ConfigError::IoError {
2461                source: e,
2462                path: path_str.clone(),
2463            })?;
2464            if filename == "pyproject.toml" {
2465                if let Some(fragment) = parse_pyproject_toml(&content, &path_str)? {
2466                    sourced_config.merge(fragment);
2467                    sourced_config.loaded_files.push(path_str);
2468                }
2469            } else {
2470                let fragment = parse_rumdl_toml(&content, &path_str, ConfigSource::ProjectConfig)?;
2471                sourced_config.merge(fragment);
2472                sourced_config.loaded_files.push(path_str);
2473            }
2474        } else if MARKDOWNLINT_FILENAMES.contains(&filename)
2475            || path_str.ends_with(".json")
2476            || path_str.ends_with(".jsonc")
2477            || path_str.ends_with(".yaml")
2478            || path_str.ends_with(".yml")
2479        {
2480            // Parse as markdownlint config (JSON/YAML)
2481            let fragment = load_from_markdownlint(&path_str)?;
2482            sourced_config.merge(fragment);
2483            sourced_config.loaded_files.push(path_str);
2484        } else {
2485            // Try TOML only
2486            let content = std::fs::read_to_string(path).map_err(|e| ConfigError::IoError {
2487                source: e,
2488                path: path_str.clone(),
2489            })?;
2490            let fragment = parse_rumdl_toml(&content, &path_str, ConfigSource::ProjectConfig)?;
2491            sourced_config.merge(fragment);
2492            sourced_config.loaded_files.push(path_str);
2493        }
2494
2495        Ok(())
2496    }
2497
2498    /// Load user config as fallback when no project config exists
2499    fn load_user_config_as_fallback(
2500        sourced_config: &mut Self,
2501        user_config_dir: Option<&Path>,
2502    ) -> Result<(), ConfigError> {
2503        let user_config_path = if let Some(dir) = user_config_dir {
2504            Self::user_configuration_path_impl(dir)
2505        } else {
2506            Self::user_configuration_path()
2507        };
2508
2509        if let Some(user_config_path) = user_config_path {
2510            let path_str = user_config_path.display().to_string();
2511            let filename = user_config_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
2512
2513            log::debug!("[rumdl-config] Loading user config as fallback: {path_str}");
2514
2515            if filename == "pyproject.toml" {
2516                let content = std::fs::read_to_string(&user_config_path).map_err(|e| ConfigError::IoError {
2517                    source: e,
2518                    path: path_str.clone(),
2519                })?;
2520                if let Some(fragment) = parse_pyproject_toml(&content, &path_str)? {
2521                    sourced_config.merge(fragment);
2522                    sourced_config.loaded_files.push(path_str);
2523                }
2524            } else {
2525                let content = std::fs::read_to_string(&user_config_path).map_err(|e| ConfigError::IoError {
2526                    source: e,
2527                    path: path_str.clone(),
2528                })?;
2529                let fragment = parse_rumdl_toml(&content, &path_str, ConfigSource::UserConfig)?;
2530                sourced_config.merge(fragment);
2531                sourced_config.loaded_files.push(path_str);
2532            }
2533        } else {
2534            log::debug!("[rumdl-config] No user configuration file found");
2535        }
2536
2537        Ok(())
2538    }
2539
2540    /// Internal implementation that accepts user config directory for testing
2541    #[doc(hidden)]
2542    pub fn load_with_discovery_impl(
2543        config_path: Option<&str>,
2544        cli_overrides: Option<&SourcedGlobalConfig>,
2545        skip_auto_discovery: bool,
2546        user_config_dir: Option<&Path>,
2547    ) -> Result<Self, ConfigError> {
2548        use std::env;
2549        log::debug!("[rumdl-config] Current working directory: {:?}", env::current_dir());
2550
2551        let mut sourced_config = SourcedConfig::default();
2552
2553        // Ruff model: Project config is standalone, user config is fallback only
2554        //
2555        // Priority order:
2556        // 1. If explicit config path provided → use ONLY that (standalone)
2557        // 2. Else if project config discovered → use ONLY that (standalone)
2558        // 3. Else if user config exists → use it as fallback
2559        // 4. CLI overrides always apply last
2560        //
2561        // This ensures project configs are reproducible across machines and
2562        // CI/local runs behave identically.
2563
2564        // Explicit config path always takes precedence
2565        if let Some(path) = config_path {
2566            // Explicit config path provided - use ONLY this config (standalone)
2567            log::debug!("[rumdl-config] Explicit config_path provided: {path:?}");
2568            Self::load_explicit_config(&mut sourced_config, path)?;
2569        } else if skip_auto_discovery {
2570            log::debug!("[rumdl-config] Skipping config discovery due to --no-config/--isolated flag");
2571            // No config loading, just apply CLI overrides at the end
2572        } else {
2573            // No explicit path - try auto-discovery
2574            log::debug!("[rumdl-config] No explicit config_path, searching default locations");
2575
2576            // Try to discover project config first
2577            if let Some((config_file, project_root)) = Self::discover_config_upward() {
2578                // Project config found - use ONLY this (standalone, no user config)
2579                let path_str = config_file.display().to_string();
2580                let filename = config_file.file_name().and_then(|n| n.to_str()).unwrap_or("");
2581
2582                log::debug!("[rumdl-config] Found project config: {path_str}");
2583                log::debug!("[rumdl-config] Project root: {}", project_root.display());
2584
2585                sourced_config.project_root = Some(project_root);
2586
2587                if filename == "pyproject.toml" {
2588                    let content = std::fs::read_to_string(&config_file).map_err(|e| ConfigError::IoError {
2589                        source: e,
2590                        path: path_str.clone(),
2591                    })?;
2592                    if let Some(fragment) = parse_pyproject_toml(&content, &path_str)? {
2593                        sourced_config.merge(fragment);
2594                        sourced_config.loaded_files.push(path_str);
2595                    }
2596                } else if filename == ".rumdl.toml" || filename == "rumdl.toml" {
2597                    let content = std::fs::read_to_string(&config_file).map_err(|e| ConfigError::IoError {
2598                        source: e,
2599                        path: path_str.clone(),
2600                    })?;
2601                    let fragment = parse_rumdl_toml(&content, &path_str, ConfigSource::ProjectConfig)?;
2602                    sourced_config.merge(fragment);
2603                    sourced_config.loaded_files.push(path_str);
2604                }
2605            } else {
2606                // No rumdl project config - try markdownlint config
2607                log::debug!("[rumdl-config] No rumdl config found, checking markdownlint config");
2608
2609                if let Some(markdownlint_path) = Self::discover_markdownlint_config_upward() {
2610                    let path_str = markdownlint_path.display().to_string();
2611                    log::debug!("[rumdl-config] Found markdownlint config: {path_str}");
2612                    match load_from_markdownlint(&path_str) {
2613                        Ok(fragment) => {
2614                            sourced_config.merge(fragment);
2615                            sourced_config.loaded_files.push(path_str);
2616                        }
2617                        Err(_e) => {
2618                            log::debug!("[rumdl-config] Failed to load markdownlint config, trying user config");
2619                            Self::load_user_config_as_fallback(&mut sourced_config, user_config_dir)?;
2620                        }
2621                    }
2622                } else {
2623                    // No project config at all - use user config as fallback
2624                    log::debug!("[rumdl-config] No project config found, using user config as fallback");
2625                    Self::load_user_config_as_fallback(&mut sourced_config, user_config_dir)?;
2626                }
2627            }
2628        }
2629
2630        // Apply CLI overrides (highest precedence)
2631        if let Some(cli) = cli_overrides {
2632            sourced_config
2633                .global
2634                .enable
2635                .merge_override(cli.enable.value.clone(), ConfigSource::Cli, None, None);
2636            sourced_config
2637                .global
2638                .disable
2639                .merge_override(cli.disable.value.clone(), ConfigSource::Cli, None, None);
2640            sourced_config
2641                .global
2642                .exclude
2643                .merge_override(cli.exclude.value.clone(), ConfigSource::Cli, None, None);
2644            sourced_config
2645                .global
2646                .include
2647                .merge_override(cli.include.value.clone(), ConfigSource::Cli, None, None);
2648            sourced_config.global.respect_gitignore.merge_override(
2649                cli.respect_gitignore.value,
2650                ConfigSource::Cli,
2651                None,
2652                None,
2653            );
2654            sourced_config
2655                .global
2656                .fixable
2657                .merge_override(cli.fixable.value.clone(), ConfigSource::Cli, None, None);
2658            sourced_config
2659                .global
2660                .unfixable
2661                .merge_override(cli.unfixable.value.clone(), ConfigSource::Cli, None, None);
2662            // No rule-specific CLI overrides implemented yet
2663        }
2664
2665        // Unknown keys are now collected during parsing and validated via validate_config_sourced()
2666
2667        Ok(sourced_config)
2668    }
2669
2670    /// Load and merge configurations from files and CLI overrides.
2671    /// If skip_auto_discovery is true, only explicit config paths are loaded.
2672    pub fn load_with_discovery(
2673        config_path: Option<&str>,
2674        cli_overrides: Option<&SourcedGlobalConfig>,
2675        skip_auto_discovery: bool,
2676    ) -> Result<Self, ConfigError> {
2677        Self::load_with_discovery_impl(config_path, cli_overrides, skip_auto_discovery, None)
2678    }
2679
2680    /// Validate the configuration against a rule registry.
2681    ///
2682    /// This method transitions the config from `ConfigLoaded` to `ConfigValidated` state,
2683    /// enabling conversion to `Config`. Validation warnings are stored in the config
2684    /// and can be displayed to the user.
2685    ///
2686    /// # Example
2687    ///
2688    /// ```ignore
2689    /// let loaded = SourcedConfig::load_with_discovery(path, None, false)?;
2690    /// let validated = loaded.validate(&registry)?;
2691    /// let config: Config = validated.into();
2692    /// ```
2693    pub fn validate(self, registry: &RuleRegistry) -> Result<SourcedConfig<ConfigValidated>, ConfigError> {
2694        let warnings = validate_config_sourced_internal(&self, registry);
2695
2696        Ok(SourcedConfig {
2697            global: self.global,
2698            per_file_ignores: self.per_file_ignores,
2699            rules: self.rules,
2700            loaded_files: self.loaded_files,
2701            unknown_keys: self.unknown_keys,
2702            project_root: self.project_root,
2703            validation_warnings: warnings,
2704            _state: PhantomData,
2705        })
2706    }
2707
2708    /// Validate and convert to Config in one step (convenience method).
2709    ///
2710    /// This combines `validate()` and `into()` for callers who want the
2711    /// validation warnings separately.
2712    pub fn validate_into(self, registry: &RuleRegistry) -> Result<(Config, Vec<ConfigValidationWarning>), ConfigError> {
2713        let validated = self.validate(registry)?;
2714        let warnings = validated.validation_warnings.clone();
2715        Ok((validated.into(), warnings))
2716    }
2717
2718    /// Skip validation and convert directly to ConfigValidated state.
2719    ///
2720    /// # Safety
2721    ///
2722    /// This method bypasses validation. Use only when:
2723    /// - You've already validated via `validate_config_sourced()`
2724    /// - You're in test code that doesn't need validation
2725    /// - You're migrating legacy code and will add proper validation later
2726    ///
2727    /// Prefer `validate()` for new code.
2728    pub fn into_validated_unchecked(self) -> SourcedConfig<ConfigValidated> {
2729        SourcedConfig {
2730            global: self.global,
2731            per_file_ignores: self.per_file_ignores,
2732            rules: self.rules,
2733            loaded_files: self.loaded_files,
2734            unknown_keys: self.unknown_keys,
2735            project_root: self.project_root,
2736            validation_warnings: Vec::new(),
2737            _state: PhantomData,
2738        }
2739    }
2740}
2741
2742/// Convert a validated configuration to the final Config type.
2743///
2744/// This implementation only exists for `SourcedConfig<ConfigValidated>`,
2745/// ensuring that validation must occur before conversion.
2746impl From<SourcedConfig<ConfigValidated>> for Config {
2747    fn from(sourced: SourcedConfig<ConfigValidated>) -> Self {
2748        let mut rules = BTreeMap::new();
2749        for (rule_name, sourced_rule_cfg) in sourced.rules {
2750            // Normalize rule name to uppercase for case-insensitive lookup
2751            let normalized_rule_name = rule_name.to_ascii_uppercase();
2752            let severity = sourced_rule_cfg.severity.map(|sv| sv.value);
2753            let mut values = BTreeMap::new();
2754            for (key, sourced_val) in sourced_rule_cfg.values {
2755                values.insert(key, sourced_val.value);
2756            }
2757            rules.insert(normalized_rule_name, RuleConfig { severity, values });
2758        }
2759        #[allow(deprecated)]
2760        let global = GlobalConfig {
2761            enable: sourced.global.enable.value,
2762            disable: sourced.global.disable.value,
2763            exclude: sourced.global.exclude.value,
2764            include: sourced.global.include.value,
2765            respect_gitignore: sourced.global.respect_gitignore.value,
2766            line_length: sourced.global.line_length.value,
2767            output_format: sourced.global.output_format.as_ref().map(|v| v.value.clone()),
2768            fixable: sourced.global.fixable.value,
2769            unfixable: sourced.global.unfixable.value,
2770            flavor: sourced.global.flavor.value,
2771            force_exclude: sourced.global.force_exclude.value,
2772            cache_dir: sourced.global.cache_dir.as_ref().map(|v| v.value.clone()),
2773            cache: sourced.global.cache.value,
2774        };
2775        Config {
2776            global,
2777            per_file_ignores: sourced.per_file_ignores.value,
2778            rules,
2779            project_root: sourced.project_root,
2780        }
2781    }
2782}
2783
2784/// Registry of all known rules and their config schemas
2785pub struct RuleRegistry {
2786    /// Map of rule name (e.g. "MD013") to set of valid config keys and their TOML value types
2787    pub rule_schemas: std::collections::BTreeMap<String, toml::map::Map<String, toml::Value>>,
2788    /// Map of rule name to config key aliases
2789    pub rule_aliases: std::collections::BTreeMap<String, std::collections::HashMap<String, String>>,
2790}
2791
2792impl RuleRegistry {
2793    /// Build a registry from a list of rules
2794    pub fn from_rules(rules: &[Box<dyn Rule>]) -> Self {
2795        let mut rule_schemas = std::collections::BTreeMap::new();
2796        let mut rule_aliases = std::collections::BTreeMap::new();
2797
2798        for rule in rules {
2799            let norm_name = if let Some((name, toml::Value::Table(table))) = rule.default_config_section() {
2800                let norm_name = normalize_key(&name); // Normalize the name from default_config_section
2801                rule_schemas.insert(norm_name.clone(), table);
2802                norm_name
2803            } else {
2804                let norm_name = normalize_key(rule.name()); // Normalize the name from rule.name()
2805                rule_schemas.insert(norm_name.clone(), toml::map::Map::new());
2806                norm_name
2807            };
2808
2809            // Store aliases if the rule provides them
2810            if let Some(aliases) = rule.config_aliases() {
2811                rule_aliases.insert(norm_name, aliases);
2812            }
2813        }
2814
2815        RuleRegistry {
2816            rule_schemas,
2817            rule_aliases,
2818        }
2819    }
2820
2821    /// Get all known rule names
2822    pub fn rule_names(&self) -> std::collections::BTreeSet<String> {
2823        self.rule_schemas.keys().cloned().collect()
2824    }
2825
2826    /// Get the valid configuration keys for a rule, including both original and normalized variants
2827    pub fn config_keys_for(&self, rule: &str) -> Option<std::collections::BTreeSet<String>> {
2828        self.rule_schemas.get(rule).map(|schema| {
2829            let mut all_keys = std::collections::BTreeSet::new();
2830
2831            // Always allow 'severity' for any rule
2832            all_keys.insert("severity".to_string());
2833
2834            // Add original keys from schema
2835            for key in schema.keys() {
2836                all_keys.insert(key.clone());
2837            }
2838
2839            // Add normalized variants for markdownlint compatibility
2840            for key in schema.keys() {
2841                // Add kebab-case variant
2842                all_keys.insert(key.replace('_', "-"));
2843                // Add snake_case variant
2844                all_keys.insert(key.replace('-', "_"));
2845                // Add normalized variant
2846                all_keys.insert(normalize_key(key));
2847            }
2848
2849            // Add any aliases defined by the rule
2850            if let Some(aliases) = self.rule_aliases.get(rule) {
2851                for alias_key in aliases.keys() {
2852                    all_keys.insert(alias_key.clone());
2853                    // Also add normalized variants of the alias
2854                    all_keys.insert(alias_key.replace('_', "-"));
2855                    all_keys.insert(alias_key.replace('-', "_"));
2856                    all_keys.insert(normalize_key(alias_key));
2857                }
2858            }
2859
2860            all_keys
2861        })
2862    }
2863
2864    /// Get the expected value type for a rule's configuration key, trying variants
2865    pub fn expected_value_for(&self, rule: &str, key: &str) -> Option<&toml::Value> {
2866        if let Some(schema) = self.rule_schemas.get(rule) {
2867            // Check if this key is an alias
2868            if let Some(aliases) = self.rule_aliases.get(rule)
2869                && let Some(canonical_key) = aliases.get(key)
2870            {
2871                // Use the canonical key for schema lookup
2872                if let Some(value) = schema.get(canonical_key) {
2873                    return Some(value);
2874                }
2875            }
2876
2877            // Try the original key
2878            if let Some(value) = schema.get(key) {
2879                return Some(value);
2880            }
2881
2882            // Try key variants
2883            let key_variants = [
2884                key.replace('-', "_"), // Convert kebab-case to snake_case
2885                key.replace('_', "-"), // Convert snake_case to kebab-case
2886                normalize_key(key),    // Normalized key (lowercase, kebab-case)
2887            ];
2888
2889            for variant in &key_variants {
2890                if let Some(value) = schema.get(variant) {
2891                    return Some(value);
2892                }
2893            }
2894        }
2895        None
2896    }
2897
2898    /// Resolve any rule name (canonical or alias) to its canonical form
2899    /// Returns None if the rule name is not recognized
2900    ///
2901    /// Resolution order:
2902    /// 1. Direct canonical name match
2903    /// 2. Static aliases (built-in markdownlint aliases)
2904    pub fn resolve_rule_name(&self, name: &str) -> Option<String> {
2905        // Try normalized canonical name first
2906        let normalized = normalize_key(name);
2907        if self.rule_schemas.contains_key(&normalized) {
2908            return Some(normalized);
2909        }
2910
2911        // Try static alias resolution (O(1) perfect hash lookup)
2912        resolve_rule_name_alias(name).map(|s| s.to_string())
2913    }
2914}
2915
2916/// Compile-time perfect hash map for O(1) rule alias lookups
2917/// Uses phf for zero-cost abstraction - compiles to direct jumps
2918static RULE_ALIAS_MAP: phf::Map<&'static str, &'static str> = phf::phf_map! {
2919    // Canonical names (identity mapping for consistency)
2920    "MD001" => "MD001",
2921    "MD003" => "MD003",
2922    "MD004" => "MD004",
2923    "MD005" => "MD005",
2924    "MD007" => "MD007",
2925    "MD008" => "MD008",
2926    "MD009" => "MD009",
2927    "MD010" => "MD010",
2928    "MD011" => "MD011",
2929    "MD012" => "MD012",
2930    "MD013" => "MD013",
2931    "MD014" => "MD014",
2932    "MD015" => "MD015",
2933    "MD018" => "MD018",
2934    "MD019" => "MD019",
2935    "MD020" => "MD020",
2936    "MD021" => "MD021",
2937    "MD022" => "MD022",
2938    "MD023" => "MD023",
2939    "MD024" => "MD024",
2940    "MD025" => "MD025",
2941    "MD026" => "MD026",
2942    "MD027" => "MD027",
2943    "MD028" => "MD028",
2944    "MD029" => "MD029",
2945    "MD030" => "MD030",
2946    "MD031" => "MD031",
2947    "MD032" => "MD032",
2948    "MD033" => "MD033",
2949    "MD034" => "MD034",
2950    "MD035" => "MD035",
2951    "MD036" => "MD036",
2952    "MD037" => "MD037",
2953    "MD038" => "MD038",
2954    "MD039" => "MD039",
2955    "MD040" => "MD040",
2956    "MD041" => "MD041",
2957    "MD042" => "MD042",
2958    "MD043" => "MD043",
2959    "MD044" => "MD044",
2960    "MD045" => "MD045",
2961    "MD046" => "MD046",
2962    "MD047" => "MD047",
2963    "MD048" => "MD048",
2964    "MD049" => "MD049",
2965    "MD050" => "MD050",
2966    "MD051" => "MD051",
2967    "MD052" => "MD052",
2968    "MD053" => "MD053",
2969    "MD054" => "MD054",
2970    "MD055" => "MD055",
2971    "MD056" => "MD056",
2972    "MD057" => "MD057",
2973    "MD058" => "MD058",
2974    "MD059" => "MD059",
2975    "MD060" => "MD060",
2976    "MD061" => "MD061",
2977    "MD062" => "MD062",
2978    "MD063" => "MD063",
2979    "MD064" => "MD064",
2980    "MD065" => "MD065",
2981    "MD066" => "MD066",
2982    "MD067" => "MD067",
2983    "MD068" => "MD068",
2984    "MD069" => "MD069",
2985
2986    // Aliases (hyphen format)
2987    "HEADING-INCREMENT" => "MD001",
2988    "HEADING-STYLE" => "MD003",
2989    "UL-STYLE" => "MD004",
2990    "LIST-INDENT" => "MD005",
2991    "UL-INDENT" => "MD007",
2992    "NO-TRAILING-SPACES" => "MD009",
2993    "NO-HARD-TABS" => "MD010",
2994    "NO-REVERSED-LINKS" => "MD011",
2995    "NO-MULTIPLE-BLANKS" => "MD012",
2996    "LINE-LENGTH" => "MD013",
2997    "COMMANDS-SHOW-OUTPUT" => "MD014",
2998    "NO-MISSING-SPACE-AFTER-LIST-MARKER" => "MD015",
2999    "NO-MISSING-SPACE-ATX" => "MD018",
3000    "NO-MULTIPLE-SPACE-ATX" => "MD019",
3001    "NO-MISSING-SPACE-CLOSED-ATX" => "MD020",
3002    "NO-MULTIPLE-SPACE-CLOSED-ATX" => "MD021",
3003    "BLANKS-AROUND-HEADINGS" => "MD022",
3004    "HEADING-START-LEFT" => "MD023",
3005    "NO-DUPLICATE-HEADING" => "MD024",
3006    "SINGLE-TITLE" => "MD025",
3007    "SINGLE-H1" => "MD025",
3008    "NO-TRAILING-PUNCTUATION" => "MD026",
3009    "NO-MULTIPLE-SPACE-BLOCKQUOTE" => "MD027",
3010    "NO-BLANKS-BLOCKQUOTE" => "MD028",
3011    "OL-PREFIX" => "MD029",
3012    "LIST-MARKER-SPACE" => "MD030",
3013    "BLANKS-AROUND-FENCES" => "MD031",
3014    "BLANKS-AROUND-LISTS" => "MD032",
3015    "NO-INLINE-HTML" => "MD033",
3016    "NO-BARE-URLS" => "MD034",
3017    "HR-STYLE" => "MD035",
3018    "NO-EMPHASIS-AS-HEADING" => "MD036",
3019    "NO-SPACE-IN-EMPHASIS" => "MD037",
3020    "NO-SPACE-IN-CODE" => "MD038",
3021    "NO-SPACE-IN-LINKS" => "MD039",
3022    "FENCED-CODE-LANGUAGE" => "MD040",
3023    "FIRST-LINE-HEADING" => "MD041",
3024    "FIRST-LINE-H1" => "MD041",
3025    "NO-EMPTY-LINKS" => "MD042",
3026    "REQUIRED-HEADINGS" => "MD043",
3027    "PROPER-NAMES" => "MD044",
3028    "NO-ALT-TEXT" => "MD045",
3029    "CODE-BLOCK-STYLE" => "MD046",
3030    "SINGLE-TRAILING-NEWLINE" => "MD047",
3031    "CODE-FENCE-STYLE" => "MD048",
3032    "EMPHASIS-STYLE" => "MD049",
3033    "STRONG-STYLE" => "MD050",
3034    "LINK-FRAGMENTS" => "MD051",
3035    "REFERENCE-LINKS-IMAGES" => "MD052",
3036    "LINK-IMAGE-REFERENCE-DEFINITIONS" => "MD053",
3037    "LINK-IMAGE-STYLE" => "MD054",
3038    "TABLE-PIPE-STYLE" => "MD055",
3039    "TABLE-COLUMN-COUNT" => "MD056",
3040    "EXISTING-RELATIVE-LINKS" => "MD057",
3041    "BLANKS-AROUND-TABLES" => "MD058",
3042    "TABLE-CELL-ALIGNMENT" => "MD059",
3043    "TABLE-FORMAT" => "MD060",
3044    "FORBIDDEN-TERMS" => "MD061",
3045    "LINK-DESTINATION-WHITESPACE" => "MD062",
3046    "HEADING-CAPITALIZATION" => "MD063",
3047    "NO-MULTIPLE-CONSECUTIVE-SPACES" => "MD064",
3048    "BLANKS-AROUND-HORIZONTAL-RULES" => "MD065",
3049    "FOOTNOTE-VALIDATION" => "MD066",
3050    "FOOTNOTE-DEFINITION-ORDER" => "MD067",
3051    "EMPTY-FOOTNOTE-DEFINITION" => "MD068",
3052    "NO-DUPLICATE-LIST-MARKERS" => "MD069",
3053};
3054
3055/// Resolve a rule name alias to its canonical form with O(1) perfect hash lookup
3056/// Converts rule aliases (like "ul-style", "line-length") to canonical IDs (like "MD004", "MD013")
3057/// Returns None if the rule name is not recognized
3058pub fn resolve_rule_name_alias(key: &str) -> Option<&'static str> {
3059    // Normalize: uppercase and replace underscores with hyphens
3060    let normalized_key = key.to_ascii_uppercase().replace('_', "-");
3061
3062    // O(1) perfect hash lookup
3063    RULE_ALIAS_MAP.get(normalized_key.as_str()).copied()
3064}
3065
3066/// Resolves a rule name to its canonical ID, supporting both rule IDs and aliases.
3067/// Returns the canonical ID (e.g., "MD001") for any valid input:
3068/// - "MD001" → "MD001" (canonical)
3069/// - "heading-increment" → "MD001" (alias)
3070/// - "HEADING_INCREMENT" → "MD001" (case-insensitive, underscore variant)
3071///
3072/// For unknown names, falls back to normalization (uppercase for MDxxx pattern, otherwise kebab-case).
3073pub fn resolve_rule_name(name: &str) -> String {
3074    resolve_rule_name_alias(name)
3075        .map(|s| s.to_string())
3076        .unwrap_or_else(|| normalize_key(name))
3077}
3078
3079/// Resolves a comma-separated list of rule names to canonical IDs.
3080/// Handles CLI input like "MD001,line-length,heading-increment".
3081/// Empty entries and whitespace are filtered out.
3082pub fn resolve_rule_names(input: &str) -> std::collections::HashSet<String> {
3083    input
3084        .split(',')
3085        .map(|s| s.trim())
3086        .filter(|s| !s.is_empty())
3087        .map(resolve_rule_name)
3088        .collect()
3089}
3090
3091/// Represents a config validation warning or error
3092#[derive(Debug, Clone)]
3093pub struct ConfigValidationWarning {
3094    pub message: String,
3095    pub rule: Option<String>,
3096    pub key: Option<String>,
3097}
3098
3099/// Internal validation function that works with any SourcedConfig state.
3100/// This is used by both the public `validate_config_sourced` and the typestate `validate()` method.
3101fn validate_config_sourced_internal<S>(
3102    sourced: &SourcedConfig<S>,
3103    registry: &RuleRegistry,
3104) -> Vec<ConfigValidationWarning> {
3105    validate_config_sourced_impl(&sourced.rules, &sourced.unknown_keys, registry)
3106}
3107
3108/// Core validation implementation that doesn't depend on SourcedConfig type parameter.
3109fn validate_config_sourced_impl(
3110    rules: &BTreeMap<String, SourcedRuleConfig>,
3111    unknown_keys: &[(String, String, Option<String>)],
3112    registry: &RuleRegistry,
3113) -> Vec<ConfigValidationWarning> {
3114    let mut warnings = Vec::new();
3115    let known_rules = registry.rule_names();
3116    // 1. Unknown rules
3117    for rule in rules.keys() {
3118        if !known_rules.contains(rule) {
3119            // Include both canonical names AND aliases for fuzzy matching
3120            let all_rule_names: Vec<String> = RULE_ALIAS_MAP.keys().map(|s| s.to_string()).collect();
3121            let message = if let Some(suggestion) = suggest_similar_key(rule, &all_rule_names) {
3122                // Convert alias suggestions to lowercase for better UX (MD001 stays uppercase, ul-style becomes lowercase)
3123                let formatted_suggestion = if suggestion.starts_with("MD") {
3124                    suggestion
3125                } else {
3126                    suggestion.to_lowercase()
3127                };
3128                format!("Unknown rule in config: {rule} (did you mean: {formatted_suggestion}?)")
3129            } else {
3130                format!("Unknown rule in config: {rule}")
3131            };
3132            warnings.push(ConfigValidationWarning {
3133                message,
3134                rule: Some(rule.clone()),
3135                key: None,
3136            });
3137        }
3138    }
3139    // 2. Unknown options and type mismatches
3140    for (rule, rule_cfg) in rules {
3141        if let Some(valid_keys) = registry.config_keys_for(rule) {
3142            for key in rule_cfg.values.keys() {
3143                if !valid_keys.contains(key) {
3144                    let valid_keys_vec: Vec<String> = valid_keys.iter().cloned().collect();
3145                    let message = if let Some(suggestion) = suggest_similar_key(key, &valid_keys_vec) {
3146                        format!("Unknown option for rule {rule}: {key} (did you mean: {suggestion}?)")
3147                    } else {
3148                        format!("Unknown option for rule {rule}: {key}")
3149                    };
3150                    warnings.push(ConfigValidationWarning {
3151                        message,
3152                        rule: Some(rule.clone()),
3153                        key: Some(key.clone()),
3154                    });
3155                } else {
3156                    // Type check: compare type of value to type of default
3157                    if let Some(expected) = registry.expected_value_for(rule, key) {
3158                        let actual = &rule_cfg.values[key].value;
3159                        if !toml_value_type_matches(expected, actual) {
3160                            warnings.push(ConfigValidationWarning {
3161                                message: format!(
3162                                    "Type mismatch for {}.{}: expected {}, got {}",
3163                                    rule,
3164                                    key,
3165                                    toml_type_name(expected),
3166                                    toml_type_name(actual)
3167                                ),
3168                                rule: Some(rule.clone()),
3169                                key: Some(key.clone()),
3170                            });
3171                        }
3172                    }
3173                }
3174            }
3175        }
3176    }
3177    // 3. Unknown global options (from unknown_keys)
3178    let known_global_keys = vec![
3179        "enable".to_string(),
3180        "disable".to_string(),
3181        "include".to_string(),
3182        "exclude".to_string(),
3183        "respect-gitignore".to_string(),
3184        "line-length".to_string(),
3185        "fixable".to_string(),
3186        "unfixable".to_string(),
3187        "flavor".to_string(),
3188        "force-exclude".to_string(),
3189        "output-format".to_string(),
3190        "cache-dir".to_string(),
3191        "cache".to_string(),
3192    ];
3193
3194    for (section, key, file_path) in unknown_keys {
3195        if section.contains("[global]") || section.contains("[tool.rumdl]") {
3196            let message = if let Some(suggestion) = suggest_similar_key(key, &known_global_keys) {
3197                if let Some(path) = file_path {
3198                    format!("Unknown global option in {path}: {key} (did you mean: {suggestion}?)")
3199                } else {
3200                    format!("Unknown global option: {key} (did you mean: {suggestion}?)")
3201                }
3202            } else if let Some(path) = file_path {
3203                format!("Unknown global option in {path}: {key}")
3204            } else {
3205                format!("Unknown global option: {key}")
3206            };
3207            warnings.push(ConfigValidationWarning {
3208                message,
3209                rule: None,
3210                key: Some(key.clone()),
3211            });
3212        } else if !key.is_empty() {
3213            // This is an unknown rule section (key is empty means it's a section header)
3214            continue;
3215        } else {
3216            // Unknown rule section - suggest similar rule names
3217            let rule_name = section.trim_matches(|c| c == '[' || c == ']');
3218            let all_rule_names: Vec<String> = RULE_ALIAS_MAP.keys().map(|s| s.to_string()).collect();
3219            let message = if let Some(suggestion) = suggest_similar_key(rule_name, &all_rule_names) {
3220                // Convert alias suggestions to lowercase for better UX (MD001 stays uppercase, ul-style becomes lowercase)
3221                let formatted_suggestion = if suggestion.starts_with("MD") {
3222                    suggestion
3223                } else {
3224                    suggestion.to_lowercase()
3225                };
3226                if let Some(path) = file_path {
3227                    format!("Unknown rule in {path}: {rule_name} (did you mean: {formatted_suggestion}?)")
3228                } else {
3229                    format!("Unknown rule in config: {rule_name} (did you mean: {formatted_suggestion}?)")
3230                }
3231            } else if let Some(path) = file_path {
3232                format!("Unknown rule in {path}: {rule_name}")
3233            } else {
3234                format!("Unknown rule in config: {rule_name}")
3235            };
3236            warnings.push(ConfigValidationWarning {
3237                message,
3238                rule: None,
3239                key: None,
3240            });
3241        }
3242    }
3243    warnings
3244}
3245
3246/// Validate a loaded config against the rule registry, using SourcedConfig for unknown key tracking.
3247///
3248/// This is the legacy API that works with `SourcedConfig<ConfigLoaded>`.
3249/// For new code, prefer using `sourced.validate(&registry)` which returns a
3250/// `SourcedConfig<ConfigValidated>` that can be converted to `Config`.
3251pub fn validate_config_sourced(
3252    sourced: &SourcedConfig<ConfigLoaded>,
3253    registry: &RuleRegistry,
3254) -> Vec<ConfigValidationWarning> {
3255    validate_config_sourced_internal(sourced, registry)
3256}
3257
3258/// Validate a config that has already been validated (no-op, returns stored warnings).
3259///
3260/// This exists for API consistency - validated configs already have their warnings stored.
3261pub fn validate_config_sourced_validated(
3262    sourced: &SourcedConfig<ConfigValidated>,
3263    _registry: &RuleRegistry,
3264) -> Vec<ConfigValidationWarning> {
3265    sourced.validation_warnings.clone()
3266}
3267
3268fn toml_type_name(val: &toml::Value) -> &'static str {
3269    match val {
3270        toml::Value::String(_) => "string",
3271        toml::Value::Integer(_) => "integer",
3272        toml::Value::Float(_) => "float",
3273        toml::Value::Boolean(_) => "boolean",
3274        toml::Value::Array(_) => "array",
3275        toml::Value::Table(_) => "table",
3276        toml::Value::Datetime(_) => "datetime",
3277    }
3278}
3279
3280/// Calculate Levenshtein distance between two strings (simple implementation)
3281fn levenshtein_distance(s1: &str, s2: &str) -> usize {
3282    let len1 = s1.len();
3283    let len2 = s2.len();
3284
3285    if len1 == 0 {
3286        return len2;
3287    }
3288    if len2 == 0 {
3289        return len1;
3290    }
3291
3292    let s1_chars: Vec<char> = s1.chars().collect();
3293    let s2_chars: Vec<char> = s2.chars().collect();
3294
3295    let mut prev_row: Vec<usize> = (0..=len2).collect();
3296    let mut curr_row = vec![0; len2 + 1];
3297
3298    for i in 1..=len1 {
3299        curr_row[0] = i;
3300        for j in 1..=len2 {
3301            let cost = if s1_chars[i - 1] == s2_chars[j - 1] { 0 } else { 1 };
3302            curr_row[j] = (prev_row[j] + 1)          // deletion
3303                .min(curr_row[j - 1] + 1)            // insertion
3304                .min(prev_row[j - 1] + cost); // substitution
3305        }
3306        std::mem::swap(&mut prev_row, &mut curr_row);
3307    }
3308
3309    prev_row[len2]
3310}
3311
3312/// Suggest a similar key from a list of valid keys using fuzzy matching
3313fn suggest_similar_key(unknown: &str, valid_keys: &[String]) -> Option<String> {
3314    let unknown_lower = unknown.to_lowercase();
3315    let max_distance = 2.max(unknown.len() / 3); // Allow up to 2 edits or 30% of string length
3316
3317    let mut best_match: Option<(String, usize)> = None;
3318
3319    for valid in valid_keys {
3320        let valid_lower = valid.to_lowercase();
3321        let distance = levenshtein_distance(&unknown_lower, &valid_lower);
3322
3323        if distance <= max_distance {
3324            if let Some((_, best_dist)) = &best_match {
3325                if distance < *best_dist {
3326                    best_match = Some((valid.clone(), distance));
3327                }
3328            } else {
3329                best_match = Some((valid.clone(), distance));
3330            }
3331        }
3332    }
3333
3334    best_match.map(|(key, _)| key)
3335}
3336
3337fn toml_value_type_matches(expected: &toml::Value, actual: &toml::Value) -> bool {
3338    use toml::Value::*;
3339    match (expected, actual) {
3340        (String(_), String(_)) => true,
3341        (Integer(_), Integer(_)) => true,
3342        (Float(_), Float(_)) => true,
3343        (Boolean(_), Boolean(_)) => true,
3344        (Array(_), Array(_)) => true,
3345        (Table(_), Table(_)) => true,
3346        (Datetime(_), Datetime(_)) => true,
3347        // Allow integer for float
3348        (Float(_), Integer(_)) => true,
3349        _ => false,
3350    }
3351}
3352
3353/// Parses pyproject.toml content and extracts the [tool.rumdl] section if present.
3354fn parse_pyproject_toml(content: &str, path: &str) -> Result<Option<SourcedConfigFragment>, ConfigError> {
3355    let doc: toml::Value =
3356        toml::from_str(content).map_err(|e| ConfigError::ParseError(format!("{path}: Failed to parse TOML: {e}")))?;
3357    let mut fragment = SourcedConfigFragment::default();
3358    let source = ConfigSource::PyprojectToml;
3359    let file = Some(path.to_string());
3360
3361    // Create rule registry for alias resolution
3362    let all_rules = rules::all_rules(&Config::default());
3363    let registry = RuleRegistry::from_rules(&all_rules);
3364
3365    // 1. Handle [tool.rumdl] and [tool.rumdl.global] sections
3366    if let Some(rumdl_config) = doc.get("tool").and_then(|t| t.get("rumdl"))
3367        && let Some(rumdl_table) = rumdl_config.as_table()
3368    {
3369        // Helper function to extract global config from a table
3370        let extract_global_config = |fragment: &mut SourcedConfigFragment, table: &toml::value::Table| {
3371            // Extract global options from the given table
3372            if let Some(enable) = table.get("enable")
3373                && let Ok(values) = Vec::<String>::deserialize(enable.clone())
3374            {
3375                // Resolve rule name aliases (e.g., "ul-style" -> "MD004")
3376                let normalized_values = values
3377                    .into_iter()
3378                    .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3379                    .collect();
3380                fragment
3381                    .global
3382                    .enable
3383                    .push_override(normalized_values, source, file.clone(), None);
3384            }
3385
3386            if let Some(disable) = table.get("disable")
3387                && let Ok(values) = Vec::<String>::deserialize(disable.clone())
3388            {
3389                // Resolve rule name aliases
3390                let normalized_values: Vec<String> = values
3391                    .into_iter()
3392                    .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3393                    .collect();
3394                fragment
3395                    .global
3396                    .disable
3397                    .push_override(normalized_values, source, file.clone(), None);
3398            }
3399
3400            if let Some(include) = table.get("include")
3401                && let Ok(values) = Vec::<String>::deserialize(include.clone())
3402            {
3403                fragment
3404                    .global
3405                    .include
3406                    .push_override(values, source, file.clone(), None);
3407            }
3408
3409            if let Some(exclude) = table.get("exclude")
3410                && let Ok(values) = Vec::<String>::deserialize(exclude.clone())
3411            {
3412                fragment
3413                    .global
3414                    .exclude
3415                    .push_override(values, source, file.clone(), None);
3416            }
3417
3418            if let Some(respect_gitignore) = table
3419                .get("respect-gitignore")
3420                .or_else(|| table.get("respect_gitignore"))
3421                && let Ok(value) = bool::deserialize(respect_gitignore.clone())
3422            {
3423                fragment
3424                    .global
3425                    .respect_gitignore
3426                    .push_override(value, source, file.clone(), None);
3427            }
3428
3429            if let Some(force_exclude) = table.get("force-exclude").or_else(|| table.get("force_exclude"))
3430                && let Ok(value) = bool::deserialize(force_exclude.clone())
3431            {
3432                fragment
3433                    .global
3434                    .force_exclude
3435                    .push_override(value, source, file.clone(), None);
3436            }
3437
3438            if let Some(output_format) = table.get("output-format").or_else(|| table.get("output_format"))
3439                && let Ok(value) = String::deserialize(output_format.clone())
3440            {
3441                if fragment.global.output_format.is_none() {
3442                    fragment.global.output_format = Some(SourcedValue::new(value.clone(), source));
3443                } else {
3444                    fragment
3445                        .global
3446                        .output_format
3447                        .as_mut()
3448                        .unwrap()
3449                        .push_override(value, source, file.clone(), None);
3450                }
3451            }
3452
3453            if let Some(fixable) = table.get("fixable")
3454                && let Ok(values) = Vec::<String>::deserialize(fixable.clone())
3455            {
3456                let normalized_values = values
3457                    .into_iter()
3458                    .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3459                    .collect();
3460                fragment
3461                    .global
3462                    .fixable
3463                    .push_override(normalized_values, source, file.clone(), None);
3464            }
3465
3466            if let Some(unfixable) = table.get("unfixable")
3467                && let Ok(values) = Vec::<String>::deserialize(unfixable.clone())
3468            {
3469                let normalized_values = values
3470                    .into_iter()
3471                    .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3472                    .collect();
3473                fragment
3474                    .global
3475                    .unfixable
3476                    .push_override(normalized_values, source, file.clone(), None);
3477            }
3478
3479            if let Some(flavor) = table.get("flavor")
3480                && let Ok(value) = MarkdownFlavor::deserialize(flavor.clone())
3481            {
3482                fragment.global.flavor.push_override(value, source, file.clone(), None);
3483            }
3484
3485            // Handle line-length special case - this should set the global line_length
3486            if let Some(line_length) = table.get("line-length").or_else(|| table.get("line_length"))
3487                && let Ok(value) = u64::deserialize(line_length.clone())
3488            {
3489                fragment
3490                    .global
3491                    .line_length
3492                    .push_override(LineLength::new(value as usize), source, file.clone(), None);
3493
3494                // Also add to MD013 rule config for backward compatibility
3495                let norm_md013_key = normalize_key("MD013");
3496                let rule_entry = fragment.rules.entry(norm_md013_key).or_default();
3497                let norm_line_length_key = normalize_key("line-length");
3498                let sv = rule_entry
3499                    .values
3500                    .entry(norm_line_length_key)
3501                    .or_insert_with(|| SourcedValue::new(line_length.clone(), ConfigSource::Default));
3502                sv.push_override(line_length.clone(), source, file.clone(), None);
3503            }
3504
3505            if let Some(cache_dir) = table.get("cache-dir").or_else(|| table.get("cache_dir"))
3506                && let Ok(value) = String::deserialize(cache_dir.clone())
3507            {
3508                if fragment.global.cache_dir.is_none() {
3509                    fragment.global.cache_dir = Some(SourcedValue::new(value.clone(), source));
3510                } else {
3511                    fragment
3512                        .global
3513                        .cache_dir
3514                        .as_mut()
3515                        .unwrap()
3516                        .push_override(value, source, file.clone(), None);
3517                }
3518            }
3519
3520            if let Some(cache) = table.get("cache")
3521                && let Ok(value) = bool::deserialize(cache.clone())
3522            {
3523                fragment.global.cache.push_override(value, source, file.clone(), None);
3524            }
3525        };
3526
3527        // First, check for [tool.rumdl.global] section
3528        if let Some(global_table) = rumdl_table.get("global").and_then(|g| g.as_table()) {
3529            extract_global_config(&mut fragment, global_table);
3530        }
3531
3532        // Also extract global options from [tool.rumdl] directly (for flat structure)
3533        extract_global_config(&mut fragment, rumdl_table);
3534
3535        // --- Extract per-file-ignores configurations ---
3536        // Check both hyphenated and underscored versions for compatibility
3537        let per_file_ignores_key = rumdl_table
3538            .get("per-file-ignores")
3539            .or_else(|| rumdl_table.get("per_file_ignores"));
3540
3541        if let Some(per_file_ignores_value) = per_file_ignores_key
3542            && let Some(per_file_table) = per_file_ignores_value.as_table()
3543        {
3544            let mut per_file_map = HashMap::new();
3545            for (pattern, rules_value) in per_file_table {
3546                if let Ok(rules) = Vec::<String>::deserialize(rules_value.clone()) {
3547                    let normalized_rules = rules
3548                        .into_iter()
3549                        .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3550                        .collect();
3551                    per_file_map.insert(pattern.clone(), normalized_rules);
3552                } else {
3553                    log::warn!(
3554                        "[WARN] Expected array for per-file-ignores pattern '{pattern}' in {path}, found {rules_value:?}"
3555                    );
3556                }
3557            }
3558            fragment
3559                .per_file_ignores
3560                .push_override(per_file_map, source, file.clone(), None);
3561        }
3562
3563        // --- Extract rule-specific configurations ---
3564        for (key, value) in rumdl_table {
3565            let norm_rule_key = normalize_key(key);
3566
3567            // Skip keys already handled as global or special cases
3568            // Note: Only skip these if they're NOT tables (rule sections are tables)
3569            let is_global_key = [
3570                "enable",
3571                "disable",
3572                "include",
3573                "exclude",
3574                "respect_gitignore",
3575                "respect-gitignore",
3576                "force_exclude",
3577                "force-exclude",
3578                "output_format",
3579                "output-format",
3580                "fixable",
3581                "unfixable",
3582                "per-file-ignores",
3583                "per_file_ignores",
3584                "global",
3585                "flavor",
3586                "cache_dir",
3587                "cache-dir",
3588                "cache",
3589            ]
3590            .contains(&norm_rule_key.as_str());
3591
3592            // Special handling for line-length: could be global config OR rule section
3593            let is_line_length_global =
3594                (norm_rule_key == "line-length" || norm_rule_key == "line_length") && !value.is_table();
3595
3596            if is_global_key || is_line_length_global {
3597                continue;
3598            }
3599
3600            // Try to resolve as a rule name (handles both canonical names and aliases)
3601            if let Some(resolved_rule_name) = registry.resolve_rule_name(key)
3602                && value.is_table()
3603                && let Some(rule_config_table) = value.as_table()
3604            {
3605                let rule_entry = fragment.rules.entry(resolved_rule_name.clone()).or_default();
3606                for (rk, rv) in rule_config_table {
3607                    let norm_rk = normalize_key(rk);
3608
3609                    // Special handling for severity - store in rule_entry.severity
3610                    if norm_rk == "severity" {
3611                        if let Ok(severity) = crate::rule::Severity::deserialize(rv.clone()) {
3612                            if rule_entry.severity.is_none() {
3613                                rule_entry.severity = Some(SourcedValue::new(severity, source));
3614                            } else {
3615                                rule_entry.severity.as_mut().unwrap().push_override(
3616                                    severity,
3617                                    source,
3618                                    file.clone(),
3619                                    None,
3620                                );
3621                            }
3622                        }
3623                        continue; // Skip regular value processing for severity
3624                    }
3625
3626                    let toml_val = rv.clone();
3627
3628                    let sv = rule_entry
3629                        .values
3630                        .entry(norm_rk.clone())
3631                        .or_insert_with(|| SourcedValue::new(toml_val.clone(), ConfigSource::Default));
3632                    sv.push_override(toml_val, source, file.clone(), None);
3633                }
3634            } else if registry.resolve_rule_name(key).is_none() {
3635                // Key is not a global/special key and not a recognized rule name
3636                // Track unknown keys under [tool.rumdl] for validation
3637                fragment
3638                    .unknown_keys
3639                    .push(("[tool.rumdl]".to_string(), key.to_string(), Some(path.to_string())));
3640            }
3641        }
3642    }
3643
3644    // 2. Handle [tool.rumdl.MDxxx] sections as rule-specific config (nested under [tool])
3645    if let Some(tool_table) = doc.get("tool").and_then(|t| t.as_table()) {
3646        for (key, value) in tool_table.iter() {
3647            if let Some(rule_name) = key.strip_prefix("rumdl.") {
3648                // Try to resolve as a rule name (handles both canonical names and aliases)
3649                if let Some(resolved_rule_name) = registry.resolve_rule_name(rule_name) {
3650                    if let Some(rule_table) = value.as_table() {
3651                        let rule_entry = fragment.rules.entry(resolved_rule_name.clone()).or_default();
3652                        for (rk, rv) in rule_table {
3653                            let norm_rk = normalize_key(rk);
3654
3655                            // Special handling for severity - store in rule_entry.severity
3656                            if norm_rk == "severity" {
3657                                if let Ok(severity) = crate::rule::Severity::deserialize(rv.clone()) {
3658                                    if rule_entry.severity.is_none() {
3659                                        rule_entry.severity = Some(SourcedValue::new(severity, source));
3660                                    } else {
3661                                        rule_entry.severity.as_mut().unwrap().push_override(
3662                                            severity,
3663                                            source,
3664                                            file.clone(),
3665                                            None,
3666                                        );
3667                                    }
3668                                }
3669                                continue; // Skip regular value processing for severity
3670                            }
3671
3672                            let toml_val = rv.clone();
3673                            let sv = rule_entry
3674                                .values
3675                                .entry(norm_rk.clone())
3676                                .or_insert_with(|| SourcedValue::new(toml_val.clone(), source));
3677                            sv.push_override(toml_val, source, file.clone(), None);
3678                        }
3679                    }
3680                } else if rule_name.to_ascii_uppercase().starts_with("MD")
3681                    || rule_name.chars().any(|c| c.is_alphabetic())
3682                {
3683                    // Track unknown rule sections like [tool.rumdl.MD999] or [tool.rumdl.unknown-rule]
3684                    fragment.unknown_keys.push((
3685                        format!("[tool.rumdl.{rule_name}]"),
3686                        String::new(),
3687                        Some(path.to_string()),
3688                    ));
3689                }
3690            }
3691        }
3692    }
3693
3694    // 3. Handle [tool.rumdl.MDxxx] sections as top-level keys (e.g., [tool.rumdl.MD007] or [tool.rumdl.line-length])
3695    if let Some(doc_table) = doc.as_table() {
3696        for (key, value) in doc_table.iter() {
3697            if let Some(rule_name) = key.strip_prefix("tool.rumdl.") {
3698                // Try to resolve as a rule name (handles both canonical names and aliases)
3699                if let Some(resolved_rule_name) = registry.resolve_rule_name(rule_name) {
3700                    if let Some(rule_table) = value.as_table() {
3701                        let rule_entry = fragment.rules.entry(resolved_rule_name.clone()).or_default();
3702                        for (rk, rv) in rule_table {
3703                            let norm_rk = normalize_key(rk);
3704
3705                            // Special handling for severity - store in rule_entry.severity
3706                            if norm_rk == "severity" {
3707                                if let Ok(severity) = crate::rule::Severity::deserialize(rv.clone()) {
3708                                    if rule_entry.severity.is_none() {
3709                                        rule_entry.severity = Some(SourcedValue::new(severity, source));
3710                                    } else {
3711                                        rule_entry.severity.as_mut().unwrap().push_override(
3712                                            severity,
3713                                            source,
3714                                            file.clone(),
3715                                            None,
3716                                        );
3717                                    }
3718                                }
3719                                continue; // Skip regular value processing for severity
3720                            }
3721
3722                            let toml_val = rv.clone();
3723                            let sv = rule_entry
3724                                .values
3725                                .entry(norm_rk.clone())
3726                                .or_insert_with(|| SourcedValue::new(toml_val.clone(), source));
3727                            sv.push_override(toml_val, source, file.clone(), None);
3728                        }
3729                    }
3730                } else if rule_name.to_ascii_uppercase().starts_with("MD")
3731                    || rule_name.chars().any(|c| c.is_alphabetic())
3732                {
3733                    // Track unknown rule sections like [tool.rumdl.MD999] or [tool.rumdl.unknown-rule]
3734                    fragment.unknown_keys.push((
3735                        format!("[tool.rumdl.{rule_name}]"),
3736                        String::new(),
3737                        Some(path.to_string()),
3738                    ));
3739                }
3740            }
3741        }
3742    }
3743
3744    // Only return Some(fragment) if any config was found
3745    let has_any = !fragment.global.enable.value.is_empty()
3746        || !fragment.global.disable.value.is_empty()
3747        || !fragment.global.include.value.is_empty()
3748        || !fragment.global.exclude.value.is_empty()
3749        || !fragment.global.fixable.value.is_empty()
3750        || !fragment.global.unfixable.value.is_empty()
3751        || fragment.global.output_format.is_some()
3752        || fragment.global.cache_dir.is_some()
3753        || !fragment.global.cache.value
3754        || !fragment.per_file_ignores.value.is_empty()
3755        || !fragment.rules.is_empty();
3756    if has_any { Ok(Some(fragment)) } else { Ok(None) }
3757}
3758
3759/// Parses rumdl.toml / .rumdl.toml content.
3760fn parse_rumdl_toml(content: &str, path: &str, source: ConfigSource) -> Result<SourcedConfigFragment, ConfigError> {
3761    let doc = content
3762        .parse::<DocumentMut>()
3763        .map_err(|e| ConfigError::ParseError(format!("{path}: Failed to parse TOML: {e}")))?;
3764    let mut fragment = SourcedConfigFragment::default();
3765    // source parameter provided by caller
3766    let file = Some(path.to_string());
3767
3768    // Define known rules before the loop
3769    let all_rules = rules::all_rules(&Config::default());
3770    let registry = RuleRegistry::from_rules(&all_rules);
3771
3772    // Handle [global] section
3773    if let Some(global_item) = doc.get("global")
3774        && let Some(global_table) = global_item.as_table()
3775    {
3776        for (key, value_item) in global_table.iter() {
3777            let norm_key = normalize_key(key);
3778            match norm_key.as_str() {
3779                "enable" | "disable" | "include" | "exclude" => {
3780                    if let Some(toml_edit::Value::Array(formatted_array)) = value_item.as_value() {
3781                        // Corrected: Iterate directly over the Formatted<Array>
3782                        let values: Vec<String> = formatted_array
3783                                .iter()
3784                                .filter_map(|item| item.as_str()) // Extract strings
3785                                .map(|s| s.to_string())
3786                                .collect();
3787
3788                        // Resolve rule name aliases for enable/disable (e.g., "ul-style" -> "MD004")
3789                        let final_values = if norm_key == "enable" || norm_key == "disable" {
3790                            values
3791                                .into_iter()
3792                                .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3793                                .collect()
3794                        } else {
3795                            values
3796                        };
3797
3798                        match norm_key.as_str() {
3799                            "enable" => fragment
3800                                .global
3801                                .enable
3802                                .push_override(final_values, source, file.clone(), None),
3803                            "disable" => {
3804                                fragment
3805                                    .global
3806                                    .disable
3807                                    .push_override(final_values, source, file.clone(), None)
3808                            }
3809                            "include" => {
3810                                fragment
3811                                    .global
3812                                    .include
3813                                    .push_override(final_values, source, file.clone(), None)
3814                            }
3815                            "exclude" => {
3816                                fragment
3817                                    .global
3818                                    .exclude
3819                                    .push_override(final_values, source, file.clone(), None)
3820                            }
3821                            _ => unreachable!("Outer match guarantees only enable/disable/include/exclude"),
3822                        }
3823                    } else {
3824                        log::warn!(
3825                            "[WARN] Expected array for global key '{}' in {}, found {}",
3826                            key,
3827                            path,
3828                            value_item.type_name()
3829                        );
3830                    }
3831                }
3832                "respect_gitignore" | "respect-gitignore" => {
3833                    // Handle both cases
3834                    if let Some(toml_edit::Value::Boolean(formatted_bool)) = value_item.as_value() {
3835                        let val = *formatted_bool.value();
3836                        fragment
3837                            .global
3838                            .respect_gitignore
3839                            .push_override(val, source, file.clone(), None);
3840                    } else {
3841                        log::warn!(
3842                            "[WARN] Expected boolean for global key '{}' in {}, found {}",
3843                            key,
3844                            path,
3845                            value_item.type_name()
3846                        );
3847                    }
3848                }
3849                "force_exclude" | "force-exclude" => {
3850                    // Handle both cases
3851                    if let Some(toml_edit::Value::Boolean(formatted_bool)) = value_item.as_value() {
3852                        let val = *formatted_bool.value();
3853                        fragment
3854                            .global
3855                            .force_exclude
3856                            .push_override(val, source, file.clone(), None);
3857                    } else {
3858                        log::warn!(
3859                            "[WARN] Expected boolean for global key '{}' in {}, found {}",
3860                            key,
3861                            path,
3862                            value_item.type_name()
3863                        );
3864                    }
3865                }
3866                "line_length" | "line-length" => {
3867                    // Handle both cases
3868                    if let Some(toml_edit::Value::Integer(formatted_int)) = value_item.as_value() {
3869                        let val = LineLength::new(*formatted_int.value() as usize);
3870                        fragment
3871                            .global
3872                            .line_length
3873                            .push_override(val, source, file.clone(), None);
3874                    } else {
3875                        log::warn!(
3876                            "[WARN] Expected integer for global key '{}' in {}, found {}",
3877                            key,
3878                            path,
3879                            value_item.type_name()
3880                        );
3881                    }
3882                }
3883                "output_format" | "output-format" => {
3884                    // Handle both cases
3885                    if let Some(toml_edit::Value::String(formatted_string)) = value_item.as_value() {
3886                        let val = formatted_string.value().clone();
3887                        if fragment.global.output_format.is_none() {
3888                            fragment.global.output_format = Some(SourcedValue::new(val.clone(), source));
3889                        } else {
3890                            fragment.global.output_format.as_mut().unwrap().push_override(
3891                                val,
3892                                source,
3893                                file.clone(),
3894                                None,
3895                            );
3896                        }
3897                    } else {
3898                        log::warn!(
3899                            "[WARN] Expected string for global key '{}' in {}, found {}",
3900                            key,
3901                            path,
3902                            value_item.type_name()
3903                        );
3904                    }
3905                }
3906                "cache_dir" | "cache-dir" => {
3907                    // Handle both cases
3908                    if let Some(toml_edit::Value::String(formatted_string)) = value_item.as_value() {
3909                        let val = formatted_string.value().clone();
3910                        if fragment.global.cache_dir.is_none() {
3911                            fragment.global.cache_dir = Some(SourcedValue::new(val.clone(), source));
3912                        } else {
3913                            fragment
3914                                .global
3915                                .cache_dir
3916                                .as_mut()
3917                                .unwrap()
3918                                .push_override(val, source, file.clone(), None);
3919                        }
3920                    } else {
3921                        log::warn!(
3922                            "[WARN] Expected string for global key '{}' in {}, found {}",
3923                            key,
3924                            path,
3925                            value_item.type_name()
3926                        );
3927                    }
3928                }
3929                "cache" => {
3930                    if let Some(toml_edit::Value::Boolean(b)) = value_item.as_value() {
3931                        let val = *b.value();
3932                        fragment.global.cache.push_override(val, source, file.clone(), None);
3933                    } else {
3934                        log::warn!(
3935                            "[WARN] Expected boolean for global key '{}' in {}, found {}",
3936                            key,
3937                            path,
3938                            value_item.type_name()
3939                        );
3940                    }
3941                }
3942                "fixable" => {
3943                    if let Some(toml_edit::Value::Array(formatted_array)) = value_item.as_value() {
3944                        let values: Vec<String> = formatted_array
3945                            .iter()
3946                            .filter_map(|item| item.as_str())
3947                            .map(normalize_key)
3948                            .collect();
3949                        fragment
3950                            .global
3951                            .fixable
3952                            .push_override(values, source, file.clone(), None);
3953                    } else {
3954                        log::warn!(
3955                            "[WARN] Expected array for global key '{}' in {}, found {}",
3956                            key,
3957                            path,
3958                            value_item.type_name()
3959                        );
3960                    }
3961                }
3962                "unfixable" => {
3963                    if let Some(toml_edit::Value::Array(formatted_array)) = value_item.as_value() {
3964                        let values: Vec<String> = formatted_array
3965                            .iter()
3966                            .filter_map(|item| item.as_str())
3967                            .map(|s| registry.resolve_rule_name(s).unwrap_or_else(|| normalize_key(s)))
3968                            .collect();
3969                        fragment
3970                            .global
3971                            .unfixable
3972                            .push_override(values, source, file.clone(), None);
3973                    } else {
3974                        log::warn!(
3975                            "[WARN] Expected array for global key '{}' in {}, found {}",
3976                            key,
3977                            path,
3978                            value_item.type_name()
3979                        );
3980                    }
3981                }
3982                "flavor" => {
3983                    if let Some(toml_edit::Value::String(formatted_string)) = value_item.as_value() {
3984                        let val = formatted_string.value();
3985                        if let Ok(flavor) = MarkdownFlavor::from_str(val) {
3986                            fragment.global.flavor.push_override(flavor, source, file.clone(), None);
3987                        } else {
3988                            log::warn!("[WARN] Unknown markdown flavor '{val}' in {path}");
3989                        }
3990                    } else {
3991                        log::warn!(
3992                            "[WARN] Expected string for global key '{}' in {}, found {}",
3993                            key,
3994                            path,
3995                            value_item.type_name()
3996                        );
3997                    }
3998                }
3999                _ => {
4000                    // Track unknown global keys for validation
4001                    fragment
4002                        .unknown_keys
4003                        .push(("[global]".to_string(), key.to_string(), Some(path.to_string())));
4004                    log::warn!("[WARN] Unknown key in [global] section of {path}: {key}");
4005                }
4006            }
4007        }
4008    }
4009
4010    // Handle [per-file-ignores] section
4011    if let Some(per_file_item) = doc.get("per-file-ignores")
4012        && let Some(per_file_table) = per_file_item.as_table()
4013    {
4014        let mut per_file_map = HashMap::new();
4015        for (pattern, value_item) in per_file_table.iter() {
4016            if let Some(toml_edit::Value::Array(formatted_array)) = value_item.as_value() {
4017                let rules: Vec<String> = formatted_array
4018                    .iter()
4019                    .filter_map(|item| item.as_str())
4020                    .map(|s| registry.resolve_rule_name(s).unwrap_or_else(|| normalize_key(s)))
4021                    .collect();
4022                per_file_map.insert(pattern.to_string(), rules);
4023            } else {
4024                let type_name = value_item.type_name();
4025                log::warn!(
4026                    "[WARN] Expected array for per-file-ignores pattern '{pattern}' in {path}, found {type_name}"
4027                );
4028            }
4029        }
4030        fragment
4031            .per_file_ignores
4032            .push_override(per_file_map, source, file.clone(), None);
4033    }
4034
4035    // Rule-specific: all other top-level tables
4036    for (key, item) in doc.iter() {
4037        // Skip known special sections
4038        if key == "global" || key == "per-file-ignores" {
4039            continue;
4040        }
4041
4042        // Resolve rule name (handles both canonical names like "MD004" and aliases like "ul-style")
4043        let norm_rule_name = if let Some(resolved) = registry.resolve_rule_name(key) {
4044            resolved
4045        } else {
4046            // Unknown rule - always track it for validation and suggestions
4047            fragment
4048                .unknown_keys
4049                .push((format!("[{key}]"), String::new(), Some(path.to_string())));
4050            continue;
4051        };
4052
4053        if let Some(tbl) = item.as_table() {
4054            let rule_entry = fragment.rules.entry(norm_rule_name.clone()).or_default();
4055            for (rk, rv_item) in tbl.iter() {
4056                let norm_rk = normalize_key(rk);
4057
4058                // Special handling for severity - store in rule_entry.severity
4059                if norm_rk == "severity" {
4060                    if let Some(toml_edit::Value::String(formatted_string)) = rv_item.as_value() {
4061                        let severity_str = formatted_string.value();
4062                        match crate::rule::Severity::deserialize(toml::Value::String(severity_str.to_string())) {
4063                            Ok(severity) => {
4064                                if rule_entry.severity.is_none() {
4065                                    rule_entry.severity = Some(SourcedValue::new(severity, source));
4066                                } else {
4067                                    rule_entry.severity.as_mut().unwrap().push_override(
4068                                        severity,
4069                                        source,
4070                                        file.clone(),
4071                                        None,
4072                                    );
4073                                }
4074                            }
4075                            Err(_) => {
4076                                log::warn!(
4077                                    "[WARN] Invalid severity '{severity_str}' for rule {norm_rule_name} in {path}. Valid values: error, warning"
4078                                );
4079                            }
4080                        }
4081                    }
4082                    continue; // Skip regular value processing for severity
4083                }
4084
4085                let maybe_toml_val: Option<toml::Value> = match rv_item.as_value() {
4086                    Some(toml_edit::Value::String(formatted)) => Some(toml::Value::String(formatted.value().clone())),
4087                    Some(toml_edit::Value::Integer(formatted)) => Some(toml::Value::Integer(*formatted.value())),
4088                    Some(toml_edit::Value::Float(formatted)) => Some(toml::Value::Float(*formatted.value())),
4089                    Some(toml_edit::Value::Boolean(formatted)) => Some(toml::Value::Boolean(*formatted.value())),
4090                    Some(toml_edit::Value::Datetime(formatted)) => Some(toml::Value::Datetime(*formatted.value())),
4091                    Some(toml_edit::Value::Array(formatted_array)) => {
4092                        // Convert toml_edit Array to toml::Value::Array
4093                        let mut values = Vec::new();
4094                        for item in formatted_array.iter() {
4095                            match item {
4096                                toml_edit::Value::String(formatted) => {
4097                                    values.push(toml::Value::String(formatted.value().clone()))
4098                                }
4099                                toml_edit::Value::Integer(formatted) => {
4100                                    values.push(toml::Value::Integer(*formatted.value()))
4101                                }
4102                                toml_edit::Value::Float(formatted) => {
4103                                    values.push(toml::Value::Float(*formatted.value()))
4104                                }
4105                                toml_edit::Value::Boolean(formatted) => {
4106                                    values.push(toml::Value::Boolean(*formatted.value()))
4107                                }
4108                                toml_edit::Value::Datetime(formatted) => {
4109                                    values.push(toml::Value::Datetime(*formatted.value()))
4110                                }
4111                                _ => {
4112                                    log::warn!(
4113                                        "[WARN] Skipping unsupported array element type in key '{norm_rule_name}.{norm_rk}' in {path}"
4114                                    );
4115                                }
4116                            }
4117                        }
4118                        Some(toml::Value::Array(values))
4119                    }
4120                    Some(toml_edit::Value::InlineTable(_)) => {
4121                        log::warn!(
4122                            "[WARN] Skipping inline table value for key '{norm_rule_name}.{norm_rk}' in {path}. Table conversion not yet fully implemented in parser."
4123                        );
4124                        None
4125                    }
4126                    None => {
4127                        log::warn!(
4128                            "[WARN] Skipping non-value item for key '{norm_rule_name}.{norm_rk}' in {path}. Expected simple value."
4129                        );
4130                        None
4131                    }
4132                };
4133                if let Some(toml_val) = maybe_toml_val {
4134                    let sv = rule_entry
4135                        .values
4136                        .entry(norm_rk.clone())
4137                        .or_insert_with(|| SourcedValue::new(toml_val.clone(), ConfigSource::Default));
4138                    sv.push_override(toml_val, source, file.clone(), None);
4139                }
4140            }
4141        } else if item.is_value() {
4142            log::warn!("[WARN] Ignoring top-level value key in {path}: '{key}'. Expected a table like [{key}].");
4143        }
4144    }
4145
4146    Ok(fragment)
4147}
4148
4149/// Loads and converts a markdownlint config file (.json or .yaml) into a SourcedConfigFragment.
4150fn load_from_markdownlint(path: &str) -> Result<SourcedConfigFragment, ConfigError> {
4151    // Use the unified loader from markdownlint_config.rs
4152    let ml_config = crate::markdownlint_config::load_markdownlint_config(path)
4153        .map_err(|e| ConfigError::ParseError(format!("{path}: {e}")))?;
4154    Ok(ml_config.map_to_sourced_rumdl_config_fragment(Some(path)))
4155}
4156
4157#[cfg(test)]
4158#[path = "config_intelligent_merge_tests.rs"]
4159mod config_intelligent_merge_tests;