"""Registrable root extraction using Public Suffix List.

Provides domain root extraction with optional publicsuffix2 support
and a fallback heuristic for when the library is not installed.
"""

from __future__ import annotations

from functools import lru_cache


@lru_cache(maxsize=10000)
def registrable_root(domain: str) -> str:
    """Return the registrable root of a domain using publicsuffix2 if available.

    Falls back to a simple heuristic (last two labels, or .co.uk style) when the
    library is not present. Always returns lowercase.

    Args:
        domain: The domain to extract the root from (e.g., "www.example.co.uk")

    Returns:
        The registrable root (e.g., "example.co.uk")

    Examples:
        >>> registrable_root("www.google.com")
        'google.com'
        >>> registrable_root("mail.example.co.uk")
        'example.co.uk'
        >>> registrable_root("")
        ''
    """
    d = (domain or "").strip().lower()
    if not d:
        return ""

    try:
        # publicsuffix2 is lightweight; only used if installed
        from publicsuffix2 import get_sld

        root = get_sld(d)
        if root:
            return root.lower()
    except Exception:
        pass

    # Fallback heuristic
    parts = [p for p in d.split(".") if p]
    if not parts:
        return d

    # Handle common multi-part TLDs (e.g., .co.uk, .com.au)
    if (
        len(parts) >= 3
        and parts[-2] in {"co", "com", "org", "net"}
        and len(parts[-1]) == 2
    ):
        return ".".join(parts[-3:])

    if len(parts) >= 2:
        return ".".join(parts[-2:])

    return d
