import datetime
from dataclasses import is_dataclass
from typing import Any
from typing import Dict
from typing import Optional

from xsdata.formats.dataclass.serializers import XmlSerializer
from xsdata.formats.dataclass.serializers.config import SerializerConfig


def serialize_message(xsdata_model: Any, indent: Optional[str] = None) -> bytes:
    """Serialize message with XSD validation."""
    if not is_dataclass(xsdata_model):
        raise TypeError("Expected a dataclass")
    config = SerializerConfig(indent=indent, xml_declaration=True)
    serializer = XmlSerializer(config=config)
    xml_string = serializer.render(
        xsdata_model, ns_map={"tns": "http://www.esrf.fr/icat"}
    )
    if indent is None:
        xml_string = xml_string.replace("\n", "")
    return xml_string.encode("utf-8")


def serialize_root(data: Dict[str, Any]) -> Dict[str, Any]:
    """XSD validation currently does not validate values so we do it ourselves."""
    result = {}
    for name, value in data.items():
        if isinstance(value, datetime.datetime):
            value = value.isoformat()
        result[name] = value
    return result
