"""Markdown file rule implementation - Markdown 文件内容规则实现."""

from __future__ import annotations

import html
import re
from pathlib import Path
from typing import Any

from ...models.fileinfo import FileInfo
from ._base import BaseContentRule

try:
    import markdown
except ImportError:
    markdown = None


class MarkdownRule(BaseContentRule):
    """Markdown 文件内容匹配规则 - 对 MD 文件适用."""

    def __init__(self, rule_data: dict[str, Any]) -> None:
        """初始化 Markdown 规则.

        Args:
            rule_data: 包含规则配置的字典
        """
        super().__init__(rule_data)
        self.file_type = "md"

    def parse_content(self, fileinfo: FileInfo) -> str:
        """从 Markdown 文件中提取内容.

        Args:
            fileinfo: 文件信息对象

        Returns
        -------
            提取的文本内容
        """
        try:
            content = Path(fileinfo.file_path).read_text(encoding="utf-8", errors="ignore")

            if markdown:
                # 将 Markdown 转换为 HTML,然后提取纯文本
                html_content = markdown.markdown(content)
                text = re.sub(r"<[^>]+>", " ", html_content)
                text = html.unescape(text)
                text = re.sub(r"\s+", " ", text).strip()
            else:
                # 如果没有安装 markdown 库,直接返回原始内容
                text = content

        except (OSError, ValueError) as e:
            from ...models.logger import logger

            logger.warning(f"提取 Markdown 时出错:{e}")
            return ""
        else:
            return text
