"""DOCX file parser using python-docx (BaseBlobParser interface)."""

from __future__ import annotations

import logging
from typing import TYPE_CHECKING, Iterator

from langchain_core.document_loaders import BaseBlobParser
from langchain_core.documents import Document
from langchain_core.utils import guard_import

if TYPE_CHECKING:
    from langchain_core.documents.base import Blob

logger = logging.getLogger(__name__)


class DocxParser(BaseBlobParser):
    """Parse DOCX files into ``Document`` objects using ``python-docx``.

    Conforms to LangChain's :class:`BaseBlobParser` interface.

    !!! note "Optional Dependency"

        Requires ``python-docx``.  Install via:

        ```bash
        pip install langchain-google-classroom[parsers]
        ```
    """

    def lazy_parse(self, blob: Blob) -> Iterator[Document]:
        """Parse a DOCX blob into a single ``Document``.

        All paragraphs are concatenated into one document.

        Args:
            blob: A LangChain ``Blob`` containing DOCX bytes.

        Yields:
            A single ``Document`` with all paragraph text.
        """
        DocxDocument = guard_import(
            module_name="docx",
            pip_name="python-docx",
        ).Document

        from io import BytesIO

        doc = DocxDocument(BytesIO(blob.as_bytes()))
        paragraphs = [p.text for p in doc.paragraphs if p.text.strip()]
        text = "\n\n".join(paragraphs)

        if text:
            yield Document(
                page_content=text,
                metadata={"source": blob.source or ""},
            )
