"""分段预览 API — 只读预览文档分段结果（不向量化）。

用户上传文档前可预览分段效果，调整 chunk_size/chunk_overlap 参数后再正式提交。
"""

from __future__ import annotations

from pydantic import BaseModel, ConfigDict, Field

from agentkit.rag_platform.document_processor import (
    DEFAULT_CHUNK_OVERLAP,
    DEFAULT_CHUNK_SIZE,
    DocumentProcessor,
)


class PreviewChunk(BaseModel):
    """预览 chunk 条目。"""

    model_config = ConfigDict()

    index: int
    content: str
    metadata: dict[str, object] = Field(default_factory=dict)


class PreviewResult(BaseModel):
    """分段预览结果。"""

    model_config = ConfigDict()

    document_id: str = ""  # 预览阶段文档尚未创建，默认空
    chunks: list[PreviewChunk]
    total_chunks: int


def generate_preview(
    file_path: str,
    file_type: str,
    chunk_size: int = DEFAULT_CHUNK_SIZE,
    chunk_overlap: int = DEFAULT_CHUNK_OVERLAP,
) -> PreviewResult:
    """生成分段预览（只读，不向量化）。

    Args:
        file_path: 文件路径
        file_type: 文件类型（扩展名，不含点），如 "pdf"、"md"
        chunk_size: 分段大小（token 数），默认 512
        chunk_overlap: 分段重叠（token 数），默认 50

    Returns:
        PreviewResult，包含 chunk 列表和总数

    Raises:
        FileNotFoundError: 文件不存在
        ValueError: 解析失败
    """
    processor = DocumentProcessor(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
    chunks = processor.preview(
        file_path,
        file_type,
        chunk_size=chunk_size,
        chunk_overlap=chunk_overlap,
    )

    return PreviewResult(
        document_id="",
        chunks=[
            PreviewChunk(
                index=c["index"],
                content=c["content"],
                metadata=c.get("metadata", {}),
            )
            for c in chunks
        ],
        total_chunks=len(chunks),
    )


__all__ = [
    "PreviewChunk",
    "PreviewResult",
    "generate_preview",
]
