"""PDF 텍스트 추출 및 언어 감지 모듈."""

from pathlib import Path

from pypdf import PdfReader


def extract_text_from_pdf(pdf_path: str | Path) -> tuple[str, int]:
    """Extract full text and page count from a PDF."""
    reader = PdfReader(str(pdf_path))
    pages = []
    for page in reader.pages:
        text = page.extract_text() or ""
        pages.append(text)
    fulltext = "\n".join(pages)
    # PostgreSQL Text 컬럼은 NUL 바이트를 허용하지 않음
    fulltext = fulltext.replace("\x00", "")
    return fulltext, len(reader.pages)


def detect_language(text: str) -> str:
    """Simple language detection based on character ranges."""
    sample = text[:2000]
    ko_count = sum(1 for c in sample if '\uAC00' <= c <= '\uD7A3')
    ja_count = sum(1 for c in sample if '\u3040' <= c <= '\u309F' or '\u30A0' <= c <= '\u30FF')
    if ko_count > 50:
        return "ko"
    if ja_count > 50:
        return "ja"
    return "en"
