"""PDF 文件发现与文本提取

从 PDF 发票文件中提取原始文本内容。

对外接口:
    find_pdf_files(directory)       -> list[Path]  查找目录下所有 PDF
    extract_text_from_pdf(filepath) -> str         提取 PDF 文本
"""

from pathlib import Path

from .. import get_logger

log = get_logger("pdf")


def find_pdf_files(directory: str = ".") -> list[Path]:
    """查找目录下所有 PDF 文件(非递归)"""
    pdf_dir = Path(directory)
    if not pdf_dir.exists():
        return []
    return sorted(pdf_dir.glob("*.pdf"))


def extract_text_from_pdf(filepath: Path) -> str:
    """从单个 PDF 中提取全部文本"""
    try:
        import pdfplumber
    except ImportError as err:
        raise ImportError("缺少 pdfplumber，请执行: uv pip install pdfplumber") from err

    try:
        parts = []
        with pdfplumber.open(filepath) as pdf:
            for page in pdf.pages:
                text = page.extract_text()
                if text:
                    parts.append(text)
        return "\n".join(parts)
    except Exception as e:
        log.error(f"无法读取 {filepath.name}: {e}")
        return ""
