"""Shared admin registration helpers."""

from django.apps import apps as django_apps
from django.contrib import admin
from django.contrib.admin.sites import AlreadyRegistered

# Sensible defaults: most models have name/title/code; show created_at/updated_at if present.
SEARCH_CANDIDATES = ("name", "title", "subject", "email", "code", "slug", "username")
LIST_DISPLAY_PRIORITY = ("id", "name", "title", "subject", "email", "status", "created_at")
LIST_FILTER_CANDIDATES = ("status", "is_active", "type", "category", "created_at")


def _fields(model):
    return [f for f in model._meta.concrete_fields if not f.many_to_many]


def _list_display(model):
    names = {f.name for f in _fields(model)}
    chosen = [n for n in LIST_DISPLAY_PRIORITY if n in names]
    if not chosen:
        chosen = [f.name for f in _fields(model)[:4] if f.name != "password"]
    if "id" not in chosen:
        chosen = ["id"] + chosen
    return tuple(chosen[:6])


def _search_fields(model):
    names = {f.name for f in _fields(model)}
    return tuple(n for n in SEARCH_CANDIDATES if n in names)


def _list_filter(model):
    names = {f.name for f in _fields(model)}
    return tuple(n for n in LIST_FILTER_CANDIDATES if n in names)


def register_app_models(app_label, exclude=()):
    """Register every concrete model in app with a generic ModelAdmin.

    Skips models already registered (e.g. User registered manually with UserAdmin).
    Pass `exclude` as iterable of model class names to skip.
    """
    for model in django_apps.get_app_config(app_label).get_models():
        if model.__name__ in exclude or admin.site.is_registered(model):
            continue
        attrs = {
            "list_display": _list_display(model),
            "search_fields": _search_fields(model),
            "list_filter": _list_filter(model),
        }
        admin_cls = type(f"{model.__name__}Admin", (admin.ModelAdmin,), attrs)
        try:
            admin.site.register(model, admin_cls)
        except AlreadyRegistered:
            pass
