from __future__ import annotations

from importlib import import_module


def patch_inference_executor_is_alive() -> bool:
    """
    Guard LiveKit's health check against a closed multiprocessing.Process.

    livekit-agents==1.3.10 calls InferenceProcExecutor.is_alive() from the
    aiohttp health route. After shutdown, multiprocessing raises
    ValueError("process object is closed"), which turns a normal unhealthy
    state into a 500.
    """

    try:
        module = import_module("livekit.agents.ipc.inference_proc_executor")
    except ImportError:
        return False

    executor_cls = getattr(module, "InferenceProcExecutor", None)
    if executor_cls is None:
        return False

    current_is_alive = getattr(executor_cls, "is_alive", None)
    if current_is_alive is None:
        return False

    if getattr(current_is_alive, "__tim_closed_process_guard__", False):
        return False

    def _safe_is_alive(self) -> bool:
        try:
            return current_is_alive(self)
        except ValueError as exc:
            if str(exc) != "process object is closed":
                raise
            return False

    _safe_is_alive.__tim_closed_process_guard__ = True
    executor_cls.is_alive = _safe_is_alive
    return True
