"""Tools for the agent.

Define the tools (functions) that this agent can use.
Each tool should be decorated with @tool and have a clear docstring.

This agent uses MACSDK's API tools to interact with a mock DevOps API.
The API is hosted at my-json-server.typicode.com for demonstration.

Replace the API service registration with your own API to customize.
"""

from __future__ import annotations

from langchain_core.tools import tool

# =============================================================================
# SERVICE REGISTRATION (lazy initialization)
# =============================================================================

_api_registered = False


def _ensure_api_registered() -> None:
    """Register the API service on first use."""
    global _api_registered
    if not _api_registered:
        from macsdk.core.api_registry import register_api_service

        # Register DevOps Mock API as a service
        # This is a demo API - replace with your own API endpoint
        register_api_service(
            name="devops",
            base_url="https://my-json-server.typicode.com/juanje/devops-mock-api",
            timeout=10,
            max_retries=2,
        )
        _api_registered = True


# =============================================================================
# SERVICE HEALTH TOOLS
# =============================================================================


@tool
async def get_services() -> str:
    """List all infrastructure services and their health status.

    Returns services with status (healthy, degraded, warning, critical).

    Returns:
        List of services as JSON string.
    """
    from macsdk.tools import api_get

    _ensure_api_registered()
    return await api_get.ainvoke(
        {
            "service": "devops",
            "endpoint": "/services",
        }
    )


@tool
async def get_service_status(service_id: int) -> str:
    """Get the status of a specific service.

    Args:
        service_id: The service's ID (1-5).

    Returns:
        Service details including name, status, and uptime.
    """
    from macsdk.tools import api_get

    _ensure_api_registered()
    return await api_get.ainvoke(
        {
            "service": "devops",
            "endpoint": f"/services/{service_id}",
        }
    )


# =============================================================================
# ALERT TOOLS
# =============================================================================


@tool
async def get_alerts() -> str:
    """List all active alerts.

    Returns alerts with severity (info, warning, critical) and acknowledgment status.
    Use this to identify issues that need attention.

    Returns:
        List of alerts as JSON string.
    """
    from macsdk.tools import api_get

    _ensure_api_registered()
    return await api_get.ainvoke(
        {
            "service": "devops",
            "endpoint": "/alerts",
        }
    )


# =============================================================================
# CUSTOMIZATION
# =============================================================================

# To use your own API, modify the _ensure_api_registered function above:
#
# def _ensure_api_registered() -> None:
#     global _api_registered
#     if not _api_registered:
#         from macsdk.core.api_registry import register_api_service
#         register_api_service(
#             name="myapi",
#             base_url="https://api.example.com",
#             token=os.environ.get("API_TOKEN"),  # Optional authentication
#             timeout=30,
#         )
#         _api_registered = True
#
# Then create tools that call your endpoints:
#
# @tool
# async def get_items() -> str:
#     """Get all items from the API."""
#     from macsdk.tools import api_get
#     _ensure_api_registered()
#     return await api_get.ainvoke({
#         "service": "myapi",
#         "endpoint": "/items",
#     })
#
# See examples/api-agent/ for a complete example with more tools.
