# Copyright 2026 Datastrato, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Message serialization and deserialization utilities for JSON-RPC."""

import json
from typing import Any

from pydantic import ValidationError

from adp_sdk.types import (
    JSONRPCError,
    JSONRPCErrorResponse,
    JSONRPCRequest,
    JSONRPCResultResponse,
    RequestId,
)

from .exceptions import ADPError, ParseError


def serialize_message(message: JSONRPCRequest | JSONRPCResultResponse | JSONRPCErrorResponse) -> str:
    """Serialize a JSON-RPC message to a JSON string.

    Args:
        message: The JSON-RPC message to serialize.

    Returns:
        A JSON string representation of the message.
    """
    return message.model_dump_json(by_alias=True, exclude_none=True)


def deserialize_request(data: str | bytes) -> JSONRPCRequest:
    """Deserialize a JSON string to a JSON-RPC request.

    Args:
        data: The JSON string or bytes to deserialize.

    Returns:
        A JSONRPCRequest object.

    Raises:
        ParseError: If the JSON is invalid or the request structure is invalid.
    """
    try:
        if isinstance(data, bytes):
            data = data.decode("utf-8")
        return JSONRPCRequest.model_validate_json(data)
    except (json.JSONDecodeError, UnicodeDecodeError) as e:
        raise ParseError(f"Invalid JSON: {e}") from e
    except ValidationError as e:
        raise ParseError(f"Invalid request structure: {e}") from e


def deserialize_json(data: str | bytes) -> dict[str, Any]:
    """Deserialize a JSON string to a dictionary.

    Args:
        data: The JSON string or bytes to deserialize.

    Returns:
        A dictionary representation of the JSON.

    Raises:
        ParseError: If the JSON is invalid.
    """
    try:
        if isinstance(data, bytes):
            data = data.decode("utf-8")
        return json.loads(data)
    except (json.JSONDecodeError, UnicodeDecodeError) as e:
        raise ParseError(f"Invalid JSON: {e}") from e


def create_result_response(request_id: RequestId, result: dict[str, Any]) -> JSONRPCResultResponse:
    """Create a successful JSON-RPC response.

    Args:
        request_id: The ID from the original request.
        result: The result data.

    Returns:
        A JSONRPCResultResponse object.
    """
    return JSONRPCResultResponse(id=request_id, result=result)


def create_error_response(
    request_id: RequestId | None,
    error: ADPError | JSONRPCError,
) -> JSONRPCErrorResponse:
    """Create an error JSON-RPC response.

    Args:
        request_id: The ID from the original request (None if parse error).
        error: The error object.

    Returns:
        A JSONRPCErrorResponse object.
    """
    if isinstance(error, ADPError):
        json_error = JSONRPCError(code=error.code, message=error.message, data=error.data)
    else:
        json_error = error

    return JSONRPCErrorResponse(id=request_id, error=json_error)


def create_error_from_exception(
    request_id: RequestId | None,
    code: int,
    message: str,
    data: Any | None = None,
) -> JSONRPCErrorResponse:
    """Create an error JSON-RPC response from exception details.

    Args:
        request_id: The ID from the original request (None if parse error).
        code: The error code.
        message: The error message.
        data: Additional error data.

    Returns:
        A JSONRPCErrorResponse object.
    """
    return JSONRPCErrorResponse(
        id=request_id,
        error=JSONRPCError(code=code, message=message, data=data),
    )
