import re
import unicodedata

RESERVED_SUBDOMAINS: frozenset[str] = frozenset(
    ["www", "admin", "api", "mail", "smtp", "indelis", "support"]
)


def slugify_subdomain(org_name: str) -> str:
    """Convert an organization name to a URL-safe subdomain slug.

    Steps:
      1. Lowercase
      2. Normalize unicode (strip accents, transliterate)
      3. Replace non-alphanumeric sequences with a single hyphen
      4. Collapse multiple hyphens
      5. Trim leading/trailing hyphens
      6. Truncate to 62 chars (leaving room for collision suffixes)
    """
    s = org_name.lower()
    # Normalize unicode — strip accents and map to closest ASCII
    s = unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode("ascii")
    # Replace anything that is not a-z or 0-9 with a hyphen
    s = re.sub(r"[^a-z0-9]+", "-", s)
    # Collapse consecutive hyphens
    s = re.sub(r"-+", "-", s)
    # Strip leading/trailing hyphens
    s = s.strip("-")
    # Truncate to 62 chars and re-strip any trailing hyphen introduced by cut
    s = s[:62].rstrip("-")
    return s


def split_full_name(name: str) -> tuple[str, str]:
    """Split a full name into (first_name, last_name).

    Single-word names go entirely to first_name; last_name is empty string.
    Multi-word names: everything before the first space is first_name,
    everything after (including middle names) is last_name.
    """
    parts = name.strip().split(" ", 1)
    first_name = parts[0]
    last_name = parts[1] if len(parts) > 1 else ""
    return first_name, last_name
