"""
JSON-RPC 2.0 protocol models.
"""

from typing import Any, Optional, Union

from pydantic import BaseModel, Field


class JSONRPCException(Exception):
    """JSON-RPC exception for error handling."""

    def __init__(self, code: int, message: str, data: Optional[Any] = None):
        self.code = code
        self.message = message
        self.data = data
        super().__init__(message)


class JSONRPCError(BaseModel):
    """JSON-RPC error object."""

    code: int = Field(..., description="Error code")
    message: str = Field(..., description="Error message")
    data: Optional[Any] = Field(None, description="Additional error data")

    model_config = {"populate_by_name": True}


class JSONRPCRequest(BaseModel):
    """JSON-RPC 2.0 request."""

    jsonrpc: str = Field(default="2.0", description="Protocol version")
    id: Optional[Union[int, str]] = Field(None, description="Request ID")
    method: str = Field(..., description="Method name")
    params: Optional[dict[str, Any]] = Field(None, description="Method parameters")

    model_config = {"populate_by_name": True}


class JSONRPCResponse(BaseModel):
    """JSON-RPC 2.0 response."""

    jsonrpc: str = Field(default="2.0", description="Protocol version")
    id: Optional[Union[int, str]] = Field(None, description="Request ID (matches request)")
    result: Optional[Any] = Field(None, description="Result (on success)")
    error: Optional[JSONRPCError] = Field(None, description="Error (on failure)")

    model_config = {"populate_by_name": True}

    def is_success(self) -> bool:
        """Check if response indicates success."""
        return self.error is None
