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

from __future__ import annotations

from typing import Any

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

try:
    from docx import Document
except ImportError:
    Document = None


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

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

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

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

        Args:
            fileinfo: 文件信息对象

        Returns
        -------
            提取的文本内容
        """
        if Document is None:
            logger.warning("未安装 python-docx, 跳过 DOCX 提取")
            return ""

        try:
            doc = Document(fileinfo.file_path)
        except (OSError, ValueError) as e:
            logger.warning(f"提取 DOCX 时出错:{e}")
            return ""

        # 提取段落文本
        text_parts = [paragraph.text for paragraph in doc.paragraphs]

        # 提取表格文本
        for table in doc.tables:
            for row in table.rows:
                row_text = " | ".join(cell.text for cell in row.cells)
                text_parts.append(row_text)

        return "\n".join(text_parts)
