from django.core.management.base import BaseCommand
from django.utils import timezone
import json


class Command(BaseCommand):
    """
    查看请求日志的管理命令
    在实际项目中，您可能需要将日志存储到数据库或文件中
    """

    help = '显示最近的请求日志信息'

    def add_arguments(self, parser):
        parser.add_argument(
            '--limit',
            type=int,
            default=10,
            help='显示的日志条目数量限制 (默认: 10)',
        )
        parser.add_argument(
            '--method',
            type=str,
            help='按HTTP方法过滤 (GET, POST, PUT, DELETE等)',
        )
        parser.add_argument(
            '--status',
            type=int,
            help='按状态码过滤',
        )

    def handle(self, *args, **options):
        limit = options['limit']
        method_filter = options['method']
        status_filter = options['status']

        self.stdout.write(
            self.style.SUCCESS(f'=== 最近 {limit} 条请求日志 ===')
        )

        # 注意：在实际项目中，这里应该从数据库或日志文件中读取数据
        # 这里只是一个示例实现
        self.stdout.write(
            self.style.WARNING('注意: 当前日志仅显示在控制台，重启后丢失。')
        )
        self.stdout.write(
            self.style.WARNING('在生产环境中，建议配置日志系统将日志保存到文件或数据库。')
        )

        # 示例日志条目
        sample_logs = [
            {
                'timestamp': timezone.now().isoformat(),
                'method': 'GET',
                'path': '/admin/',
                'status_code': 200,
                'duration': 0.145,
                'ip_address': '127.0.0.1',
            },
            {
                'timestamp': timezone.now().isoformat(),
                'method': 'POST',
                'path': '/api/auth/login/',
                'status_code': 200,
                'duration': 0.234,
                'ip_address': '127.0.0.1',
            }
        ]

        for log in sample_logs[:limit]:
            # 应用过滤器
            if method_filter and log['method'] != method_filter.upper():
                continue
            if status_filter and log['status_code'] != status_filter:
                continue

            # 格式化输出
            self.stdout.write(
                f"{log['timestamp']} "
                f"{self._format_method(log['method'])} "
                f"{self._format_path(log['path'])} "
                f"{self._format_status(log['status_code'])} "
                f"{self._format_duration(log['duration'])} "
                f"{log['ip_address']}"
            )

    def _format_method(self, method):
        """格式化HTTP方法"""
        colors = {
            'GET': self.style.HTTP_SUCCESS,  # 绿色
            'POST': self.style.HTTP_INFO,  # 蓝色
            'PUT': self.style.HTTP_NOT_MODIFIED,  # 橙色
            'DELETE': self.style.HTTP_BAD_REQUEST,  # 红色
        }
        color = colors.get(method, self.style.HTTP_SUCCESS)
        return color(method.ljust(6))

    def _format_path(self, path):
        """格式化路径"""
        return self.style.SQL_FIELD(path)

    def _format_status(self, status_code):
        """格式化状态码"""
        if 200 <= status_code < 300:
            return self.style.HTTP_SUCCESS(str(status_code))
        elif 300 <= status_code < 400:
            return self.style.HTTP_NOT_MODIFIED(str(status_code))
        elif 400 <= status_code < 500:
            return self.style.HTTP_BAD_REQUEST(str(status_code))
        else:
            return self.style.HTTP_SERVER_ERROR(str(status_code))

    def _format_duration(self, duration):
        """格式化持续时间"""
        if duration < 0.1:
            return self.style.SUCCESS(f"{duration * 1000:.1f}ms")
        elif duration < 1:
            return self.style.WARNING(f"{duration * 1000:.1f}ms")
        else:
            return self.style.ERROR(f"{duration:.2f}s")