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

from __future__ import annotations

from typing import Any

try:
    from pptx import Presentation
except ImportError:
    Presentation = None

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


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

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

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

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

        Args:
            fileinfo: 文件信息对象

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

            logger.warning("未安装 python-pptx, 跳过 PPTX 提取")
            return ""

        try:
            prs = Presentation(fileinfo.file_path)
            text_parts = []

            for slide_num, slide in enumerate(prs.slides, 1):
                text_parts.append(f"[Slide {slide_num}]")
                text_parts.extend(shape.text for shape in slide.shapes if hasattr(shape, "text"))

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

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