/// Rule MD029: Ordered list item prefix
///
/// See [docs/md029.md](../../docs/md029.md) for full documentation, configuration, and examples.
use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
use crate::rule_config_serde::RuleConfig;
use crate::utils::regex_cache::ORDERED_LIST_MARKER_REGEX;
use toml;

mod md029_config;
pub use md029_config::{ListStyle, MD029Config};

#[derive(Debug, Clone, Default)]
pub struct MD029OrderedListPrefix {
    config: MD029Config,
}

impl MD029OrderedListPrefix {
    pub fn new(style: ListStyle) -> Self {
        Self {
            config: MD029Config { style },
        }
    }

    pub fn from_config_struct(config: MD029Config) -> Self {
        Self { config }
    }

    #[inline]
    fn parse_marker_number(marker: &str) -> Option<usize> {
        // Handle marker format like "1." or "1"
        let num_part = if let Some(stripped) = marker.strip_suffix('.') {
            stripped
        } else {
            marker
        };
        num_part.parse::<usize>().ok()
    }

    #[inline]
    fn get_expected_number(&self, index: usize, detected_style: Option<ListStyle>) -> usize {
        // Use detected_style when the configuration is auto-detect mode (OneOrOrdered or Consistent)
        // For explicit style configurations, always use the configured style
        let style = match self.config.style {
            ListStyle::OneOrOrdered | ListStyle::Consistent => detected_style.unwrap_or(ListStyle::OneOne),
            _ => self.config.style.clone(),
        };

        match style {
            ListStyle::One | ListStyle::OneOne => 1,
            ListStyle::Ordered => index + 1,
            ListStyle::Ordered0 => index,
            ListStyle::OneOrOrdered | ListStyle::Consistent => {
                // This shouldn't be reached since we handle these above
                1
            }
        }
    }

    /// Detect the style being used in a list by checking all items for prevalence
    fn detect_list_style(
        items: &[(
            usize,
            &crate::lint_context::LineInfo,
            &crate::lint_context::ListItemInfo,
        )],
    ) -> ListStyle {
        if items.len() < 2 {
            // With only one item, we can't determine the style, default to OneOne
            return ListStyle::OneOne;
        }

        let first_num = Self::parse_marker_number(&items[0].2.marker);
        let second_num = Self::parse_marker_number(&items[1].2.marker);

        // Fast path: Check for Ordered0 special case (starts with 0, 1)
        if matches!((first_num, second_num), (Some(0), Some(1))) {
            return ListStyle::Ordered0;
        }

        // Fast path: If first 2 items aren't both "1", it must be Ordered (O(1))
        // This handles ~95% of lists instantly: "1. 2. 3...", "2. 3. 4...", etc.
        if first_num != Some(1) || second_num != Some(1) {
            return ListStyle::Ordered;
        }

        // Slow path: Both first items are "1", check if ALL are "1" (O(n))
        // This is necessary for lists like "1. 1. 1..." vs "1. 1. 2. 3..."
        let all_ones = items
            .iter()
            .all(|(_, _, item)| Self::parse_marker_number(&item.marker) == Some(1));

        if all_ones {
            ListStyle::OneOne
        } else {
            ListStyle::Ordered
        }
    }
}

