"""Runtime controls: hot reload of the toolset and the LLM health reset."""

from typing import Annotated

from fastapi import Depends

from navi.api.deps import require_admin
from navi.auth import User

from ._router import router
from .common import log


@router.post("/ollama/clear-blacklists", status_code=204)
async def admin_clear_ollama_blacklists(
    user: Annotated[User, Depends(require_admin)],
) -> None:
    """Forget recorded LLM target failures and restart every route at its primary.

    The old endpoint cleared blacklists. The state now also holds cooling
    (quota/5xx) and auth flags, so the same button means "re-check everything
    now" — useful after fixing a key or bringing a host back by hand.
    """
    from navi.api.deps import _resolve_container

    backend = getattr(_resolve_container(), "llm_backend", None)
    reset = getattr(backend, "reset_health", None)
    if callable(reset):
        reset()
    log.info("admin.ollama_health_reset", admin_id=user.id)


@router.post("/tools/reload")
async def admin_reload_tools(
    user: Annotated[User, Depends(require_admin)],
) -> dict:
    """Hot-reload user tools, context providers and MCP servers.

    Same work as the ``reload_tools`` built-in, for admins whose profile does
    not carry that tool — one ``reload_all``, so a reload from here and one from
    the tool cannot leave different toolsets behind.
    """
    from navi.api.deps import get_cp_registry, get_mcp_manager, get_tool_registry
    from navi.core.reload import reload_all

    report = await reload_all(get_tool_registry(), get_cp_registry(), get_mcp_manager())
    log.info("admin.tools_reloaded", admin_id=user.id, ok=report.ok, tools=len(report.tools))
    return report.as_dict()
