"""The shared /health endpoint. Pure liveness by default; a service can wire a deep-check
(settings.SVC_HEALTHCHECK = "module.path:callable" returning truthy when healthy — e.g. a real
DB SELECT 1, as uuid_service and pdf_feed do) so the Docker/systemd healthcheck exercises the
real dependency, not just process-up."""
import logging
from importlib import import_module

from django.conf import settings
from drf_spectacular.utils import extend_schema
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from .serializers import HealthSerializer

log = logging.getLogger("andrea_svc_web")


def _run_check() -> bool:
    dotted = getattr(settings, "SVC_HEALTHCHECK", None)
    if not dotted:
        return True
    mod_path, _, fn_name = str(dotted).partition(":")
    fn = getattr(import_module(mod_path), fn_name)
    return bool(fn())


class HealthView(APIView):
    """GET /health — 200 {status:ok} when healthy, 503 {status:degraded} otherwise. Always
    unauthenticated (a healthcheck must not need a credential)."""

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

    @extend_schema(operation_id="health", summary="Health check", responses={200: HealthSerializer})
    def get(self, request):
        try:
            ok = _run_check()
        except Exception:                                    # noqa: BLE001 — a failing dep is "degraded", not a 500
            log.exception("health deep-check raised")
            ok = False
        name = getattr(settings, "SERVICE_NAME", "andrea-service")
        return Response(
            {"status": "ok" if ok else "degraded", "service": name},
            status=status.HTTP_200_OK if ok else status.HTTP_503_SERVICE_UNAVAILABLE,
        )
