"""Core health check logic — framework-agnostic."""
from typing import Any, Dict, List, Optional

from fk_utils.health.base import HealthCheck

_HEALTHY = "healthy"


def check_health(
    environment: str,
    country: str,
    version: Optional[str] = None,
    checks: Optional[List[HealthCheck]] = None,
) -> Dict[str, Any]:
    """
    Builds a standardized health check response.

    Each check is optional: pass only the ones relevant to the service.
    Custom checks can be added by subclassing :class:`fk_utils.health.base.HealthCheck`.

    :param environment: Deployment environment (e.g. ``"localhost"``, ``"production"``).
    :param country: Country code (e.g. ``"CO"``, ``"MX"``).
    :param version: Service version string. May be ``None``.
    :param checks: List of :class:`HealthCheck` instances to run.
    :return: Serializable dict with health status and individual check results.

    Example::

        from fk_utils.health import check_health, MongoDBCheck, PostgreSQLCheck

        result = check_health(
            environment="localhost",
            country="CO",
            version="1.1.0",
            checks=[
                MongoDBCheck(mongo_client),
                PostgreSQLCheck(session_factory=get_db),
            ],
        )
    """
    databases: Dict[str, str] = {c.name: c.check() for c in (checks or [])}

    overall = (
        _HEALTHY
        if all(v == _HEALTHY for v in databases.values())
        else "unhealthy"
    )

    return {
        "status": overall,
        "environment": environment,
        "country": country,
        "version": version,
        "databases": databases,
    }
