import platform
from typing import Dict

from django.db import connections, DatabaseError
from django.utils import timezone
from django.utils.version import get_version
from rest_framework.response import Response
from rest_framework.views import APIView


class HealthCheckView(APIView):
    """
    简单健康检查接口，返回当前服务的基础指标信息，包括：
    - 应用版本
    - Python/Django 版本
    - 服务器时间
    - 数据库连接状态
    """

    authentication_classes: list = []
    permission_classes: list = []

    def get(self, request):
        db_status: Dict[str, str] = {}
        for alias in connections:
            try:
                connections[alias].cursor()
                db_status[alias] = 'ok'
            except DatabaseError as exc:
                db_status[alias] = f'error: {exc.__class__.__name__}'

        payload = {
            'service': 'flower-api',
            'status': 'ok' if all(status == 'ok' for status in db_status.values()) else 'degraded',
            'server_time': timezone.now().isoformat(),
            'python_version': platform.python_version(),
            'django_version': get_version(),
            'platform': platform.platform(),
            'databases': db_status,
        }
        return Response(payload)

