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

from __future__ import annotations

import time
from typing import Any, Dict

from database.{{ module_name }} import {{ module_class_name }}, DbMongoDependencyError
from types.db_mongo import (
    MongoClusterMetrics,
    MongoHealthReport,
    MongoReplicaState,
    build_health_report,
)


async def _collect_replica_status(runtime: {{ module_class_name }}) -> MongoReplicaState:
    try:
        client = runtime.client
        previous_command = getattr(client, "last_command", None)
        try:
            status = await client.get_database("admin").command({"replSetGetStatus": 1})
        finally:
            if getattr(client, "last_command", None) is not None:
                client.last_command = previous_command
    except Exception:  # noqa: BLE001 - replica sets are optional
        return MongoReplicaState()

    members = []
    for entry in status.get("members", []):
        name = entry.get("name")
        if name:
            members.append(str(name))
    return MongoReplicaState(
        set_name=status.get("set"),
        primary=status.get("primary"),
        members=tuple(members),
    )


async def perform_health_check(
    runtime: {{ module_class_name }},
    *,
    timeout_ms: int,
    collect_metrics: bool = True,
) -> MongoHealthReport:
    errors: list[str] = []
    metrics_payload: Dict[str, Any] = {}
    extra: Dict[str, Any] = {}
    server_version: str | None = None
    status = "ok"
    detail = "ok"

    started = time.perf_counter()
    try:
        await runtime.ping(timeout_ms=timeout_ms)
    except DbMongoDependencyError as exc:
        status = "critical"
        detail = "motor missing"
        errors.append(str(exc))
    except Exception as exc:  # noqa: BLE001 - propagate as degraded health
        status = "degraded"
        detail = f"ping failed: {exc}"
        errors.append(str(exc))
    else:
        metrics_payload["latency_ms"] = (time.perf_counter() - started) * 1000.0

    if collect_metrics:
        try:
            info = await runtime.server_info()
            server_version = str(info.get("version", "unknown"))
            metrics_payload.setdefault("connections", info.get("connections", {}))
            metrics_payload.setdefault("opcounters", info.get("opcounters", {}))
            metrics_payload.setdefault("storage", info.get("wiredTiger", {}))
            extra.update(
                {
                    "process": info.get("process"),
                    "max_wire_version": info.get("maxWireVersion"),
                    "git_version": info.get("gitVersion"),
                }
            )
        except Exception as exc:  # noqa: BLE001 - metrics are best effort
            errors.append(f"server_info: {exc}")

        replica_state = await _collect_replica_status(runtime)
    else:
        replica_state = MongoReplicaState()

    metrics = MongoClusterMetrics(
        latency_ms=float(metrics_payload.get("latency_ms", 0.0)),
        connections=dict(metrics_payload.get("connections", {})),
        opcounters=dict(metrics_payload.get("opcounters", {})),
        storage=dict(metrics_payload.get("storage", {})),
    )

    report = build_health_report(
        status=status,
        detail=detail,
        metrics={
            "latency_ms": metrics.latency_ms,
            "connections": metrics.connections,
            "opcounters": metrics.opcounters,
            "storage": metrics.storage,
        },
        replica={
            "set_name": replica_state.set_name,
            "primary": replica_state.primary,
            "members": replica_state.members,
        },
        server_version=server_version,
        extra=extra,
        errors=errors,
    )
    return report


__all__ = ["perform_health_check"]
