from collections.abc import Callable
from importlib import import_module

from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpRequest

USE_KEYCLOAK = getattr(settings, "USE_KEYCLOAK", False)


KEYCLOAK_POST_LOGOUT_URL = getattr(settings, "KEYCLOAK_POST_LOGOUT_URL", None)
REALM_NAME = getattr(settings, "REALM_NAME", None)
CLIENT_ID = getattr(settings, "CLIENT_ID", None)
KEYCLOAK_URL_BASE_CLIENT = getattr(settings, "KEYCLOAK_URL_BASE_CLIENT", None)
KEYCLOAK_SCOPES = getattr(settings, "KEYCLOAK_SCOPES", None)
KEYCLOAK_REDIRECT_URI = getattr(settings, "KEYCLOAK_REDIRECT_URI", None)
CLIENT_SECRET = getattr(settings, "CLIENT_SECRET", None)
KEYCLOAK_URL_BASE = getattr(settings, "KEYCLOAK_URL_BASE", None)
KEYCLOAK_AUDIENCE = getattr(settings, "KEYCLOAK_AUDIENCE", None)
KEYCLOAK_IS_CREATE = getattr(settings, "KEYCLOAK_IS_CREATE", True)
KEYCLOAK_CERT_FILENAME = getattr(settings, "KEYCLOAK_CERT_FILENAME", "/home/sdl/cert/host.pem")
AUTH_PAGE_DOCUMENT = getattr(settings, "AUTH_PAGE_DOCUMENT", None)
ERROR_PAGE_DOCUMENT = getattr(settings, "ERROR_PAGE_DOCUMENT", None)

VERSION_TAG = getattr(settings, "VERSION_TAG", None)

DEFAULT_REDIRECT_URI = getattr(settings, "DEFAULT_REDIRECT_URI", "/")

DEFAULT_REQUEST_TIMEOUT = 60


def get_cache_callback() -> Callable[[HttpRequest], str] | None:
    path = getattr(settings, "CACHE_CALLBACK", None)
    if path is None:
        return None
    module_name, func_name = path.rsplit(".", 1)
    module = import_module(module_name)
    return getattr(module, func_name)


def get_clear_cache_callback() -> Callable[[User], None] | None:
    path = getattr(settings, "CLEAR_CACHE_CALLBACK", None)
    if path is None:
        return None
    module_name, func_name = path.rsplit(".", 1)
    module = import_module(module_name)
    return getattr(module, func_name)


CACHE_CALLBACK = get_cache_callback()
CLEAR_CACHE_CALLBACK = get_clear_cache_callback()


if USE_KEYCLOAK and not (
    CLIENT_ID is not None
    and CLIENT_SECRET is not None
    and REALM_NAME is not None
    and KEYCLOAK_URL_BASE is not None
    and KEYCLOAK_POST_LOGOUT_URL is not None
    and KEYCLOAK_REDIRECT_URI is not None
    and KEYCLOAK_IS_CREATE is not None
):
    msg = """Не удалось найти параметры KEYCLOAK_CLIENT_ID, KEYCLOAK_CLIENT_SECRET, KEYCLOAK_REALM_NAME, \
        KEYCLOAK_URL_BASE, KEYCLOAK_POST_LOGOUT_URL в настройках приложения"""  # noqa: RUF001
    raise ImproperlyConfigured(msg)
