"""JSON-RPC 2.0 message builders for the MCP protocol."""

from __future__ import annotations

import json
from typing import Any


def build_initialize_request(
    request_id: int = 1,
    client_name: str = "hdx",
    client_version: str = "0.1.0",
) -> str:
    """Build a JSON-RPC initialize request message."""
    return json.dumps({
        "jsonrpc": "2.0",
        "id": request_id,
        "method": "initialize",
        "params": {
            "protocolVersion": "2025-03-26",
            "capabilities": {},
            "clientInfo": {"name": client_name, "version": client_version},
        },
    })


def build_initialized_notification() -> str:
    """Build a JSON-RPC notifications/initialized notification."""
    return json.dumps({
        "jsonrpc": "2.0",
        "method": "notifications/initialized",
    })


def build_tool_call_request(
    tool_name: str,
    arguments: dict[str, Any] | None = None,
    request_id: int = 2,
) -> str:
    """Build a JSON-RPC tools/call request message."""
    return json.dumps({
        "jsonrpc": "2.0",
        "id": request_id,
        "method": "tools/call",
        "params": {"name": tool_name, "arguments": arguments or {}},
    })


def build_request(method: str, params: dict[str, Any], request_id: int) -> str:
    """Build a generic JSON-RPC 2.0 request message."""
    return json.dumps({
        "jsonrpc": "2.0",
        "id": request_id,
        "method": method,
        "params": params,
    })


def build_notification(method: str, params: dict[str, Any] | None = None) -> str:
    """Build a JSON-RPC 2.0 notification (no id, no response expected)."""
    message: dict[str, Any] = {
        "jsonrpc": "2.0",
        "method": method,
    }
    if params is not None:
        message["params"] = params
    return json.dumps(message)
