"""Graylog stream tools — list and inspect streams."""

from __future__ import annotations

from typing import Any

from mcp.types import ToolAnnotations

from mcp_eregistrations_graylog.graylog_client import (
    GraylogClient,
    GraylogClientError,
    translate_error,
)
from mcp_eregistrations_graylog.server import mcp


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
async def graylog_stream_list(
    instance: str | None = None,
) -> dict[str, Any]:
    """List all Graylog streams. Requires auth.

    Args:
        instance: Instance name.

    Returns:
        dict with count, streams (id, title, description, disabled).
    """
    try:
        async with GraylogClient.for_instance(instance) as client:
            data = await client.get("/api/streams")
    except GraylogClientError as e:
        raise translate_error(e, resource_type="streams") from e

    raw_streams = data.get("streams", [])
    streams = [
        {
            "id": s.get("id"),
            "title": s.get("title"),
            "description": s.get("description"),
            "disabled": s.get("disabled", False),
        }
        for s in raw_streams
    ]
    return {"count": len(streams), "streams": streams}


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
async def graylog_stream_get(
    stream_id: str,
    instance: str | None = None,
) -> dict[str, Any]:
    """Get detailed stream info. Requires auth.

    Args:
        stream_id: Stream ID (from graylog_stream_list).
        instance: Instance name.

    Returns:
        dict with stream details (id, title, rules, created_at, etc).
    """
    try:
        async with GraylogClient.for_instance(instance) as client:
            result: dict[str, Any] = await client.get(f"/api/streams/{stream_id}")
            return result
    except GraylogClientError as e:
        raise translate_error(e, resource_type="stream", resource_id=stream_id) from e
