import logging
from typing import Any, Callable

from django.db.models import Model
from django.db.models.constants import LOOKUP_SEP
from django_extensions.db.fields import AutoSlugField
from slugify import slugify

logger = logging.getLogger("django")


def unicode_slugify_function(content: Any) -> str:
    return slugify(
        text=str(content),
        allow_unicode=True,
        max_length=88,
        word_boundary=True,
        save_order=True,
        regex_pattern=r"(?:[^\w-]|_)+",
        separator="-",
    )


class TweakedAutoSlugField(AutoSlugField):
    def get_slug_fields(self, model_instance: Model, lookup_value: str | Callable[[Any], Any]) -> str | Model:
        if callable(lookup_value):
            return f"{lookup_value(model_instance)}"

        lookup_value_path = lookup_value.split(LOOKUP_SEP)
        attr = model_instance

        for elem in lookup_value_path:
            try:
                attr: Any = getattr(attr, elem)
            except AttributeError:
                attr: Any = ""
        if callable(attr):
            # noinspection PyCallingNonCallable
            return f"{attr()}"

        return attr
