from django.contrib import admin

from ..registry import registry


def create_admin(device_type_cls):
    """Generate and register Django admin classes for a DeviceType's models."""
    device_model = device_type_cls._device_model
    reading_model = device_type_cls._reading_model
    message_model = device_type_cls._message_model
    type_name = device_type_cls.__name__

    # -- Device Admin --
    device_list_display = [
        "name",
        "device_id",
        "status",
        "battery_level",
        "last_seen",
        "is_active",
        "created_at",
    ]
    device_list_display.extend(device_type_cls._state_fields.keys())

    DeviceAdmin = type(
        f"{type_name}DeviceAdmin",
        (admin.ModelAdmin,),
        {
            "list_display": device_list_display,
            "list_filter": ["status", "is_active"],
            "search_fields": ["name", "device_id"],
            "readonly_fields": [
                "mqtt_username",
                "mqtt_password_hash",
                "api_key",
                "last_seen",
                "created_at",
                "updated_at",
            ],
        },
    )

    # -- Reading Admin --
    reading_list_display = ["device", "timestamp"]
    reading_list_display.extend(device_type_cls._readings.keys())

    ReadingAdmin = type(
        f"{type_name}ReadingAdmin",
        (admin.ModelAdmin,),
        {
            "list_display": reading_list_display,
            "list_filter": ["device"],
            "date_hierarchy": "timestamp",
        },
    )

    # -- Message Admin --
    MessageAdmin = type(
        f"{type_name}MessageAdmin",
        (admin.ModelAdmin,),
        {
            "list_display": [
                "device",
                "topic",
                "processing_status",
                "received_at",
            ],
            "list_filter": ["processing_status"],
            "readonly_fields": [
                "device",
                "topic",
                "payload_json",
                "content_type",
                "correlation_id",
                "user_properties",
                "processing_error",
                "received_at",
                "processed_at",
            ],
        },
    )

    admin.site.register(device_model, DeviceAdmin)
    admin.site.register(reading_model, ReadingAdmin)
    admin.site.register(message_model, MessageAdmin)

    return DeviceAdmin, ReadingAdmin, MessageAdmin


def auto_register_admin():
    """Register admin for all device types that have models.

    Call this in your project's admin.py or let AUTO_ADMIN handle it.
    """
    for dt_cls, device_model, _, _ in registry.all_with_models():
        if not admin.site.is_registered(device_model):
            create_admin(dt_cls)
