"""Best-effort text extraction from uploaded bytes (PDF, plain text)."""
from __future__ import annotations

from typing import Optional, Tuple


def extract_text_from_upload(
    *,
    filename: str,
    content_type: Optional[str],
    data: bytes,
) -> Tuple[Optional[str], str, Optional[str]]:
    """
    Returns (extracted_text, parse_status, error_message).
    parse_status: done | skipped
    """
    safe = (filename or "").lower()
    ct = (content_type or "").lower()

    if "text/" in ct or safe.endswith(".txt") or safe.endswith(".md"):
        try:
            text = data.decode("utf-8")
            return text, "done", None
        except UnicodeDecodeError as e:
            return None, "skipped", f"utf-8 decode error: {e}"

    if safe.endswith(".pdf"):
        try:
            import fitz  # PyMuPDF

            doc = fitz.open(stream=data, filetype="pdf")
            try:
                parts: list[str] = []
                for page in doc:
                    t = page.get_text()
                    if t and t.strip():
                        parts.append(t.strip())
                merged = "\n\n".join(parts)
                if not merged.strip():
                    return None, "skipped", "pdf_no_extractable_text"
                return merged, "done", None
            finally:
                doc.close()
        except Exception as e:
            return None, "skipped", f"pdf_parse_error: {e}"[:500]

    return None, "skipped", None
