from typing import Any

from django import template
from django.contrib.contenttypes.models import ContentType

register = template.Library()


@register.filter
def get_object_name(value: int | None, model_path: str) -> str | None:
    """Get object name from ID and model path."""
    if not value or not model_path or "." not in model_path:
        return None

    app_label, model = model_path.split(".")
    try:
        content_type = ContentType.objects.get(app_label=app_label.lower(), model=model.lower())
        model_class = content_type.model_class()
        if not model_class:
            return None

        obj = model_class.objects.filter(id=value).first()
        return str(obj) if obj else None
    except Exception:
        return None


@register.filter
def get_category_display(value: str | None) -> str | None:
    """Get display value for ride category."""
    if not value:
        return None

    categories = {
        "RC": "Roller Coaster",
        "DR": "Dark Ride",
        "FR": "Flat Ride",
        "WR": "Water Ride",
        "TR": "Transport",
        "OT": "Other",
    }
    return categories.get(value)


@register.filter
def get_park_area_name(value: int | None, park_id: int | None) -> str | None:
    """Get park area name from ID and park ID."""
    if not value or not park_id:
        return None

    try:
        from apps.parks.models import ParkArea

        area = ParkArea.objects.filter(id=value, park_id=park_id).first()
        return str(area) if area else None
    except Exception:
        return None


@register.filter
def get_item(dictionary: dict[str, Any] | None, key: str | int | None) -> list[Any]:
    """Get item from dictionary by key."""
    if not dictionary or not isinstance(dictionary, dict) or not key:
        return []

    return dictionary.get(str(key), [])
