from dataclasses import dataclass
from pathlib import Path

from pypdf import PdfReader

from kbqa.api.errors import AppError


@dataclass(frozen=True, slots=True)
class LoadedPage:
    content: str
    page_number: int | None


def load_document(path: Path, file_type: str) -> list[LoadedPage]:
    if file_type == "pdf":
        with path.open("rb") as handle:
            if handle.read(5) != b"%PDF-":
                raise AppError("INVALID_PDF", "PDF 文件格式无效", 415)
        reader = PdfReader(str(path))
        pages = [
            LoadedPage(content=(page.extract_text() or "").strip(), page_number=index + 1)
            for index, page in enumerate(reader.pages)
        ]
        pages = [page for page in pages if page.content]
        if not pages:
            raise AppError(
                "PDF_TEXT_NOT_EXTRACTABLE",
                "PDF 中没有可提取文本，暂不支持扫描件 OCR",
                415,
            )
        return pages
    try:
        content = path.read_text(encoding="utf-8").strip()
    except UnicodeDecodeError as exc:
        raise AppError("TEXT_ENCODING_ERROR", "文本文件必须使用 UTF-8 编码", 415) from exc
    if not content:
        raise AppError("EMPTY_DOCUMENT", "文档内容为空", 415)
    return [LoadedPage(content=content, page_number=None)]
