"""
Management command to view and manage rate limited IPs.
"""
from django.core.management.base import BaseCommand
from django.core.cache import cache
from django.conf import settings
import time


class Command(BaseCommand):
    help = 'Manage rate limited IP addresses'

    def add_arguments(self, parser):
        parser.add_argument(
            '--list-blocked',
            action='store_true',
            help='List all currently blocked IP addresses',
        )
        parser.add_argument(
            '--unblock',
            type=str,
            help='Unblock a specific IP address',
            metavar='IP_ADDRESS'
        )
        parser.add_argument(
            '--block',
            type=str,
            help='Block a specific IP address',
            metavar='IP_ADDRESS'
        )
        parser.add_argument(
            '--clear-all',
            action='store_true',
            help='Clear all rate limiting data (unblock all IPs)',
        )
        parser.add_argument(
            '--stats',
            type=str,
            help='Show request statistics for a specific IP',
            metavar='IP_ADDRESS'
        )

    def handle(self, *args, **options):
        if options['list_blocked']:
            self.list_blocked_ips()
        elif options['unblock']:
            self.unblock_ip(options['unblock'])
        elif options['block']:
            self.block_ip(options['block'])
        elif options['clear_all']:
            self.clear_all_limits()
        elif options['stats']:
            self.show_ip_stats(options['stats'])
        else:
            self.stdout.write(self.style.WARNING('No action specified. Use --help for options.'))

    def get_cache_key(self, ip_address, key_type):
        """Generate cache key for IP address."""
        return f"rate_limit_{key_type}_{ip_address}"

    def list_blocked_ips(self):
        """List all currently blocked IP addresses."""
        self.stdout.write(self.style.SUCCESS('Currently blocked IP addresses:'))
        
        # Note: This is a simplified approach. In production, you might want to
        # maintain a separate list of blocked IPs for easier enumeration
        self.stdout.write('To check if a specific IP is blocked, use: --stats IP_ADDRESS')

    def unblock_ip(self, ip_address):
        """Unblock a specific IP address."""
        block_key = self.get_cache_key(ip_address, "block")
        count_key = self.get_cache_key(ip_address, "count")
        
        # Remove both block and count entries
        cache.delete(block_key)
        cache.delete(count_key)
        
        self.stdout.write(
            self.style.SUCCESS(f'Successfully unblocked IP address: {ip_address}')
        )

    def block_ip(self, ip_address):
        """Block a specific IP address."""
        block_key = self.get_cache_key(ip_address, "block")
        block_duration = getattr(settings, 'RATE_LIMIT_BLOCK_DURATION', 1800)
        
        cache.set(block_key, True, block_duration)
        
        self.stdout.write(
            self.style.WARNING(f'Blocked IP address: {ip_address} for {block_duration} seconds')
        )

    def clear_all_limits(self):
        """Clear all rate limiting data."""
        # This will clear the entire cache, which might affect other cached data
        # In production, consider a more targeted approach
        cache.clear()
        
        self.stdout.write(
            self.style.SUCCESS('Cleared all rate limiting data')
        )

    def show_ip_stats(self, ip_address):
        """Show statistics for a specific IP address."""
        block_key = self.get_cache_key(ip_address, "block")
        count_key = self.get_cache_key(ip_address, "count")
        
        is_blocked = cache.get(block_key, False)
        request_data = cache.get(count_key, None)
        
        self.stdout.write(f'Statistics for IP: {ip_address}')
        self.stdout.write(f'Currently blocked: {"Yes" if is_blocked else "No"}')
        
        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)
            
            self.stdout.write(f'Requests in current window: {count}')
            self.stdout.write(f'Window started: {time.ctime(window_start)}')
            self.stdout.write(f'Time remaining in window: {remaining_time:.0f} seconds')
        else:
            self.stdout.write('No request data found for this IP')