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


class NoTrailingWhitespaceRule(BaseRule):
    """检测行尾空格规则"""

    rule_id = "no-trailing-whitespace"
    severity = "warning"

    # 排除代码块内的行尾空格（可选）
    EXCLUDE_CODE_BLOCKS = True

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

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

        in_code_block = False

        for line_num, line in enumerate(lines, 1):
            # 检测代码块边界
            if line.strip().startswith('```'):
                in_code_block = not in_code_block
                continue

            # 跳过代码块内的检查（可选）
            if self.exclude_code_blocks and in_code_block:
                continue

            # 检测行尾空格（包括空格和制表符）
            if line.rstrip('\r') != line.rstrip():
                # 找到行尾空格的位置
                stripped = line.rstrip()
                col_num = len(stripped) + 1

                diagnostics.append(Diagnostic(
                    file=file_path,
                    line=line_num,
                    column=col_num,
                    message=f"行尾发现 {len(line) - len(stripped)} 个空白字符",
                    severity=self.severity,
                    rule_id=self.rule_id
                ))

        return diagnostics