from django.core.cache import cache
from django.http import JsonResponse
from functools import wraps
import hashlib


def rate_limit_otp(max_requests=5, window_minutes=15):
    """
    Rate limiting decorator for OTP endpoints
    Limits requests per IP address
    """
    def decorator(view_func):
        @wraps(view_func)
        def wrapper(*args, **kwargs):
            # Support both function-based views and class-based view methods.
            # For CBVs, args are typically (self, request, ...); for FBVs, (request, ...).
            request = None
            if args:
                if hasattr(args[0], "META"):
                    request = args[0]
                elif len(args) > 1 and hasattr(args[1], "META"):
                    request = args[1]

            # If request cannot be resolved, skip rate-limiting rather than crashing.
            if request is None:
                return view_func(*args, **kwargs)

            # Get client IP
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]
            else:
                ip = request.META.get('REMOTE_ADDR')
            
            # Create cache key
            cache_key = f"otp_rate_limit_{hashlib.md5(ip.encode()).hexdigest()}"
            
            # Get current request count
            current_requests = cache.get(cache_key, 0)
            
            if current_requests >= max_requests:
                return JsonResponse({
                    'status': False,
                    'message': 'Too many OTP requests. Please try again later.'
                }, status=429)
            
            # Increment counter
            cache.set(cache_key, current_requests + 1, window_minutes * 60)
            
            return view_func(*args, **kwargs)
        return wrapper
    return decorator
