from django.conf import settings
from django.db import DatabaseError, connections, transaction
from django.http import JsonResponse
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_safe


@never_cache
@require_safe
def health(request):
    """Liveness only: the process is running and able to answer.

    Deliberately touches no database, configuration or filesystem so a liveness
    probe never depends on a dependency and never discloses infrastructure.
    """
    return JsonResponse({"status": "ok"})


@never_cache
@require_safe
def ready(request):
    """Readiness: the process can serve authenticated traffic.

    Confirms the database is reachable using one bounded read inside a
    transaction-local statement timeout. It writes nothing, reads no business
    data and reports only a coarse status; connection strings, database names,
    hostnames and driver detail are never returned.
    """
    timeout = getattr(settings, "READY_STATEMENT_TIMEOUT_MS", 2000)
    try:
        with transaction.atomic():
            with connections["default"].cursor() as cursor:
                cursor.execute("SET LOCAL statement_timeout = %s", [timeout])
                cursor.execute("SELECT 1")
                cursor.fetchone()
    except DatabaseError:
        return JsonResponse({"status": "not_ready"}, status=503)
    return JsonResponse({"status": "ready"})