impl Rule for MD029OrderedListPrefix {
    fn name(&self) -> &'static str {
        "MD029"
    }

    fn description(&self) -> &'static str {
        "Ordered list marker value"
    }

    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
        // Early returns for performance
        if ctx.content.is_empty() {
            return Ok(Vec::new());
        }

        // Quick check for any ordered list markers before processing
        if !ctx.content.contains('.') || !ctx.content.lines().any(|line| ORDERED_LIST_MARKER_REGEX.is_match(line)) {
            return Ok(Vec::new());
        }

        let mut warnings = Vec::new();

        // Collect all list blocks that contain ordered items (not just purely ordered blocks)
        // This handles mixed lists where ordered items are nested within unordered lists
        let blocks_with_ordered: Vec<_> = ctx
            .list_blocks
            .iter()
            .filter(|block| {
                // Check if this block contains any ordered items
                block.item_lines.iter().any(|&line| {
                    ctx.line_info(line)
                        .and_then(|info| info.list_item.as_ref())
                        .map(|item| item.is_ordered)
                        .unwrap_or(false)
                })
            })
            .collect();

        if blocks_with_ordered.is_empty() {
            return Ok(Vec::new());
        }

        // Group consecutive list blocks that should be treated as continuous
        let mut block_groups = Vec::new();
        let mut current_group = vec![blocks_with_ordered[0]];

        for i in 1..blocks_with_ordered.len() {
            let prev_block = blocks_with_ordered[i - 1];
            let current_block = blocks_with_ordered[i];

            // This catches the pattern: 1. item / - sub / 1. item (should be 2.)
            let has_only_unindented_lists =
                self.has_only_unindented_lists_between(ctx, prev_block.end_line, current_block.start_line);

            // Be more conservative: only group if there are no structural separators
            // Check specifically for headings between the blocks
            let has_heading_between =
                self.has_heading_between_blocks(ctx, prev_block.end_line, current_block.start_line);

            // Check if there are only code blocks/fences between these list blocks
            let between_content_is_code_only =
                self.is_only_code_between_blocks(ctx, prev_block.end_line, current_block.start_line);

            // Group blocks if:
            // 1. They have only code between them, OR
            // 2. They have only unindented list items between them (the new case!)
            let should_group = (between_content_is_code_only || has_only_unindented_lists)
                && self.blocks_are_logically_continuous(ctx, prev_block.end_line, current_block.start_line)
                && !has_heading_between;

            if should_group {
                // Treat as continuation of the same logical list
                current_group.push(current_block);
            } else {
                // Start a new list group
                block_groups.push(current_group);
                current_group = vec![current_block];
            }
        }
        block_groups.push(current_group);

        // For Consistent style, detect document-wide prevalent style
        let document_wide_style = if self.config.style == ListStyle::Consistent {
            // Collect ALL ordered items from ALL groups
            let mut all_document_items = Vec::new();
            for group in &block_groups {
                for list_block in group {
                    for &item_line in &list_block.item_lines {
                        if let Some(line_info) = ctx.line_info(item_line)
                            && let Some(list_item) = &line_info.list_item
                            && list_item.is_ordered
                        {
                            all_document_items.push((item_line, line_info, list_item));
                        }
                    }
                }
            }
            // Detect style across entire document
            if !all_document_items.is_empty() {
                Some(Self::detect_list_style(&all_document_items))
            } else {
                None
            }
        } else {
            None
        };

        // Process each group of blocks as a continuous list
        for group in block_groups {
            self.check_ordered_list_group(ctx, &group, &mut warnings, document_wide_style.clone());
        }

        Ok(warnings)
    }

    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
        // Use the same logic as check() - just apply the fixes from warnings
        let warnings = self.check(ctx)?;

        if warnings.is_empty() {
            // No changes needed
            return Ok(ctx.content.to_string());
        }

        // Collect fixes and sort by position
        let mut fixes: Vec<&Fix> = Vec::new();
        for warning in &warnings {
            if let Some(ref fix) = warning.fix {
                fixes.push(fix);
            }
        }
        fixes.sort_by_key(|f| f.range.start);

        let mut result = String::new();
        let mut last_pos = 0;
        let content_bytes = ctx.content.as_bytes();

        for fix in fixes {
            // Add content before the fix
            if last_pos < fix.range.start {
                let chunk = &content_bytes[last_pos..fix.range.start];
                result.push_str(
                    std::str::from_utf8(chunk).map_err(|_| LintError::InvalidInput("Invalid UTF-8".to_string()))?,
                );
            }
            // Add the replacement
            result.push_str(&fix.replacement);
            last_pos = fix.range.end;
        }

        // Add remaining content
        if last_pos < content_bytes.len() {
            let chunk = &content_bytes[last_pos..];
            result.push_str(
                std::str::from_utf8(chunk).map_err(|_| LintError::InvalidInput("Invalid UTF-8".to_string()))?,
            );
        }

        Ok(result)
    }

    /// Get the category of this rule for selective processing
    fn category(&self) -> RuleCategory {
        RuleCategory::List
    }

    /// Check if this rule should be skipped
    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
        ctx.content.is_empty() || !ctx.likely_has_lists()
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn default_config_section(&self) -> Option<(String, toml::Value)> {
        let default_config = MD029Config::default();
        let json_value = serde_json::to_value(&default_config).ok()?;
        let toml_value = crate::rule_config_serde::json_to_toml_value(&json_value)?;
        if let toml::Value::Table(table) = toml_value {
            if !table.is_empty() {
                Some((MD029Config::RULE_NAME.to_string(), toml::Value::Table(table)))
            } else {
                None
            }
        } else {
            None
        }
    }

    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
    where
        Self: Sized,
    {
        let rule_config = crate::rule_config_serde::load_rule_config::<MD029Config>(config);
        Box::new(MD029OrderedListPrefix::from_config_struct(rule_config))
    }
}

