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

from __future__ import annotations

from typing import Any

try:
    from openpyxl import load_workbook
except ImportError:
    load_workbook = None

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


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

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

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

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

        Args:
            fileinfo: 文件信息对象

        Returns
        -------
            提取的文本内容
        """
        if load_workbook is None:
            from ...models.logger import logger

            logger.warning("未安装 openpyxl, 跳过 XLSX 提取")
            return ""

        wb = None
        try:
            wb = load_workbook(fileinfo.file_path, read_only=True, data_only=True)
            text_parts = []

            for sheet_name in wb.sheetnames:
                sheet = wb[sheet_name]
                text_parts.append(f"[Sheet: {sheet_name}]")
                for row in sheet.iter_rows(values_only=True):
                    row_text = " | ".join(str(cell) if cell is not None else "" for cell in row)
                    if row_text.strip():
                        text_parts.append(row_text)

            return "\n".join(text_parts)
        except (OSError, ValueError) as e:
            from ...models.logger import logger

            logger.warning(f"提取 XLSX 时出错:{e}")
            return ""
        finally:
            if wb:
                wb.close()
