"""工具健康检查"""

from __future__ import annotations

import logging

import httpx

from tool_agent.router.status import ToolStatusManager, ProcessState

logger = logging.getLogger(__name__)


class HealthChecker:
    """定期检查工具状态"""

    def __init__(self, status_manager: ToolStatusManager) -> None:
        self._status_manager = status_manager

    async def check(self, tool_id: str) -> bool:
        """检查单个工具健康状态"""
        endpoint = self._status_manager.get_active_endpoint(tool_id)
        if not endpoint:
            return False
        try:
            url = endpoint["url"].rsplit("/", 1)[0] + "/health"
            async with httpx.AsyncClient(timeout=5) as client:
                resp = await client.get(url)
                return resp.status_code == 200
        except Exception:
            return False

    async def check_all(self) -> dict[str, bool]:
        """批量健康检查"""
        results = {}
        for route in self._status_manager.list_status():
            if route.state == ProcessState.RUNNING:
                results[route.tool_id] = await self.check(route.tool_id)
        return results
