from django.contrib import admin
from django.contrib.admin.apps import AdminConfig


class ReadOnlyAdmin(admin.ModelAdmin):
    """Generic read-only admin for system tables."""

    def has_add_permission(self, request):
        return False

    def has_change_permission(self, request, obj=None):
        return False

    def has_delete_permission(self, request, obj=None):
        return False


def _safe_register(model, model_admin):
    try:
        admin.site.register(model, model_admin)
    except admin.sites.AlreadyRegistered:
        pass


class Igny8AdminConfig(AdminConfig):
    default_site = 'igny8_core.admin.site.Igny8AdminSite'
    name = 'django.contrib.admin'

    def ready(self):
        super().ready()
        
        # Replace default admin.site with our custom Igny8AdminSite
        # IMPORTANT: Must copy all registrations from old site to new site
        # because models register themselves before ready() is called
        from igny8_core.admin.site import admin_site
        import django.contrib.admin as admin_module
        
        # Copy all model registrations from the default site to our custom site
        old_site = admin_module.site
        admin_site._registry = old_site._registry.copy()
        admin_site._actions = old_site._actions.copy()
        admin_site._global_actions = old_site._global_actions.copy()
        
        # Now replace the default site
        admin_module.site = admin_site
        admin_module.sites.site = admin_site
        
        # Import Unfold AFTER apps are ready
        from unfold.admin import ModelAdmin as UnfoldModelAdmin
        
        # Register Django internals in admin (read-only where appropriate)
        from django.contrib.admin.models import LogEntry
        from django.contrib.auth.models import Group, Permission
        from django.contrib.contenttypes.models import ContentType
        from django.contrib.sessions.models import Session

        _safe_register(LogEntry, ReadOnlyAdmin)
        _safe_register(Permission, UnfoldModelAdmin)
        _safe_register(Group, UnfoldModelAdmin)
        _safe_register(ContentType, ReadOnlyAdmin)
        _safe_register(Session, ReadOnlyAdmin)
        
        # Import and setup enhanced Celery task monitoring
        self._setup_celery_admin()
    
    def _setup_celery_admin(self):
        """Setup enhanced Celery admin with proper unregister/register"""
        try:
            from django_celery_results.models import TaskResult, GroupResult
            from igny8_core.admin.celery_admin import CeleryTaskResultAdmin, CeleryGroupResultAdmin
            
            # Unregister the default TaskResult admin
            try:
                admin.site.unregister(TaskResult)
            except admin.sites.NotRegistered:
                pass
            
            # Unregister the default GroupResult admin
            try:
                admin.site.unregister(GroupResult)
            except admin.sites.NotRegistered:
                pass
            
            # Register our enhanced versions
            admin.site.register(TaskResult, CeleryTaskResultAdmin)
            admin.site.register(GroupResult, CeleryGroupResultAdmin)
        except Exception as e:
            # Log the error but don't crash the app
            import logging
            logger = logging.getLogger(__name__)
            logger.warning(f"Could not setup enhanced Celery admin: {e}")


