import os
import importlib.resources

def get_text(filename):
    """Read a file from the library's data folder or from a given path."""
    
    # First check if it's a path to an external file
    if os.path.isfile(filename):
        filepath = filename
    else:
        # Look inside the package's data folder
        package_dir = os.path.dirname(__file__)
        filepath = os.path.join(package_dir, "data", filename)
        if not os.path.isfile(filepath):
            raise FileNotFoundError(f"File '{filename}' not found in package data or filesystem.")

    ext = os.path.splitext(filepath)[1].lower()

    if ext == ".txt":
        return _read_txt(filepath)
    elif ext == ".pdf":
        return _read_pdf(filepath)
    elif ext == ".docx":
        return _read_docx(filepath)
    else:
        raise ValueError(f"Unsupported file type: '{ext}'. Supported: .txt, .pdf, .docx")


def _read_txt(filepath):
    with open(filepath, "r", encoding="utf-8") as f:
        return f.read()


def _read_pdf(filepath):
    try:
        import pdfplumber
    except ImportError:
        raise ImportError("pdfplumber is required for PDF support. Run: pip install pdfplumber")
    
    text = []
    with pdfplumber.open(filepath) as pdf:
        for page in pdf.pages:
            page_text = page.extract_text()
            if page_text:
                text.append(page_text)
    return "\n".join(text)


def _read_docx(filepath):
    try:
        from docx import Document
    except ImportError:
        raise ImportError("python-docx is required for Word support. Run: pip install python-docx")
    
    doc = Document(filepath)
    return "\n".join([para.text for para in doc.paragraphs if para.text.strip()])