impl MD029OrderedListPrefix {
    /// Check for lazy continuation lines in a list block
    fn check_for_lazy_continuation(
        &self,
        ctx: &crate::lint_context::LintContext,
        list_block: &crate::lint_context::ListBlock,
        warnings: &mut Vec<LintWarning>,
    ) {
        // Check all lines in the block for lazy continuation
        for line_num in list_block.start_line..=list_block.end_line {
            if let Some(line_info) = ctx.line_info(line_num) {
                // Skip list item lines themselves
                if list_block.item_lines.contains(&line_num) {
                    continue;
                }

                // Skip blank lines
                if line_info.is_blank {
                    continue;
                }

                // Skip lines that are in code blocks
                if line_info.in_code_block {
                    continue;
                }

                // Skip code fence lines
                let trimmed = line_info.content(ctx.content).trim();
                if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
                    continue;
                }

                // Skip headings - they should never be treated as lazy continuation
                if line_info.heading.is_some() {
                    continue;
                }

                // Check if this is a lazy continuation (0-2 spaces)
                if line_info.indent <= 2 && !line_info.content(ctx.content).trim().is_empty() {
                    // This is a lazy continuation - add a style warning
                    let col = line_info.indent + 1;

                    warnings.push(LintWarning {
                        rule_name: Some(self.name().to_string()),
                        message: "List continuation should be indented (lazy continuation detected)".to_string(),
                        line: line_num,
                        column: col,
                        end_line: line_num,
                        end_column: col,
                        severity: Severity::Warning,
                        fix: Some(Fix {
                            range: line_info.byte_offset..line_info.byte_offset,
                            replacement: "   ".to_string(), // Add 3 spaces
                        }),
                    });
                }
            }
        }
    }

    /// Check if blocks are separated only by list items or properly indented list continuation content
    /// This helps detect the pattern: 1. item / - nested sub / 1. item (should be 2.)
    /// Now also allows indented nested lists and content that's properly indented for list continuation
    fn has_only_unindented_lists_between(
        &self,
        ctx: &crate::lint_context::LintContext,
        end_line: usize,
        start_line: usize,
    ) -> bool {
        if end_line >= start_line {
            return false;
        }

        // Calculate minimum continuation indent from the previous block's last item
        let min_continuation_indent =
            if let Some(prev_block) = ctx.list_blocks.iter().find(|block| block.end_line == end_line) {
                if let Some(&last_item_line) = prev_block.item_lines.last() {
                    if let Some(line_info) = ctx.line_info(last_item_line) {
                        if let Some(list_item) = &line_info.list_item {
                            if list_item.is_ordered {
                                list_item.marker.len() + 1 // Add 1 for space after ordered markers
                            } else {
                                2 // Unordered lists need at least 2 spaces
                            }
                        } else {
                            3 // Fallback
                        }
                    } else {
                        3 // Fallback
                    }
                } else {
                    3 // Fallback
                }
            } else {
                3 // Fallback
            };

        for line_num in (end_line + 1)..start_line {
            if let Some(line_info) = ctx.line_info(line_num) {
                let trimmed = line_info.content(ctx.content).trim();

                // Skip empty lines
                if trimmed.is_empty() {
                    continue;
                }

                // Allow any list item (both unindented and properly indented nested lists)
                if line_info.list_item.is_some() {
                    // Check if nested list has sufficient indentation to be continuation
                    if line_info.indent >= min_continuation_indent {
                        continue; // Properly indented nested list
                    }
                    // Unindented or under-indented list item breaks continuity
                    return false;
                }

                // Allow fence markers that are properly indented
                if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
                    if line_info.indent >= min_continuation_indent {
                        continue; // Properly indented fence marker
                    }
                    // Under-indented fence marker breaks continuity
                    return false;
                }

                // Allow code blocks that are properly indented
                if line_info.in_code_block {
                    if line_info.indent >= min_continuation_indent {
                        continue; // Properly indented code block
                    }
                    // Under-indented code block breaks continuity
                    return false;
                }

                // Allow other indented text that's part of list continuation
                if line_info.indent >= min_continuation_indent {
                    continue;
                }

                // Any other content (unindented or under-indented) breaks continuity
                return false;
            }
        }

        true
    }

    /// Calculate the minimum indentation required for continuing a list block
    fn calculate_min_continuation_indent(&self, ctx: &crate::lint_context::LintContext, end_line: usize) -> usize {
        if let Some(prev_block) = ctx.list_blocks.iter().find(|block| block.end_line == end_line) {
            if let Some(&last_item_line) = prev_block.item_lines.last() {
                if let Some(line_info) = ctx.line_info(last_item_line) {
                    if let Some(list_item) = &line_info.list_item {
                        if list_item.is_ordered {
                            list_item.marker.len() + 1 // Add 1 for space after ordered markers
                        } else {
                            2 // Unordered lists need at least 2 spaces
                        }
                    } else {
                        3 // Fallback
                    }
                } else {
                    3 // Fallback
                }
            } else {
                3 // Fallback
            }
        } else {
            3 // Fallback
        }
    }

    /// Check if two list blocks are logically continuous (no major structural separators)
    fn blocks_are_logically_continuous(
        &self,
        ctx: &crate::lint_context::LintContext,
        end_line: usize,
        start_line: usize,
    ) -> bool {
        if end_line >= start_line {
            return false;
        }

        // Calculate minimum continuation indent from the previous block's last item
        let min_continuation_indent = self.calculate_min_continuation_indent(ctx, end_line);

        for line_num in (end_line + 1)..start_line {
            if let Some(line_info) = ctx.line_info(line_num) {
                // Skip empty lines
                if line_info.is_blank {
                    continue;
                }

                // If there's any heading, the lists are not continuous
                if line_info.heading.is_some() {
                    return false;
                }

                let trimmed = line_info.content(ctx.content).trim();

                // Allow list items if properly indented
                if line_info.list_item.is_some() {
                    if line_info.indent >= min_continuation_indent {
                        continue; // Properly indented nested list
                    }
                    // Under-indented list breaks continuity
                    return false;
                }

                // Allow fence markers if properly indented
                if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
                    if line_info.indent >= min_continuation_indent {
                        continue; // Properly indented fence
                    }
                    // Under-indented fence breaks continuity
                    return false;
                }

                // Allow code blocks if properly indented
                if line_info.in_code_block {
                    if line_info.indent >= min_continuation_indent {
                        continue; // Properly indented code block
                    }
                    // Under-indented code block breaks continuity
                    return false;
                }

                // Allow other indented text that's part of list continuation
                if line_info.indent >= min_continuation_indent {
                    continue;
                }

                // Any other unindented or under-indented content breaks continuity
                if !trimmed.is_empty() {
                    return false;
                }
            }
        }

        true
    }

    fn is_only_code_between_blocks(
        &self,
        ctx: &crate::lint_context::LintContext,
        end_line: usize,
        start_line: usize,
    ) -> bool {
        if end_line >= start_line {
            return false;
        }

        // Calculate minimum continuation indent from the previous block's last item
        let min_continuation_indent = self.calculate_min_continuation_indent(ctx, end_line);

        for line_num in (end_line + 1)..start_line {
            if let Some(line_info) = ctx.line_info(line_num) {
                let trimmed = line_info.content(ctx.content).trim();

                // Skip empty lines
                if trimmed.is_empty() {
                    continue;
                }

                // Enhanced code block analysis
                if line_info.in_code_block || trimmed.starts_with("```") || trimmed.starts_with("~~~") {
                    // Check if this is a standalone code block that should separate lists
                    if line_info.in_code_block {
                        // Use the new classification system to determine if this code block separates lists
                        let context = crate::utils::code_block_utils::CodeBlockUtils::analyze_code_block_context(
                            &ctx.lines,
                            line_num - 1,
                            min_continuation_indent,
                        );

                        // If it's a standalone code block, lists should be separated
                        if matches!(context, crate::utils::code_block_utils::CodeBlockContext::Standalone) {
                            return false; // Lists are separated, not continuous
                        }
                    }
                    continue; // Other code block lines (indented/adjacent) don't break continuity
                }

                // If there's a heading, lists are definitely separated
                if line_info.heading.is_some() {
                    return false;
                }

                // Any other non-empty content means lists are truly separated
                return false;
            }
        }

        true
    }

    /// Check if there are any headings between two list blocks
    fn has_heading_between_blocks(
        &self,
        ctx: &crate::lint_context::LintContext,
        end_line: usize,
        start_line: usize,
    ) -> bool {
        if end_line >= start_line {
            return false;
        }

        for line_num in (end_line + 1)..start_line {
            if let Some(line_info) = ctx.line_info(line_num)
                && line_info.heading.is_some()
            {
                return true;
            }
        }

        false
    }

    /// Find the closest parent list item for an ordered item (can be ordered or unordered)
    /// Returns the line number of the parent, or 0 if no parent found
    fn find_parent_list_item(
        &self,
        ctx: &crate::lint_context::LintContext,
        ordered_line: usize,
        ordered_indent: usize,
    ) -> usize {
        // Look backward from the ordered item to find its closest parent
        for line_num in (1..ordered_line).rev() {
            if let Some(line_info) = ctx.line_info(line_num) {
                if let Some(list_item) = &line_info.list_item {
                    // Found a list item - check if it could be the parent
                    if list_item.marker_column < ordered_indent {
                        // This list item is at a lower indentation, so it's the parent
                        return line_num;
                    }
                }
                // If we encounter non-blank, non-list content at column 0, stop looking
                else if !line_info.is_blank && line_info.indent == 0 {
                    break;
                }
            }
        }
        0 // No parent found
    }

    /// Check a group of ordered list blocks that should be treated as continuous
    fn check_ordered_list_group(
        &self,
        ctx: &crate::lint_context::LintContext,
        group: &[&crate::lint_context::ListBlock],
        warnings: &mut Vec<LintWarning>,
        document_wide_style: Option<ListStyle>,
    ) {
        // Collect all items from all blocks in the group
        let mut all_items = Vec::new();

        for list_block in group {
            // First, check for lazy continuation in this block
            self.check_for_lazy_continuation(ctx, list_block, warnings);

            for &item_line in &list_block.item_lines {
                if let Some(line_info) = ctx.line_info(item_line)
                    && let Some(list_item) = &line_info.list_item
                {
                    // Skip unordered lists (safety check)
                    if !list_item.is_ordered {
                        continue;
                    }
                    all_items.push((item_line, line_info, list_item));
                }
            }
        }

        // Sort by line number to ensure correct order
        all_items.sort_by_key(|(line_num, _, _)| *line_num);

        // Group items by indentation level AND parent context
        // Use (indent_level, parent_line) as the key to separate sequences under different parents
        type LevelGroups<'a> = std::collections::HashMap<
            (usize, usize),
            Vec<(
                usize,
                &'a crate::lint_context::LineInfo,
                &'a crate::lint_context::ListItemInfo,
            )>,
        >;
        let mut level_groups: LevelGroups = std::collections::HashMap::new();

        for (line_num, line_info, list_item) in all_items {
            // Find the closest parent list item (ordered or unordered) for this ordered item
            let parent_line = self.find_parent_list_item(ctx, line_num, list_item.marker_column);

            // Group by both marker column (indentation level) and parent context
            level_groups
                .entry((list_item.marker_column, parent_line))
                .or_default()
                .push((line_num, line_info, list_item));
        }

        // Process each indentation level and parent context separately
        for ((_indent, _parent), mut group) in level_groups {
            // Sort by line number to ensure correct order
            group.sort_by_key(|(line_num, _, _)| *line_num);

            // Use document-wide style if provided (Consistent mode),
            // otherwise detect per-group for OneOrOrdered, or use None for explicit styles
            let detected_style = if let Some(doc_style) = document_wide_style.clone() {
                // Consistent mode: use document-wide prevalent style
                Some(doc_style)
            } else if self.config.style == ListStyle::OneOrOrdered {
                // OneOrOrdered mode: detect style per-group
                Some(Self::detect_list_style(&group))
            } else {
                // Explicit style configuration
                None
            };

            // Check each item in the group for correct sequence
            for (idx, (line_num, line_info, list_item)) in group.iter().enumerate() {
                // Parse the actual number from the marker (e.g., "1." -> 1)
                if let Some(actual_num) = Self::parse_marker_number(&list_item.marker) {
                    let expected_num = self.get_expected_number(idx, detected_style.clone());

                    if actual_num != expected_num {
                        // Calculate byte position for the fix
                        let marker_start = line_info.byte_offset + list_item.marker_column;
                        // Use the actual marker length (e.g., "05" is 2 chars, not 1)
                        let number_len = if let Some(dot_pos) = list_item.marker.find('.') {
                            dot_pos // Length up to the dot
                        } else if let Some(paren_pos) = list_item.marker.find(')') {
                            paren_pos // Length up to the paren
                        } else {
                            list_item.marker.len() // Fallback to full marker length
                        };

                        // Determine the style context for the warning message
                        let style_name = match detected_style.as_ref().unwrap_or(&ListStyle::Ordered) {
                            ListStyle::OneOne => "one",
                            ListStyle::Ordered => "ordered",
                            ListStyle::Ordered0 => "ordered0",
                            _ => "ordered", // fallback
                        };

                        let style_context = match self.config.style {
                            ListStyle::Consistent => format!("document style '{style_name}'"),
                            ListStyle::OneOrOrdered => format!("list style '{style_name}'"),
                            ListStyle::One | ListStyle::OneOne => "configured style 'one'".to_string(),
                            ListStyle::Ordered => "configured style 'ordered'".to_string(),
                            ListStyle::Ordered0 => "configured style 'ordered0'".to_string(),
                        };

                        warnings.push(LintWarning {
                            rule_name: Some(self.name().to_string()),
                            message: format!(
                                "Ordered list item number {actual_num} does not match {style_context} (expected {expected_num})"
                            ),
                            line: *line_num,
                            column: list_item.marker_column + 1,
                            end_line: *line_num,
                            end_column: list_item.marker_column + number_len + 1,
                            severity: Severity::Warning,
                            fix: Some(Fix {
                                range: marker_start..marker_start + number_len,
                                replacement: expected_num.to_string(),
                            }),
                        });
                    }
                }
            }
        }
    }
}

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

    #[test]
    fn test_basic_functionality() {
        // Test with default style (ordered)
        let rule = MD029OrderedListPrefix::default();

        // Test with correctly ordered list
        let content = "1. First item\n2. Second item\n3. Third item";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
        let result = rule.check(&ctx).unwrap();
        assert!(result.is_empty());

        // Test with incorrectly ordered list
        let content = "1. First item\n3. Third item\n5. Fifth item";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 2); // Should have warnings for items 3 and 5

        // Test with one-one style
        let rule = MD029OrderedListPrefix::new(ListStyle::OneOne);
        let content = "1. First item\n2. Second item\n3. Third item";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 2); // Should have warnings for items 2 and 3

        // Test with ordered0 style
        let rule = MD029OrderedListPrefix::new(ListStyle::Ordered0);
        let content = "0. First item\n1. Second item\n2. Third item";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
        let result = rule.check(&ctx).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn test_redundant_computation_fix() {
        // This test confirms that the redundant computation bug is fixed
        // Previously: get_list_number() was called twice (once for is_some(), once for unwrap())
        // Now: get_list_number() is called once with if let pattern

        let rule = MD029OrderedListPrefix::default();

        // Test with mixed valid and edge case content
        let content = "1. First item\n3. Wrong number\n2. Another wrong number";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);

        // This should not panic and should produce warnings for incorrect numbering
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 2); // Should have warnings for items 3 and 2

        // Verify the warnings have correct content
        assert!(result[0].message.contains("3") && result[0].message.contains("expected 2"));
        assert!(result[1].message.contains("2") && result[1].message.contains("expected 3"));
    }

    #[test]
    fn test_performance_improvement() {
        // This test verifies that the fix improves performance by avoiding redundant calls
        let rule = MD029OrderedListPrefix::default();

        // Create a larger list to test performance
        let mut content = String::new();
        for i in 1..=100 {
            content.push_str(&format!("{}. Item {}\n", i + 1, i)); // All wrong numbers
        }

        let ctx = crate::lint_context::LintContext::new(&content, crate::config::MarkdownFlavor::Standard);

        // This should complete without issues and produce warnings for all items
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 100); // Should have warnings for all 100 items

        // Verify first and last warnings
        assert!(result[0].message.contains("2") && result[0].message.contains("expected 1"));
        assert!(result[99].message.contains("101") && result[99].message.contains("expected 100"));
    }

    #[test]
    fn test_one_or_ordered_with_all_ones() {
        // Test OneOrOrdered style with all 1s (should pass)
        let rule = MD029OrderedListPrefix::new(ListStyle::OneOrOrdered);

        let content = "1. First item\n1. Second item\n1. Third item";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
        let result = rule.check(&ctx).unwrap();
        assert!(result.is_empty(), "All ones should be valid in OneOrOrdered mode");
    }

    #[test]
    fn test_one_or_ordered_with_sequential() {
        // Test OneOrOrdered style with sequential numbering (should pass)
        let rule = MD029OrderedListPrefix::new(ListStyle::OneOrOrdered);

        let content = "1. First item\n2. Second item\n3. Third item";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Sequential numbering should be valid in OneOrOrdered mode"
        );
    }

    #[test]
    fn test_one_or_ordered_with_mixed_style() {
        // Test OneOrOrdered style with mixed numbering (should fail)
        let rule = MD029OrderedListPrefix::new(ListStyle::OneOrOrdered);

        let content = "1. First item\n2. Second item\n1. Third item";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "Mixed style should produce one warning");
        assert!(result[0].message.contains("1") && result[0].message.contains("expected 3"));
    }

    #[test]
    fn test_one_or_ordered_separate_lists() {
        // Test OneOrOrdered with separate lists using different styles (should pass)
        let rule = MD029OrderedListPrefix::new(ListStyle::OneOrOrdered);

        let content = "# First list\n\n1. Item A\n1. Item B\n\n# Second list\n\n1. Item X\n2. Item Y\n3. Item Z";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Separate lists can use different styles in OneOrOrdered mode"
        );
    }
}
