import re
from html import escape

from markupsafe import Markup


TRANSLIT = str.maketrans(
    {
        "а": "a", "б": "b", "в": "v", "г": "g", "д": "d", "е": "e", "ё": "e",
        "ж": "zh", "з": "z", "и": "i", "й": "y", "к": "k", "л": "l", "м": "m",
        "н": "n", "о": "o", "п": "p", "р": "r", "с": "s", "т": "t", "у": "u",
        "ф": "f", "х": "h", "ц": "c", "ч": "ch", "ш": "sh", "щ": "sch",
        "ъ": "", "ы": "y", "ь": "", "э": "e", "ю": "yu", "я": "ya",
    }
)


def slugify(value: str) -> str:
    value = value.strip().lower().translate(TRANSLIT)
    value = re.sub(r"[^a-z0-9]+", "-", value).strip("-")
    return value[:180] or "article"


def paragraphs(value: str) -> Markup:
    blocks = []
    for part in re.split(r"\n\s*\n", value.strip()):
        lines = "<br>".join(escape(line.strip()) for line in part.splitlines() if line.strip())
        if lines:
            blocks.append(f"<p>{lines}</p>")
    return Markup("".join(blocks))


def excerpt(value: str, limit: int = 180) -> str:
    compact = re.sub(r"\s+", " ", value or "").strip()
    if len(compact) <= limit:
        return compact
    return compact[: limit - 1].rsplit(" ", 1)[0] + "…"
