__author__ = "https://github.com/materialsvirtuallab/monty/blob/master/monty/json.py"
__version__ = "3.0.0"

from typing import Optional, List, Dict, Any

"""
This code has been taken and modified from https://guide.materialsvirtuallab.org/monty/index.html
Many thanks to the original authors, the source and contributors can be found at __author__

The MIT License (MIT)

Copyright (c) 2014 Materials Virtual Lab

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


JSON serialization and deserialization utilities.
"""

#  SPDX-FileCopyrightText: 2022 easyCore contributors  <core@easyscience.software>
#  SPDX-License-Identifier: BSD-3-Clause
#  © 2021-2022 Contributors to the easyCore project <https://github.com/easyScience/easyCore>

import os
import json
import datetime

from hashlib import sha1
from collections import OrderedDict, defaultdict
from enum import Enum

from importlib import import_module

from inspect import getfullargspec

from easyCore import np


_KNOWN_CORE_TYPES = ("Descriptor", "Parameter")

try:
    import bson
except ImportError:
    bson = None

try:
    import ruamel.yaml as yaml
except ImportError:
    try:
        import yaml  # type: ignore
    except ImportError:
        yaml = None  # type: ignore


def _load_redirect(redirect_file):
    try:
        with open(redirect_file, "rt") as f:
            d = yaml.safe_load(f)
    except IOError:
        # If we can't find the file
        # Just use an empty redirect dict
        return {}

    # Convert the full paths to module/class
    redirect_dict = defaultdict(dict)
    for old_path, new_path in d.items():
        old_class = old_path.split(".")[-1]
        old_module = ".".join(old_path.split(".")[:-1])

        new_class = new_path.split(".")[-1]
        new_module = ".".join(new_path.split(".")[:-1])

        redirect_dict[old_module][old_class] = {
            "@module": new_module,
            "@class": new_class,
        }

    return dict(redirect_dict)


def get_class_module(obj):
    """
    Returns the REAL module of the class of the object.
    """
    c = getattr(obj, "__old_class__", obj.__class__)
    return c.__module__


