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

import logging
from pathlib import Path

import pymupdf

logger = logging.getLogger(__name__)


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


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"
