from __future__ import annotations

import html
import re

_TAG_RE = re.compile(r"<[^>]+>")
_WHITESPACE_RE = re.compile(r"[\t\r\f\v]+")
_MULTILINE_BREAK_RE = re.compile(r"\n{3,}")


def clean_text(text: str) -> str:
    """Remove obvious HTML tags and clipboard artifacts while preserving content."""
    if not text:
        return text

    text = html.unescape(text)
    text = _TAG_RE.sub(" ", text)
    text = _WHITESPACE_RE.sub(" ", text)
    text = _MULTILINE_BREAK_RE.sub("\n\n", text)
    text = re.sub(r" +", " ", text)
    return text.strip()
