import logging

from django.apps import AppConfig

logger = logging.getLogger(__name__)


class ManagementUiConfig(AppConfig):
    """Configuration for Management UI app."""

    default_auto_field = "django.db.models.BigAutoField"
    name = "management_ui"
    verbose_name = "Admin Extension"

    def ready(self) -> None:
        """
        Perform initialization when Django starts.

        Monkey-patches admin.site.get_app_list to inject Commands section
        into the Django Admin sidebar for superusers.
        """
        self._inject_commands_into_admin_sidebar()

    def _inject_commands_into_admin_sidebar(self) -> None:
        """
        Monkey-patch admin.site.get_app_list to add Commands section.

        Wraps the original get_app_list method to insert a virtual
        "Commands" app at the top of the sidebar for superusers.
        """
        from django.contrib import admin
        from django.urls import reverse
        from functools import wraps

        # Store original method
        original_get_app_list = admin.site.get_app_list

        @wraps(original_get_app_list)
        def custom_get_app_list(request, app_label=None):
            """Extended get_app_list with Commands section."""
            # Call original method with self (admin.site)
            app_list = original_get_app_list(request, app_label)

            # Only show Commands to superusers
            if not request.user.is_superuser:
                return app_list

            # Build Commands virtual app
            try:
                commands_app = {
                    'name': 'Commands',
                    'app_label': 'management_ui_commands',
                    'app_url': reverse('management_ui:command_list'),
                    'models': [
                        {
                            'name': 'Management Commands',
                            'object_name': 'command',
                            'admin_url': reverse('management_ui:command_list'),
                            'view_only': True,
                        }
                    ],
                }

                # Insert at top of list
                app_list.insert(0, commands_app)

            except Exception:
                logger.warning(
                    'Failed to inject Commands section into admin sidebar. '
                    'Check that management_ui URLs are configured in urlpatterns.',
                    exc_info=True,
                )

            return app_list

        # Replace method on admin site instance
        # Note: original_get_app_list is already bound to admin.site, so custom function doesn't need self
        admin.site.get_app_list = custom_get_app_list
