"""
Configuration reader for management_ui settings.
"""

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured


def get_allowed_commands() -> frozenset[str] | None:
    """
    Return set of allowed command names, or None if all commands allowed.

    Reads MANAGEMENT_UI["COMMANDS"] from Django settings.
    - Returns frozenset[str] if COMMANDS key exists (allowlist active)
    - Returns None if COMMANDS key absent (no filtering, all allowed)

    Empty list [] in settings returns empty frozenset (nothing allowed).

    Returns:
        frozenset[str] | None: Set of allowed command names, or None for no filter.

    Example settings.py:
        # Production - explicit allowlist
        MANAGEMENT_UI = {
            "COMMANDS": ["migrate", "collectstatic", "clearsessions"],
        }

        # Development - all commands allowed
        MANAGEMENT_UI = {}  # or omit entirely
    """
    management_ui_conf: dict = getattr(settings, 'MANAGEMENT_UI', {})

    # Check if COMMANDS key exists (not just if it's truthy)
    if 'COMMANDS' not in management_ui_conf:
        return None

    allowed = management_ui_conf['COMMANDS']

    # Validate COMMANDS value type
    if not isinstance(allowed, (list, tuple)):
        raise ImproperlyConfigured(
            f"MANAGEMENT_UI['COMMANDS'] must be a list or tuple of strings, "
            f"got {type(allowed).__name__}: {allowed!r}"
        )

    return frozenset(allowed)


def is_command_allowed(command_name: str) -> bool:
    """
    Check if command is allowed in current configuration.

    Args:
        command_name: Django management command name

    Returns:
        True if command should be visible/executable, False otherwise

    Logic:
        - If get_allowed_commands() returns None: allow all (development mode)
        - Otherwise: check if command_name in allowlist
    """
    allowed = get_allowed_commands()

    # No filter active - all commands allowed
    if allowed is None:
        return True

    # Filter active - check membership
    return command_name in allowed
