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

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


class HtmlRule(BaseContentRule):
    """HTML 文件内容匹配规则 - 对 HTML/HTM 文件适用."""

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

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

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

        Args:
            fileinfo: 文件信息对象

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

            # 移除 HTML 标签
            text = re.sub(r"<[^>]+>", " ", html_content)
            # 解码 HTML 实体
            text = html.unescape(text)
            # 压缩空白字符
            return re.sub(r"\s+", " ", text).strip()

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

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