from __future__ import annotations

import re
import unicodedata


SAFE_NAME_FALLBACK = "untitled"
DEFAULT_MAX_LEN = 90


def normalize_filename_part(raw: str, *, max_len: int = DEFAULT_MAX_LEN) -> str:
    value = unicodedata.normalize("NFKD", raw).encode("ascii", "ignore").decode("ascii")
    value = value.lower().strip()
    value = re.sub(r"[^a-z0-9\s-]", "", value)
    value = re.sub(r"\s+", "-", value)
    value = re.sub(r"-+", "-", value)
    value = value.strip("-")
    if not value:
        value = SAFE_NAME_FALLBACK
    return value[:max_len].strip("-") or SAFE_NAME_FALLBACK


def build_markdown_filename(title: str, channel: str) -> str:
    title_part = normalize_filename_part(title)
    channel_part = normalize_filename_part(channel)
    return f"{title_part}__{channel_part}.md"
