# Input sanitization utilities
import os
import re

_SAFE_NAME_RE = re.compile(r'^[a-zA-Z0-9_\-]+$')
_ALLOWED_SAVE_DIRS = [os.path.expanduser("~/maps"), "/tmp/maps"]


def _safe_name(name: str, default: str = "map") -> str:
    """Remove dangerous characters from file/map names."""
    if not name or not _SAFE_NAME_RE.match(name):
        return default
    return name


def _safe_dir(path: str) -> str:
    """Validate directory against allowed whitelist."""
    resolved = os.path.realpath(os.path.expanduser(path))
    for allowed in _ALLOWED_SAVE_DIRS:
        allowed_resolved = os.path.realpath(os.path.expanduser(allowed))
        if resolved.startswith(allowed_resolved):
            return resolved
    return os.path.realpath(os.path.expanduser(_ALLOWED_SAVE_DIRS[0]))
