from __future__ import annotations

from datetime import datetime, timezone
from typing import List, Tuple


def utc_now() -> str:
    """Return current UTC time as ISO-8601 string."""
    return datetime.now(tz=timezone.utc).isoformat()


def sanitize_name(name: str) -> str:
    """Sanitize a name for use as a filename or SQL table identifier."""
    return "".join(c if c.isalnum() or c in ("_", "-") else "_" for c in name)


def route_subdir(name: str, routes: List[Tuple[str, str]]) -> str:
    """Match *name* against a list of (prefix, subdir) pairs.

    Returns the *subdir* for the first matching prefix, or ``""`` if
    nothing matches.  Used by NoSQLStorage, BlobStorage, and
    CacheStorage to segregate files by provider.
    """
    for prefix, subdir in routes:
        if name.startswith(prefix):
            return subdir
    return ""


def prefixed_name(name: str, prefix: str, separator: str = "-") -> str:
    """Ensure *name* carries the given *prefix*.

    If *name* already starts with ``prefix + separator``, return it
    unchanged.  Otherwise prepend ``prefix + separator``.
    """
    tag = f"{prefix}{separator}"
    return name if name.startswith(tag) else f"{tag}{name}"
