"""Health helpers for the {{ module_title }} runtime."""

from __future__ import annotations

import sys
from types import ModuleType
from typing import Any, Mapping

try:
    from fastapi import APIRouter, FastAPI
except ImportError:  # pragma: no cover - FastAPI optional during template checks
    APIRouter = None  # type: ignore[assignment]
    FastAPI = None  # type: ignore[assignment]


def _resolve_runtime() -> tuple[type[Any], type[Any]]:
    try:
        from src.modules.free.ai.ai_assistant.ai_assistant import {{ module_class_name }}, {{ module_class_name }}Config

        return {{ module_class_name }}, {{ module_class_name }}Config
    except Exception:
        pass

    runtime_module: ModuleType | None = next(
        (
            module
            for module in reversed(list(sys.modules.values()))
            if isinstance(module, ModuleType)
            and hasattr(module, "{{ module_class_name }}")
            and hasattr(module, "{{ module_class_name }}Config")
        ),
        None,
    )
    if runtime_module is None:  # pragma: no cover - defensive guard
        raise RuntimeError("{{ module_class_name }} runtime is unavailable")

    assistant_cls = getattr(runtime_module, "{{ module_class_name }}")
    config_cls = getattr(runtime_module, "{{ module_class_name }}Config")
    return assistant_cls, config_cls


def check_health(
    config: Any | None = None,
    *,
    context: Mapping[str, Any] | None = None,
) -> Mapping[str, Any]:
    """Return a detailed health payload for the assistant runtime."""

    assistant_cls, config_cls = _resolve_runtime()
    assistant = assistant_cls(config or config_cls())
    report = assistant.health_report()

    if context:
        enriched = dict(report)
        enriched.setdefault("metadata", {}).update(dict(context))
        return enriched
    return report


if APIRouter is not None:
    router = APIRouter(prefix="/api/health/module", tags=["health"])

    @router.get("/ai-assistant", summary="Ai Assistant module health check")
    async def ai_assistant_health_check() -> Mapping[str, Any]:
        return check_health()

else:  # pragma: no cover - FastAPI optional during linting-only flows
    router = None


def register_ai_assistant_health(app: Any) -> None:
    if FastAPI is not None and not isinstance(app, FastAPI):
        raise TypeError("register_ai_assistant_health expects a FastAPI application instance")
    if router is None:
        raise RuntimeError("FastAPI must be installed to register ai_assistant health routes")
    app.include_router(router)


__all__ = ["check_health", "register_ai_assistant_health", "router"]
