from typing import Any
from typing import Dict
from typing import Tuple
from xml.etree import ElementTree

from xsdata.formats.dataclass.parsers import XmlParser
from xsdata.formats.dataclass.parsers.config import ParserConfig
from xsdata.formats.dataclass.serializers import DictEncoder
from xsdata.formats.dataclass.serializers import DictFactory

from ..models.xsd.dataset import Dataset
from ..models.xsd.investigation import Investigation


def deserialize_message(data: bytes) -> Tuple[str, Dict[str, Any]]:
    """
    :raises xml.etree.ElementTree.ParseError:
    """
    root = ElementTree.fromstring(data)
    root_tag = root.tag.split("}", 1)[-1]

    if root_tag == "dataset":
        cls = Dataset
    elif root_tag == "investigation":
        cls = Investigation
    else:
        raise ValueError(f"Unknown ICAT root element: {root.tag}")

    config = ParserConfig(fail_on_unknown_properties=False)
    deserializer = XmlParser(config=config)
    xsdata_model = deserializer.from_bytes(data, cls)

    encoder = DictEncoder(dict_factory=DictFactory.FILTER_NONE)
    model_as_dict = encoder.encode(xsdata_model)

    return root_tag, model_as_dict
