"""
PowerPoint Preprocessor for DSOL V2 Extraction Pipeline.

This module ONLY handles speaker notes extraction.
Images and tables are handled by custom serializers during chunking.
"""

from pathlib import Path

import structlog
from pptx import Presentation
from pptx.util import Inches

logger = structlog.get_logger(__name__)


class PptxPreprocessor:
    """
    Preprocess PowerPoint documents before Docling conversion.

    ONLY extracts and embeds speaker notes inline.
    Images and tables are handled by ImgTableAnnotationSerializerProvider during chunking.
    """

    def __init__(self):
        """Initialize the PowerPoint preprocessor."""
        self.logger = structlog.get_logger()

    def preprocess(self, file_path: Path) -> Path:
        """
        Preprocess PowerPoint: extract speaker notes only.

        Args:
            file_path: Path to the .pptx file

        Returns:
            Path to preprocessed .pptx file with embedded speaker notes
        """
        self.logger.info("Starting PowerPoint preprocessing (speaker notes)", file=file_path.name)

        # Load presentation
        prs = Presentation(str(file_path))

        # Extract and embed speaker notes
        notes_count = self._extract_and_embed_notes(prs)
        self.logger.info(f"Extracted {notes_count} speaker notes")

        # Save preprocessed presentation
        output_path = file_path.parent / f"{file_path.stem}_preprocessed.pptx"
        prs.save(str(output_path))

        self.logger.info(
            "Preprocessing complete",
            input=file_path.name,
            output=output_path.name,
            notes=notes_count
        )

        return output_path

    def _extract_and_embed_notes(self, prs: Presentation) -> int:
        """
        Extract speaker notes and embed inline in slides.

        Adds notes as text boxes at bottom of slides for Docling to process.

        Args:
            prs: PowerPoint Presentation object

        Returns:
            Number of slides with speaker notes embedded
        """
        notes_count = 0

        for slide_num, slide in enumerate(prs.slides, start=1):
            if slide.has_notes_slide:
                notes_text = slide.notes_slide.notes_text_frame.text.strip()

                if notes_text:
                    # Add text box with speaker notes at bottom of slide
                    textbox = slide.shapes.add_textbox(
                        Inches(0.5),  # left
                        Inches(7),    # top
                        Inches(9),    # width
                        Inches(0.5)   # height
                    )
                    textbox.text_frame.text = f"[SPEAKER NOTES]: {notes_text}"
                    notes_count += 1

                    self.logger.debug(
                        f"Embedded notes from slide {slide_num}",
                        slide=slide_num,
                        notes_length=len(notes_text)
                    )

        return notes_count
