"""Shared HTML → text for fetchers. Block tags become newlines; inline tags drop."""
from __future__ import annotations
import re
from html import unescape
_SCRIPT = re.compile(r"(?is)<(script|style)[^>]*>.*?\1>")
_BLOCK_END = re.compile(
r"(?i)(p|div|h[1-6]|li|tr|table|ul|ol|blockquote)\s*>|
"
)
_TAG = re.compile(r"<[^>]+>")
def html_to_text(html: str) -> str:
if not html:
return ""
html = _SCRIPT.sub("", html)
html = _BLOCK_END.sub("\n", html)
html = _TAG.sub("", html)
text = unescape(html).replace("\r\n", "\n").replace("\r", "\n")
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r" *\n *", "\n", text)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()