"""Limpieza de artefactos tipicos de extraccion PyPDF2 en texto plano."""

from __future__ import annotations

import re


def clean_pdf_text(text: str) -> str:
    """Clean PDF text extraction artifacts.

    Removes: page-number markers like '1/20', tabs, hyphenated line breaks
    in mid-word, duplicated spaces, line breaks not at sentence end.

    Args:
        text: Raw text extracted from a PDF (e.g. via PyPDF2 or pdfplumber).

    Returns:
        Cleaned text with artifacts removed and whitespace normalized.
    """
    # Eliminar marcas de pagina tipo "1/20" o "3/128"
    text = re.sub(r"\b\d{1,2}/\d{1,3}\b", " ", text)
    # Tabs a espacio
    text = text.replace("\t", " ")
    # Dehyphenation: "exa-\nmple" -> "example"
    text = re.sub(r"-\s*\n\s*", "", text)
    # Saltos de linea que NO son fin de oracion -> espacio
    text = re.sub(r"(?<![\.!?])\n+", " ", text)
    # Colapsar espacios multiples
    text = re.sub(r" {2,}", " ", text)
    # Limpiar lineas vacias y trim por linea
    text = "\n".join(line.strip() for line in text.split("\n") if line.strip())
    return text.strip()
