"""
Analytics and tracking middleware for Django application.
"""

import logging

import pghistory
from django.contrib.auth.models import AnonymousUser
from django.core.handlers.wsgi import WSGIRequest

logger = logging.getLogger(__name__)


class RequestContextProvider(pghistory.context):
    """Custom context provider for pghistory that extracts information from the request."""

    def __call__(self, request: WSGIRequest) -> dict:
        return {
            "user": (str(request.user) if request.user and not isinstance(request.user, AnonymousUser) else None),
            "ip": request.META.get("REMOTE_ADDR"),
            "user_agent": request.META.get("HTTP_USER_AGENT"),
            "session_key": (request.session.session_key if hasattr(request, "session") else None),
        }


# Initialize the context provider
request_context = RequestContextProvider()


class PgHistoryContextMiddleware:
    """
    Middleware that ensures request object is available to pghistory context.
    """

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Set the pghistory context with request information
        context_data = request_context(request)
        with pghistory.context(**context_data):
            response = self.get_response(request)
            return response
