# src/rules/static/heading_space.py
import re
from typing import List, Dict, Any, Optional
from ..base import BaseRule, Diagnostic


class HeadingSpaceRule(BaseRule):
    """检测 Markdown 标题后必须有空格规则"""

    rule_id = "heading-space"
    severity = "error"

    # Markdown 标题正则：# 后必须跟空格
    HEADING_PATTERN = re.compile(r'^(#{1,6})([^#\s])')

    def __init__(self, config: Optional[Dict[str, Any]] = None):
        super().__init__(config)
        self.allow_atx_no_space = self.config.get('allow_atx_no_space', False)

    def check(self, file_path: str, content: str) -> List[Diagnostic]:
        diagnostics = []
        lines = content.split('\n')

        for line_num, line in enumerate(lines, 1):
            # 跳过空行
            if not line.strip():
                continue

            # 检查是否是标题行
            match = self.HEADING_PATTERN.match(line)
            if match:
                hashes = match.group(1)
                first_char = match.group(2)

                diagnostics.append(Diagnostic(
                    file=file_path,
                    line=line_num,
                    column=len(hashes) + 1,
                    message=f"标题 '{hashes}' 后必须有空格，应为 '{hashes} {first_char}'",
                    severity=self.severity,
                    rule_id=self.rule_id
                ))

        return diagnostics