class MSONable:
    """
    This is a mix-in base class specifying an API for msonable objects. MSON
    is Monty JSON. Essentially, MSONable objects must implement an as_dict
    method, which must return a json serializable dict and must also support
    no arguments (though optional arguments to finetune the output is ok),
    and a from_dict class method that regenerates the object from the dict
    generated by the as_dict method. The as_dict method should contain the
    "@module" and "@class" keys which will allow the MontyEncoder to
    dynamically deserialize the class. E.g.::

        d["@module"] = self.__class__.__module__
        d["@class"] = self.__class__.__name__

    A default implementation is provided in MSONable, which automatically
    determines if the class already contains self.argname or self._argname
    attributes for every arg. If so, these will be used for serialization in
    the dict format. Similarly, the default from_dict will deserialization
    classes of such form. An example is given below::

        class MSONClass(MSONable):

        def __init__(self, a, b, c, d=1, **kwargs):
            self.a = a
            self.b = b
            self._c = c
            self._d = d
            self.kwargs = kwargs

    For such classes, you merely need to inherit from MSONable and you do not
    need to implement your own as_dict or from_dict protocol.

    New to Monty V2.0.6....
    Classes can be redirected to moved implementations by putting in the old
    fully qualified path and new fully qualified path into .monty.yaml in the
    home folder

    Example:
    old_module.old_class: new_module.new_class
    """

    REDIRECT = _load_redirect(os.path.join(os.path.expanduser("~"), ".monty.yaml"))

    def as_dict(self, skip: Optional[List[str]] = None) -> Dict[str, Any]:
        """
        A JSON serializable dict representation of an object.
        """
        if skip is None:
            skip = []
        elif isinstance(skip, str):
            skip = [skip]
        if not isinstance(skip, list):
            raise ValueError("Skip must be a list of strings.")

        d = {"@module": get_class_module(self), "@class": self.__class__.__name__}

        try:
            parent_module = get_class_module(self).split(".")[0]
            module_version = import_module(parent_module).__version__  # type: ignore
            d["@version"] = "{}".format(module_version)
        except (AttributeError, ImportError):
            d["@version"] = None  # type: ignore

        spec = getfullargspec(self.__class__.__init__)
        args = spec.args

        def recursive_as_dict(obj):
            if isinstance(obj, (list, tuple)):
                return [recursive_as_dict(it) for it in obj]
            if isinstance(obj, dict):
                return {kk: recursive_as_dict(vv) for kk, vv in obj.items()}
            if hasattr(obj, "as_dict"):
                return obj.as_dict(skip=skip)
            return obj

        for c in args:
            if c != "self" and c not in skip:
                try:
                    a = self.__getattribute__(c)
                except AttributeError:
                    try:
                        a = self.__getattribute__("_" + c)
                    except AttributeError:
                        err = True
                        if hasattr(self, "kwargs"):
                            # type: ignore
                            option = getattr(self, "kwargs")
                            if hasattr(option, c):
                                v = getattr(option, c)
                                delattr(option, c)
                                d.update(v)  # pylint: disable=E1101
                                err = False
                        if hasattr(self, "_kwargs"):
                            # type: ignore
                            option = getattr(self, "_kwargs")
                            if hasattr(option, c):
                                v = getattr(option, c)
                                delattr(option, c)
                                d.update(v)  # pylint: disable=E1101
                                err = False
                        if err:
                            raise NotImplementedError(
                                "Unable to automatically determine as_dict "
                                "format from class. MSONAble requires all "
                                "args to be present as either self.argname or "
                                "self._argname, and kwargs to be present under"
                                "a self.kwargs variable to automatically "
                                "determine the dict format. Alternatively, "
                                "you can implement both as_dict and from_dict."
                            )
                d[c] = recursive_as_dict(a)
        if hasattr(self, "kwargs"):
            # type: ignore
            d.update(
                {k: v for k, v in getattr(self, "kwargs").items() if k not in skip}
            )  # pylint: disable=E1101
        if spec.varargs is not None and getattr(self, spec.varargs, None) is not None:
            d.update({spec.varargs: getattr(self, spec.varargs)})
        if hasattr(self, "_kwargs"):
            d.update(
                {k: v for k, v in getattr(self, "_kwargs").items() if k not in skip}
            )  # pylint: disable=E1101
        if isinstance(self, Enum):
            d.update({"value": self.value})  # pylint: disable=E1101
        return d

    @classmethod
    def from_dict(cls, d: Dict[str, Any]) -> "MSONable":
        """
        :param d: Dict representation.
        :return: MSONable class.
        """
        decoded = {
            k: MontyDecoder().process_decoded(v)
            for k, v in d.items()
            if not k.startswith("@")
        }
        return cls(**decoded)

    def to_json(self) -> str:
        """
        Returns a json string representation of the MSONable object.
        """
        return json.dumps(self, cls=MontyEncoder)

    @staticmethod
    def __parse_dict(in_dict: Dict[str, Any]) -> Dict[str, Any]:
        out_dict = dict()
        for key in in_dict.keys():
            if key[0] == "@":
                if key == "@class" and in_dict[key] not in _KNOWN_CORE_TYPES:
                    out_dict["name"] = in_dict[key]
                continue
            out_dict[key] = in_dict[key]
            if isinstance(in_dict[key], dict):
                out_dict[key] = MSONable.__parse_dict(in_dict[key])
            elif isinstance(in_dict[key], list):
                out_dict[key] = [
                    MSONable.__parse_dict(x) if isinstance(x, dict) else x
                    for x in in_dict[key]
                ]
        return out_dict

    def to_data_dict(self, skip: Optional[List[str]] = None) -> Dict[str, Any]:
        """
        Convert the object to a reduced dictionary only containing data.

        :param skip: Which items should be skipped.
        :return: Dictionary representation of the object.
        """
        if skip is None:
            skip = []
        elif isinstance(skip, str):
            skip = [skip]
        if not isinstance(skip, list):
            raise ValueError("Skip must be a list of strings.")

        d = self.as_dict(skip=skip)
        return self.__parse_dict(d)

    def unsafe_hash(self) -> sha1:
        """
        Returns an hash of the current object. This uses a generic but low
        performance method of converting the object to a dictionary, flattening
        any nested keys, and then performing a hash on the resulting object
        """

        def flatten(obj, seperator="."):
            # Flattens a dictionary

            flat_dict = {}
            for key, value in obj.items():
                if isinstance(value, dict):
                    flat_dict.update(
                        {
                            seperator.join([key, _key]): _value
                            for _key, _value in flatten(value).items()
                        }
                    )
                elif isinstance(value, list):
                    list_dict = {
                        "{}{}{}".format(key, seperator, num): item
                        for num, item in enumerate(value)
                    }
                    flat_dict.update(flatten(list_dict))
                else:
                    flat_dict[key] = value

            return flat_dict

        ordered_keys = sorted(
            flatten(jsanitize(self.as_dict())).items(), key=lambda x: x[0]
        )
        ordered_keys = [item for item in ordered_keys if "@" not in item[0]]
        return sha1(json.dumps(OrderedDict(ordered_keys)).encode("utf-8"))  # nosec


