from uuid import UUID, uuid5

from langchain_text_splitters import RecursiveCharacterTextSplitter

from kbqa.indexing.loaders import LoadedPage
from kbqa.rag.types import PreparedChunk


def split_pages(
    document_id: str,
    pages: list[LoadedPage],
    chunk_size: int,
    chunk_overlap: int,
) -> list[PreparedChunk]:
    splitter = RecursiveCharacterTextSplitter(
        chunk_size=chunk_size,
        chunk_overlap=chunk_overlap,
        length_function=len,
    )
    chunks: list[PreparedChunk] = []
    namespace = UUID(document_id)
    for page in pages:
        for content in splitter.split_text(page.content):
            order_index = len(chunks)
            chunks.append(
                PreparedChunk(
                    id=str(uuid5(namespace, str(order_index))),
                    document_id=document_id,
                    order_index=order_index,
                    page_number=page.page_number,
                    content=content,
                )
            )
    return chunks
