# src/django_core_micha/auth/security.py
import logging
from django.conf import settings

logger = logging.getLogger(__name__)


def get_security_level(request) -> str:
    """
    Returns the current security level for this request.
    """
    if not getattr(request, "user", None) or not request.user.is_authenticated:
        return "anon"
    return request.session.get("auth_level", settings.SECURITY_DEFAULT_LEVEL)


def set_security_level(request, level: str) -> None:
    """
    Stores the security level in the session if the user is authenticated.
    """
    if not getattr(request, "user", None) or not request.user.is_authenticated:
        return
    if level not in settings.SECURITY_LEVELS:
        logger.warning("Attempt to set invalid security level: %s", level)
        return
    request.session["auth_level"] = level


def is_level_sufficient(current: str, required: str) -> bool:
    """
    Compares two levels based on SECURITY_LEVELS order.
    """
    levels = list(settings.SECURITY_LEVELS)
    try:
        return levels.index(current) >= levels.index(required)
    except ValueError:
        return False


def require_security_level(required: str):
    """
    Phase 1/2 version: does not enforce yet, only logs.
    Later we will return 401 + flows if not sufficient.
    """
    def decorator(view_func):
        def _wrapped(request, *args, **kwargs):
            current = get_security_level(request)
            if not is_level_sufficient(current, required):
                logger.info(
                    "Security level too low for view %s: current=%s required=%s",
                    getattr(view_func, "__name__", str(view_func)),
                    current,
                    required,
                )
                # Phase 1/2: do not block, just log
                return view_func(request, *args, **kwargs)
            return view_func(request, *args, **kwargs)
        return _wrapped
    return decorator