class MontyEncoder(json.JSONEncoder):
    """
    A Json Encoder which supports the MSONable API, plus adds support for
    numpy arrays, datetime objects, bson ObjectIds (requires bson).

    Usage::

        # Add it as a *cls* keyword when using json.dump
        json.dumps(object, cls=MontyEncoder)
    """

    def default(self, o) -> dict:  # pylint: disable=E0202
        """
        Overriding default method for JSON encoding. This method does two
        things: (a) If an object has a to_dict property, return the to_dict
        output. (b) If the @module and @class keys are not in the to_dict,
        add them to the output automatically. If the object has no to_dict
        property, the default Python json encoder default method is called.

        Args:
            o: Python object.

        Return:
            Python dict representation.
        """
        if isinstance(o, datetime.datetime):
            return {"@module": "datetime", "@class": "datetime", "string": o.__str__()}
        if np is not None:
            if isinstance(o, np.ndarray):
                if str(o.dtype).startswith("complex"):
                    return {
                        "@module": "numpy",
                        "@class": "array",
                        "dtype": o.dtype.__str__(),
                        "data": [o.real.tolist(), o.imag.tolist()],
                    }
                return {
                    "@module": "numpy",
                    "@class": "array",
                    "dtype": o.dtype.__str__(),
                    "data": o.tolist(),
                }
            if isinstance(o, np.generic):
                return o.item()
        if bson is not None:
            if isinstance(o, bson.objectid.ObjectId):
                return {"@module": "bson.objectid", "@class": "ObjectId", "oid": str(o)}

        try:
            d = o.as_dict()
            if "@module" not in d:
                d["@module"] = "{}".format(o.__class__.__module__)
            if "@class" not in d:
                d["@class"] = "{}".format(o.__class__.__name__)
            if "@version" not in d:
                try:
                    parent_module = o.__class__.__module__.split(".")[0]
                    module_version = import_module(parent_module).__version__  # type: ignore
                    d["@version"] = "{}".format(module_version)
                except (AttributeError, ImportError):
                    d["@version"] = None
            return d
        except AttributeError:
            return json.JSONEncoder.default(self, o)


