"""
Rate limiting monitoring views for admins.
"""
from django.shortcuts import render
from django.contrib.admin.views.decorators import staff_member_required
from django.http import JsonResponse
from django.core.cache import cache
from django.conf import settings
import time


@staff_member_required
def rate_limit_status(request):
    """
    Display rate limiting status and configuration.
    Only accessible by staff members.
    """
    context = {
        'enabled': getattr(settings, 'RATE_LIMIT_ENABLED', True),
        'requests_limit': getattr(settings, 'RATE_LIMIT_REQUESTS', 100),
        'time_window': getattr(settings, 'RATE_LIMIT_WINDOW', 3600),
        'block_duration': getattr(settings, 'RATE_LIMIT_BLOCK_DURATION', 1800),
        'exempt_paths': getattr(settings, 'RATE_LIMIT_EXEMPT_PATHS', []),
    }
    
    return render(request, 'admin/rate_limit_status.html', context)


@staff_member_required  
def check_ip_status(request):
    """
    API endpoint to check the status of a specific IP address.
    """
    if request.method == 'POST':
        ip_address = request.POST.get('ip_address', '').strip()
        
        if not ip_address:
            return JsonResponse({'error': 'IP address is required'}, status=400)
        
        # Check if IP is blocked
        block_key = f"rate_limit_block_{ip_address}"
        is_blocked = cache.get(block_key, False)
        
        # Get request count data
        count_key = f"rate_limit_count_{ip_address}"
        request_data = cache.get(count_key, None)
        
        response_data = {
            'ip_address': ip_address,
            'is_blocked': is_blocked,
            'request_data': None
        }
        
        if request_data:
            current_time = time.time()
            window_start = request_data['window_start']
            count = request_data['count']
            time_window = getattr(settings, 'RATE_LIMIT_WINDOW', 3600)
            
            time_in_window = current_time - window_start
            remaining_time = max(0, time_window - time_in_window)
            
            response_data['request_data'] = {
                'count': count,
                'window_start': time.ctime(window_start),
                'remaining_time_seconds': int(remaining_time),
                'limit': getattr(settings, 'RATE_LIMIT_REQUESTS', 100)
            }
        
        return JsonResponse(response_data)
    
    return JsonResponse({'error': 'POST method required'}, status=405)


@staff_member_required
def unblock_ip(request):
    """
    API endpoint to unblock a specific IP address.
    """
    if request.method == 'POST':
        ip_address = request.POST.get('ip_address', '').strip()
        
        if not ip_address:
            return JsonResponse({'error': 'IP address is required'}, status=400)
        
        # Remove block and count entries
        block_key = f"rate_limit_block_{ip_address}"
        count_key = f"rate_limit_count_{ip_address}"
        
        cache.delete(block_key)
        cache.delete(count_key)
        
        return JsonResponse({
            'success': True,
            'message': f'Successfully unblocked IP: {ip_address}'
        })
    
    return JsonResponse({'error': 'POST method required'}, status=405)