"""Middleware module health endpoint helpers.

This file is generated by RapidKit's middleware module.
"""

from __future__ import annotations

import logging
import time
from datetime import datetime, timezone

from typing import Any, Dict

from fastapi import APIRouter, FastAPI, status
from fastapi.responses import JSONResponse

router = APIRouter(prefix="/api/health/module", tags=["health"])
logger = logging.getLogger("middleware.health")

_START_MONOTONIC = time.monotonic()

_MIDDLEWARE_COUNT = 3  # ProcessTime, ServiceHeader, CustomHeader


def _build_payload() -> Dict[str, Any]:
    return {
        "status": "ok",
        "module": "{{ rapidkit_vendor_module }}",
        "version": "{{ rapidkit_vendor_version }}",
        "uptime": max(0.0, time.monotonic() - _START_MONOTONIC),
        "module_version": "{{ rapidkit_vendor_version }}",
        "middleware_count": _MIDDLEWARE_COUNT,
        "checked_at": datetime.now(timezone.utc).isoformat(),
    }


@router.get(
    "/middleware",
    summary="Middleware module health check",
    status_code=status.HTTP_200_OK,
    responses={
        status.HTTP_503_SERVICE_UNAVAILABLE: {
            "description": "Middleware subsystem unavailable",
        }
    },
)
async def middleware_health_check() -> Any:
    """Return basic health information for the generated middleware module."""
    try:
        payload = _build_payload()
    except Exception as exc:  # pragma: no cover - defensive guard
        message = str(exc) or "middleware health check failed"
        logger.exception("Middleware health check failed")
        return JSONResponse(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            content={
                "status": "error",
                "module": "{{ rapidkit_vendor_module }}",
                "detail": message,
            },
        )

    logger.debug("Middleware health endpoint invoked", extra={"payload": payload})
    return payload


def register_middleware_health(app: FastAPI) -> None:
    """Attach the middleware health router to the provided FastAPI application."""
    app.include_router(router)


__all__ = ["middleware_health_check", "register_middleware_health", "router"]
