import os
import re
import unicodedata

def safe_filename(name: str, max_len: int = 100, default: str = "file", ascii_only: bool = True) -> str:
    """
    Convert an arbitrary filename into a safe, normalized filename:
    - Keeps only letters, digits, dash, underscore in the stem
    - Preserves a cleaned, alphanumeric extension (lowercased)
    - Replaces spaces and invalid chars with underscores
    - Collapses repeated underscores and trims length
    - Removes path segments and control characters

    Examples:
      " My Report (final).PDF " -> "My_Report_final.pdf"
      "../../weird\\path?.png"  -> "weird_path.png"
    """
    base = os.path.basename((name or "").replace("\x00", "")).strip()
    if not base or base in {".", ".."}:
        base = default

    if ascii_only:
        base = unicodedata.normalize("NFKD", base).encode("ascii", "ignore").decode("ascii")

    stem, ext = os.path.splitext(base)

    # Clean extension: keep only alnum, lowercase.
    ext = re.sub(r"[^A-Za-z0-9]", "", ext.lower())
    if ext:
        ext = "." + ext

    # Clean stem: allow letters, digits, dash, underscore; convert dots/spaces to underscore.
    stem = stem.replace(".", "_")
    stem = re.sub(r"\s+", "_", stem)
    stem = re.sub(r"[^A-Za-z0-9_-]", "_", stem)
    stem = re.sub(r"_+", "_", stem).strip("._-")

    if not stem:
        stem = default

    # Ensure total length cap (including extension).
    allow = max(1, max_len - len(ext))
    if len(stem) > allow:
        stem = stem[:allow].rstrip("._-")

    out = (stem or default) + ext
    return out or default