class MontyDecoder(json.JSONDecoder):
    """
    A Json Decoder which supports the MSONable API. By default, the
    decoder attempts to find a module and name associated with a dict. If
    found, the decoder will generate a Pymatgen as a priority.  If that fails,
    the original decoded dictionary from the string is returned. Note that
    nested lists and dicts containing pymatgen object will be decoded correctly
    as well.

    Usage:

        # Add it as a *cls* keyword when using json.load
        json.loads(json_string, cls=MontyDecoder)
    """

    def process_decoded(self, d):
        """
        Recursive method to support decoding dicts and lists containing
        pymatgen objects.
        """
        if isinstance(d, dict):
            if "@module" in d and "@class" in d:
                modname = d["@module"]
                classname = d["@class"]
                if classname in MSONable.REDIRECT.get(modname, {}):
                    modname = MSONable.REDIRECT[modname][classname]["@module"]
                    classname = MSONable.REDIRECT[modname][classname]["@class"]
            else:
                modname = None
                classname = None
            if modname and modname not in ["bson.objectid", "numpy"]:
                if modname == "datetime" and classname == "datetime":
                    try:
                        dt = datetime.datetime.strptime(
                            d["string"], "%Y-%m-%d %H:%M:%S.%f"
                        )
                    except ValueError:
                        dt = datetime.datetime.strptime(
                            d["string"], "%Y-%m-%d %H:%M:%S"
                        )
                    return dt

                mod = __import__(modname, globals(), locals(), [classname], 0)
                if hasattr(mod, classname):
                    cls_ = getattr(mod, classname)
                    data = {k: v for k, v in d.items() if not k.startswith("@")}
                    if hasattr(cls_, "from_dict"):
                        return cls_.from_dict(data)
            elif np is not None and modname == "numpy" and classname == "array":
                if d["dtype"].startswith("complex"):
                    return np.array(
                        [r + i * 1j for r, i in zip(*d["data"])], dtype=d["dtype"]
                    )
                return np.array(d["data"], dtype=d["dtype"])

            elif (
                (bson is not None)
                and modname == "bson.objectid"
                and classname == "ObjectId"
            ):
                return bson.objectid.ObjectId(d["oid"])

            return {
                self.process_decoded(k): self.process_decoded(v) for k, v in d.items()
            }

        if isinstance(d, list):
            return [self.process_decoded(x) for x in d]

        return d

    def decode(self, s):
        """
        Overrides decode from JSONDecoder.

        :param s: string
        :return: Object.
        """
        d = json.JSONDecoder.decode(self, s)
        return self.process_decoded(d)


class MSONError(Exception):
    """
    Exception class for serialization errors.
    """


def jsanitize(obj, strict=False, allow_bson=False):
    """
    This method cleans an input json-like object, either a list or a dict or
    some sequence, nested or otherwise, by converting all non-string
    dictionary keys (such as int and float) to strings, and also recursively
    encodes all objects using Monty's as_dict() protocol.

    Args:
        obj: input json-like object.
        strict (bool): This parameters sets the behavior when jsanitize
            encounters an object it does not understand. If strict is True,
            jsanitize will try to get the as_dict() attribute of the object. If
            no such attribute is found, an attribute error will be thrown. If
            strict is False, jsanitize will simply call str(object) to convert
            the object to a string representation.
        allow_bson (bool): This parameters sets the behavior when jsanitize
            encounters an bson supported type such as objectid and datetime. If
            True, such bson types will be ignored, allowing for proper
            insertion into MongoDb databases.

    Returns:
        Sanitized dict that can be json serialized.
    """
    if allow_bson and (
        isinstance(obj, (datetime.datetime, bytes))
        or (bson is not None and isinstance(obj, bson.objectid.ObjectId))
    ):
        return obj
    if isinstance(obj, (list, tuple)):
        return [jsanitize(i, strict=strict, allow_bson=allow_bson) for i in obj]
    if np is not None and isinstance(obj, np.ndarray):
        return [
            jsanitize(i, strict=strict, allow_bson=allow_bson) for i in obj.tolist()
        ]
    if isinstance(obj, dict):
        return {
            k.__str__(): jsanitize(v, strict=strict, allow_bson=allow_bson)
            for k, v in obj.items()
        }
    if isinstance(obj, (int, float)):
        return obj
    if obj is None:
        return None

    if not strict:
        return obj.__str__()

    if isinstance(obj, str):
        return obj.__str__()

    return jsanitize(obj.as_dict(), strict=strict, allow_bson=allow_bson)
