"""
Request logging middleware for tracking video upload requests.
"""

import logging
import time
import uuid
from django.utils.deprecation import MiddlewareMixin

logger = logging.getLogger('request_middleware')


class RequestLoggingMiddleware(MiddlewareMixin):
    """
    Middleware to log request details for video upload tracking.
    """
    
    def process_request(self, request):
        """Log incoming request details."""
        # Generate unique request ID for tracking
        request.request_id = str(uuid.uuid4())[:8]
        request.start_time = time.time()
        
        # Get user info
        user_id = getattr(request.user, 'id', 'anonymous') if hasattr(request, 'user') else 'unknown'
        
        # Log request details for review endpoints
        if '/reviews/' in request.path:
            logger.info(
                f"Request started - Method: {request.method}, Path: {request.path}, "
                f"User: {user_id}, Request ID: {request.request_id}, "
                f"Content-Type: {request.content_type}, "
                f"Content-Length: {request.META.get('CONTENT_LENGTH', 'unknown')}"
            )
            
            # Log file upload details
            if request.FILES:
                for field_name, file_obj in request.FILES.items():
                    file_size_mb = round(file_obj.size / (1024 * 1024), 2) if hasattr(file_obj, 'size') else 'unknown'
                    logger.info(
                        f"File detected - Field: {field_name}, Name: {file_obj.name}, "
                        f"Size: {file_size_mb}MB, Type: {file_obj.content_type}, "
                        f"User: {user_id}, Request ID: {request.request_id}"
                    )
        
        return None
    
    def process_response(self, request, response):
        """Log response details."""
        if hasattr(request, 'request_id') and '/reviews/' in request.path:
            duration = round(time.time() - request.start_time, 3) if hasattr(request, 'start_time') else 'unknown'
            user_id = getattr(request.user, 'id', 'anonymous') if hasattr(request, 'user') else 'unknown'
            
            logger.info(
                f"Request completed - Status: {response.status_code}, "
                f"Duration: {duration}s, Content-Type: {response.get('Content-Type', 'unknown')}, "
                f"User: {user_id}, Request ID: {request.request_id}"
            )
            
            # Log error responses
            if response.status_code >= 400:
                response_size = len(response.content) if hasattr(response, 'content') else 0
                logger.warning(
                    f"Error response - Status: {response.status_code}, "
                    f"Size: {response_size} bytes, User: {user_id}, Request ID: {request.request_id}"
                )
        
        return response
    
    def process_exception(self, request, exception):
        """Log unhandled exceptions."""
        if hasattr(request, 'request_id'):
            user_id = getattr(request.user, 'id', 'anonymous') if hasattr(request, 'user') else 'unknown'
            logger.error(
                f"Unhandled exception - Type: {exception.__class__.__name__}, "
                f"Message: {str(exception)}, User: {user_id}, Request ID: {request.request_id}",
                exc_info=True
            )
        
        return None