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

from __future__ import annotations

from typing import Any

from defusedxml.ElementTree import ParseError, parse

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


class XmlRule(BaseContentRule):
    """XML 文件内容匹配规则 - 对 XML 文件适用."""

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

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

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

        Args:
            fileinfo: 文件信息对象

        Returns
        -------
            提取的文本内容
        """
        try:
            tree = parse(fileinfo.file_path)
            root = tree.getroot()

            text_parts = [elem.text for elem in root.iter() if elem.text and elem.text.strip()]
            return "\n".join(text_parts)

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

            logger.warning(f"提取 XML 时出错:{e}")
            return ""
        except RuntimeError as e:
            # 捕获其他可能的运行时错误
            from ...models.logger import logger

            logger.warning(f"提取 XML 时发生错误:{e}")
            return ""
