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.
    """
    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

    parts = [p for p in d.split(".") if p]
    if not parts:
        return d
    # Handle common multi-part TLDs
    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
