"""Settings module health endpoint helpers.

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

from __future__ import annotations

import logging
import time
from datetime import datetime, timezone
from typing import Any, Dict

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

from src.modules.free.essentials.settings.settings import Settings, get_settings
from src.modules.free.essentials.settings.settings_types import SettingsSnapshot, as_dict

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

_START_MONOTONIC = time.monotonic()


def _resolve_settings() -> Settings:
    return get_settings()


def _build_payload(snapshot: SettingsSnapshot) -> Dict[str, Any]:
    payload = as_dict(snapshot)
    payload.update(
        {
            # Strict health contract fields (required by stabilization runner).
            "module": "{{ rapidkit_vendor_module }}",
            "version": "{{ rapidkit_vendor_version }}",
            "uptime": max(0.0, time.monotonic() - _START_MONOTONIC),
            "status": "ok",
            "checked_at": datetime.now(timezone.utc).isoformat(),
            "checks": {
                "secret_placeholder": snapshot.metadata.get("vault_url") is not None,
            },
        }
    )
    payload["module_version"] = "{{ rapidkit_vendor_version }}"
    return payload


@router.get(
    "/settings",
    summary="Settings module health check",
    status_code=status.HTTP_200_OK,
    responses={
        status.HTTP_503_SERVICE_UNAVAILABLE: {
            "description": "Settings subsystem unavailable",
        }
    },
)
async def settings_health_check(settings: Settings = Depends(_resolve_settings)) -> Any:
    """Return detailed health information for the generated settings module."""

    try:
        snapshot = SettingsSnapshot.from_settings(settings)
        payload = _build_payload(snapshot)
    except Exception as exc:  # pragma: no cover - defensive guard
        message = str(exc) or "settings health check failed"
        logger.exception("Settings health check failed")
        return JSONResponse(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            content={
                "status": "error",
                "module": "{{ rapidkit_vendor_module }}",
                "detail": message,
            },
        )

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


def register_settings_health(app: FastAPI) -> None:
    """Attach the settings health router to the provided FastAPI application."""

    app.include_router(router)


__all__ = ["register_settings_health", "settings_health_check", "router"]
