"""
LangChain adapter — maps ChunkRecord → langchain_core Document.
No hard dependency: langchain_core is imported inside the class.
"""

from __future__ import annotations

from collections.abc import Iterator
from pathlib import Path
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    pass


class ExtractorLoader:
    """
    LangChain BaseLoader compatible class.

    Usage:
        from extractor.integrations.langchain import ExtractorLoader
        docs = list(ExtractorLoader("paper.pdf").lazy_load())
    """

    def __init__(self, source: Path | str, **extract_kwargs):
        self.source = Path(source)
        self.extract_kwargs = extract_kwargs

    def lazy_load(self) -> Iterator:
        try:
            from langchain_core.documents import Document
        except ImportError as e:
            raise ImportError(
                "langchain-core not installed. Run: pip install langchain-core"
            ) from e

        from extractor import extract

        kwargs = dict(self.extract_kwargs)
        kwargs.setdefault("mode", "chunks")

        for chunk in extract(self.source, **kwargs):
            from extractor.schema import ChunkRecord

            if not isinstance(chunk, ChunkRecord):
                raise TypeError(
                    f"ExtractorLoader requires mode='chunks' or mode='dual-chunks', "
                    f"got {type(chunk).__name__}. Set mode='chunks' in extract_kwargs."
                )
            entities = getattr(chunk, "entities", None) or []
            entity_types = (
                chunk.chunk_metadata.entity_types
                if chunk.chunk_metadata and chunk.chunk_metadata.entity_types
                else []
            )
            yield Document(
                page_content=chunk.text,
                metadata={
                    "source": chunk.source_filename,
                    "source_sha256": chunk.source_sha256,
                    "section_path": chunk.section_path,
                    "section_path_str": " > ".join(chunk.section_path or []),
                    "page": chunk.page,
                    "element_type": chunk.element_type,
                    "chunk_id": chunk.id,
                    "has_table": chunk.chunk_metadata.has_table if chunk.chunk_metadata else False,
                    "token_count": chunk.token_count,
                    # Entity metadata for vector store payload filtering
                    "entity_types": entity_types,
                    "entities": [e.model_dump(exclude_none=True) for e in entities],
                },
            )

    def load(self) -> list:
        return list(self.lazy_load())
