"""JSON serializer/deserializer for QRP messages."""

from __future__ import annotations

import json
import logging
from typing import Any

logger = logging.getLogger("qremotex.protocol")


def serialize(msg: dict[str, Any]) -> str:
    """Serialize a QRP message dict to a JSON string."""
    return json.dumps(msg, ensure_ascii=False, separators=(",", ":"))


def deserialize(raw: str) -> dict[str, Any] | None:
    """Deserialize a raw JSON string to a QRP message dict.

    Returns None for malformed input rather than raising.
    """
    try:
        data = json.loads(raw)
    except (json.JSONDecodeError, TypeError):
        logger.warning("Failed to deserialize QRP message (invalid JSON)")
        return None

    if not isinstance(data, dict):
        logger.warning("QRP message is not a JSON object")
        return None

    if "type" not in data:
        logger.warning("QRP message missing 'type' field")
        return None

    return data
