# #region AssistantToolHealthSummary [C:3] [TYPE Module] [SEMANTICS assistant, tool, health, summary]
# @BRIEF Handler for the "get_health_summary" tool — get summary of dashboard health.
# @LAYER API
# @RELATION DEPENDS_ON -> [AssistantToolRegistry]
# @RELATION DEPENDS_ON -> [HealthService]

from __future__ import annotations

from typing import Any

from sqlalchemy.orm import Session

from src.core.config_manager import ConfigManager
from src.core.logger import belief_scope, logger
from src.core.task_manager import TaskManager
from src.schemas.auth import User
from src.services.health_service import HealthService

from ._resolvers import _get_environment_name_by_id, _resolve_env_id
from ._schemas import AssistantAction
from ._tool_registry import assistant_tool


# #region handle_get_health_summary [C:3] [TYPE Function]
@assistant_tool(
    operation="get_health_summary",
    domain="health",
    description="Get summary of dashboard health and failing validations",
    optional_entities=["environment"],
    risk_level="safe",
    requires_confirmation=False,
    permission_checks=[("plugin:migration", "READ")],
)
@belief_scope("get_health_summary")
async def handle_get_health_summary(
    intent: dict[str, Any],
    current_user: User,
    task_manager: TaskManager,
    config_manager: ConfigManager,
    db: Session,
) -> tuple[str, str | None, list[AssistantAction]]:
    """Get summary of dashboard health and failing validations."""
    entities = intent.get("entities", {})
    env_token = entities.get("environment")
    env_id = _resolve_env_id(env_token, config_manager)
    service = HealthService(db)
    summary = await service.get_health_summary(environment_id=env_id)
    env_name = (
        _get_environment_name_by_id(env_id, config_manager)
        if env_id
        else "всех окружений"
    )
    text = (
        f"Сводка здоровья дашбордов для {env_name}:\n"
        f"- ✅ Прошли проверку: {summary.pass_count}\n"
        f"- ⚠️ С предупреждениями: {summary.warn_count}\n"
        f"- ❌ Ошибки валидации: {summary.fail_count}\n"
        f"- ❓ Неизвестно: {summary.unknown_count}"
    )
    actions: list[AssistantAction] = [
        AssistantAction(
            type="open_route", label="Открыть Health Center", target="/dashboards/health"
        )
    ]
    if summary.fail_count > 0:
        text += "\n\nОбнаружены ошибки в следующих дашбордах:"
        for item in summary.items:
            if item.status == "FAIL":
                text += f"\n- {item.dashboard_id} ({item.environment_id}): {item.summary or 'Нет деталей'}"
                actions.append(
                    AssistantAction(
                        type="open_route",
                        label=f"Отчет {item.dashboard_id}",
                        target=f"/reports/llm/{item.task_id}",
                    )
                )
    return (text, None, actions[:5])


# #endregion handle_get_health_summary
# #endregion AssistantToolHealthSummary
