# This is culled but modified from Python 3.x's inspect.py
"""Parts of Python 3.3+'s inspect class for older Pythons"""

import itertools
import types
from collections import namedtuple, OrderedDict

from xdis import PYTHON_VERSION

# from _ParameterKind without the enum that doesn't work on older Pythons
POSITIONAL_ONLY = 0
POSITIONAL_OR_KEYWORD = 1
VAR_POSITIONAL = 2
KEYWORD_ONLY = 3
VAR_KEYWORD = 4


def formatannotation(annotation, base_module=None):
    if getattr(annotation, "__module__", None) == "typing":
        return repr(annotation).replace("typing.", "")
    if isinstance(annotation, type):
        if annotation.__module__ in ("builtins", base_module):
            return annotation.__qualname__
        return annotation.__module__ + "." + annotation.__qualname__
    return repr(annotation)


class _void:
    """A private marker - used in Parameter & Signature."""


class _empty:
    """Marker object for Signature.empty and Parameter.empty."""

    pass


_PARAM_NAME_MAPPING = {
    POSITIONAL_ONLY: "positional-only",
    POSITIONAL_OR_KEYWORD: "positional or keyword",
    VAR_POSITIONAL: "variadic positional",
    KEYWORD_ONLY: "keyword-only",
    VAR_KEYWORD: "variadic keyword",
}
_get_paramkind_descr = _PARAM_NAME_MAPPING.__getitem__

FullArgSpec = namedtuple(
    "FullArgSpec",
    "args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations",
)


class Parameter:
    """Represents a parameter in a function signature.

    Has the following public attributes:

    * name : str
        The name of the parameter as a string.
    * default : object
        The default value for the parameter if specified.  If the
        parameter has no default value, this attribute is set to
        `Parameter.empty`.
    * annotation
        The annotation for the parameter if specified.  If the
        parameter has no annotation, this attribute is set to
        `Parameter.empty`.
    * kind : str
        Describes how argument values are bound to the parameter.
        Possible values: `Parameter.POSITIONAL_ONLY`,
        `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
        `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
    """

    __slots__ = ("_name", "_kind", "_default", "_annotation")

    empty = _empty

    def __init__(self, name, kind, default=_empty, annotation=_empty):
        try:
            self._kind = kind
        except ValueError:
            raise ValueError("value {%r} is not a valid Parameter.kind" % kind)
        if default is not _empty:
            if self._kind in (VAR_POSITIONAL, VAR_KEYWORD):
                msg = "{} parameters cannot have default values"
                msg = msg.format(_get_paramkind_descr(self._kind))
                raise ValueError(msg)
        self._default = default
        self._annotation = annotation

        if name is _empty:
            raise ValueError("name is a required attribute for Parameter")

        if not isinstance(name, str):
            msg = "name must be a str, not a {}".format(type(name).__name__)
            raise TypeError(msg)

        if name[0] == "." and name[1:].isdigit():
            # These are implicit arguments generated by comprehensions. In
            # order to provide a friendlier interface to users, we recast
            # their name as "implicitN" and treat them as positional-only.
            # See issue 19611.
            if self._kind != POSITIONAL_OR_KEYWORD:
                msg = (
                    "implicit arguments must be passed as "
                    "positional or keyword arguments, not {}"
                )
                msg = msg.format(_get_paramkind_descr(self._kind))
                raise ValueError(msg)
            self._kind = POSITIONAL_ONLY
            name = "implicit{}".format(name[1:])

        if not name.isidentifier():
            raise ValueError("{!r} is not a valid parameter name".format(name))

        self._name = name

    def __reduce__(self):
        return (
            type(self),
            (self._name, self._kind),
            {"_default": self._default, "_annotation": self._annotation},
        )

    def __setstate__(self, state):
        self._default = state["_default"]
        self._annotation = state["_annotation"]

    @property
    def name(self):
        return self._name

    @property
    def default(self):
        return self._default

    @property
    def annotation(self):
        return self._annotation

    @property
    def kind(self):
        return self._kind

    def replace(self, name=_void, kind=_void, annotation=_void, default=_void):
        """Creates a customized copy of the Parameter."""

        if name is _void:
            name = self._name

        if kind is _void:
            kind = self._kind

        if annotation is _void:
            annotation = self._annotation

        if default is _void:
            default = self._default

        return type(self)(name, kind, default=default, annotation=annotation)

    def __str__(self):
        kind = self.kind
        formatted = self._name

        # Add annotation and default value
        if self._annotation is not _empty:
            formatted = "{}: {}".format(formatted, formatannotation(self._annotation))

        if self._default is not _empty:
            if self._annotation is not _empty:
                formatted = "{} = {}".format(formatted, repr(self._default))
            else:
                formatted = "{}={}".format(formatted, repr(self._default))

        if kind == VAR_POSITIONAL:
            formatted = "*" + formatted
        elif kind == VAR_KEYWORD:
            formatted = "**" + formatted

        return formatted

    def __repr__(self):
        return '<{} "{}">'.format(self.__class__.__name__, self)

    def __hash__(self):
        return hash((self.name, self.kind, self.annotation, self.default))

    def __eq__(self, other):
        if self is other:
            return True
        if not isinstance(other, Parameter):
            return NotImplemented
        return (
            self._name == other._name
            and self._kind == other._kind
            and self._default == other._default
            and self._annotation == other._annotation
        )


class BoundArguments:
    """Result of `Signature.bind` call.  Holds the mapping of arguments
    to the function's parameters.

    Has the following public attributes:

    * arguments : OrderedDict
        An ordered mutable mapping of parameters' names to arguments' values.
        Does not contain arguments' default values.
    * signature : Signature
        The Signature object that created this instance.
    * args : tuple
        Tuple of positional arguments values.
    * kwargs : dict
        Dict of keyword arguments values.
    """

    __slots__ = ("arguments", "_signature", "__weakref__")

    def __init__(self, signature, arguments):
        self.arguments = arguments
        self._signature = signature

    @property
    def signature(self):
        return self._signature

    @property
    def args(self):
        args = []
        for param_name, param in self._signature.parameters.items():
            if param.kind in (VAR_KEYWORD, KEYWORD_ONLY):
                break

            try:
                arg = self.arguments[param_name]
            except KeyError:
                # We're done here. Other arguments
                # will be mapped in 'BoundArguments.kwargs'
                break
            else:
                if param.kind == VAR_POSITIONAL:
                    # *args
                    args.extend(arg)
                else:
                    # plain argument
                    args.append(arg)

        return tuple(args)

    @property
    def kwargs(self):
        kwargs = {}
        kwargs_started = False
        for param_name, param in self._signature.parameters.items():
            if not kwargs_started:
                if param.kind in (VAR_KEYWORD, KEYWORD_ONLY):
                    kwargs_started = True
                else:
                    if param_name not in self.arguments:
                        kwargs_started = True
                        continue

            if not kwargs_started:
                continue

            try:
                arg = self.arguments[param_name]
            except KeyError:
                pass
            else:
                if param.kind == VAR_KEYWORD:
                    # **kwargs
                    kwargs.update(arg)
                else:
                    # plain keyword argument
                    kwargs[param_name] = arg

        return kwargs

    def apply_defaults(self):
        """Set default values for missing arguments.

        For variable-positional arguments (*args) the default is an
        empty tuple.

        For variable-keyword arguments (**kwargs) the default is an
        empty dict.
        """
        arguments = self.arguments
        new_arguments = []
        for name, param in self._signature.parameters.items():
            try:
                new_arguments.append((name, arguments[name]))
            except KeyError:
                if param.default is not _empty:
                    val = param.default
                elif param.kind is VAR_POSITIONAL:
                    val = ()
                elif param.kind is VAR_KEYWORD:
                    val = {}
                else:
                    # This BoundArguments was likely produced by
                    # Signature.bind_partial().
                    continue
                new_arguments.append((name, val))
        self.arguments = OrderedDict(new_arguments)

    def __eq__(self, other):
        if self is other:
            return True
        if not isinstance(other, BoundArguments):
            return NotImplemented
        return self.signature == other.signature and self.arguments == other.arguments

    def __setstate__(self, state):
        self._signature = state["_signature"]
        self.arguments = state["arguments"]

    def __getstate__(self):
        return {"_signature": self._signature, "arguments": self.arguments}

    def __repr__(self):
        args = []
        for arg, value in self.arguments.items():
            args.append("{}={!r}".format(arg, value))
        return "<{} ({})>".format(self.__class__.__name__, ", ".join(args))


class Signature:
    """A Signature object represents the overall signature of a function.
    It stores a Parameter object for each parameter accepted by the
    function, as well as information specific to the function itself.

    A Signature object has the following public attributes and methods:

    * parameters : OrderedDict
        An ordered mapping of parameters' names to the corresponding
        Parameter objects (keyword-only arguments are in the same order
        as listed in `code.co_varnames`).
    * return_annotation : object
        The annotation for the return type of the function if specified.
        If the function has no annotation for its return type, this
        attribute is set to `Signature.empty`.
    * bind(*args, **kwargs) -> BoundArguments
        Creates a mapping from positional and keyword arguments to
        parameters.
    * bind_partial(*args, **kwargs) -> BoundArguments
        Creates a partial mapping from positional and keyword arguments
        to parameters (simulating 'functools.partial' behavior.)
    """

    __slots__ = ("_return_annotation", "_parameters")

    _parameter_cls = Parameter
    _bound_arguments_cls = BoundArguments

    empty = _empty

    def __init__(
        self, parameters=None, return_annotation=_empty, __validate_parameters__=True
    ):
        """Constructs Signature from the given list of Parameter
        objects and 'return_annotation'.  All arguments are optional.
        """

        if parameters is None:
            params = OrderedDict()
        else:
            if __validate_parameters__:
                params = OrderedDict()
                top_kind = POSITIONAL_ONLY
                kind_defaults = False

                for idx, param in enumerate(parameters):
                    kind = param.kind
                    name = param.name

                    if kind < top_kind:
                        msg = (
                            "wrong parameter order: {} parameter before {} " "parameter"
                        )
                        msg = msg.format(
                            _get_paramkind_descr(top_kind), _get_paramkind_descr(kind)
                        )
                        raise ValueError(msg)
                    elif kind > top_kind:
                        kind_defaults = False
                        top_kind = kind

                    if kind in (POSITIONAL_ONLY, POSITIONAL_OR_KEYWORD):
                        if param.default is _empty:
                            if kind_defaults:
                                # No default for this parameter, but the
                                # previous parameter of the same kind had
                                # a default
                                msg = "non-default argument follows default " "argument"
                                raise ValueError(msg)
                        else:
                            # There is a default for this parameter.
                            kind_defaults = True

                    if name in params:
                        msg = "duplicate parameter name: {!r}".format(name)
                        raise ValueError(msg)

                    params[name] = param
            else:
                params = OrderedDict(((param.name, param) for param in parameters))

        # types.MappingProxyType (which is "dict" isn't around in older Pythons
        # and dict(params) doesn't work.
        # self._parameters = types.MappingProxyType(params)
        # FIXME: the below simplification may cause problems in the future.
        self._parameters = params

        self._return_annotation = return_annotation

    # TODO: add as needed
    # @classmethod
    # def from_function(cls, func):
    #     """Constructs Signature for the given python function.

    #     Deprecated since Python 3.5, use `Signature.from_callable()`.
    #     """

    #     warnings.warn("inspect.Signature.from_function() is deprecated since "
    #                   "Python 3.5, use Signature.from_callable()",
    #                   DeprecationWarning, stacklevel=2)
    #     return _signature_from_function(cls, func)

    # @classmethod
    # def from_builtin(cls, func):
    #     """Constructs Signature for the given builtin function.

    #     Deprecated since Python 3.5, use `Signature.from_callable()`.
    #     """

    #     warnings.warn("inspect.Signature.from_builtin() is deprecated since "
    #                   "Python 3.5, use Signature.from_callable()",
    #                   DeprecationWarning, stacklevel=2)
    #     return _signature_from_builtin(cls, func)

    # @classmethod
    # def from_callable(cls, obj, *, follow_wrapped=True):
    #     """Constructs Signature for the given callable object."""
    #     return _signature_from_callable(obj, sigcls=cls,
    #                                     follow_wrapper_chains=follow_wrapped)

    @property
    def parameters(self):
        return self._parameters

    @property
    def return_annotation(self):
        return self._return_annotation

    def replace(self, parameters=_void, return_annotation=_void):
        """Creates a customized copy of the Signature.
        Pass 'parameters' and/or 'return_annotation' arguments
        to override them in the new copy.
        """

        if parameters is _void:
            parameters = self.parameters.values()

        if return_annotation is _void:
            return_annotation = self._return_annotation

        return type(self)(parameters, return_annotation=return_annotation)

    def _hash_basis(self):
        params = tuple(
            param for param in self.parameters.values() if param.kind != KEYWORD_ONLY
        )

        kwo_params = {
            param.name: param
            for param in self.parameters.values()
            if param.kind == KEYWORD_ONLY
        }

        return params, kwo_params, self.return_annotation

    def __hash__(self):
        params, kwo_params, return_annotation = self._hash_basis()
        kwo_params = frozenset(kwo_params.values())
        return hash((params, kwo_params, return_annotation))

    def __eq__(self, other):
        if self is other:
            return True
        if not isinstance(other, Signature):
            return NotImplemented
        return self._hash_basis() == other._hash_basis()

    def _bind(self, args, kwargs, partial=False):
        """Private method. Don't use directly."""

        arguments = OrderedDict()

        parameters = iter(self.parameters.values())
        parameters_ex = ()
        arg_vals = iter(args)

        while True:
            # Let's iterate through the positional arguments and corresponding
            # parameters
            try:
                arg_val = next(arg_vals)
            except StopIteration:
                # No more positional arguments
                try:
                    param = next(parameters)
                except StopIteration:
                    # No more parameters. That's it. Just need to check that
                    # we have no `kwargs` after this while loop
                    break
                else:
                    if param.kind == VAR_POSITIONAL:
                        # That's OK, just empty *args.  Let's start parsing
                        # kwargs
                        break
                    elif param.name in kwargs:
                        if param.kind == POSITIONAL_ONLY:
                            msg = (
                                "{arg!r} parameter is positional only, "
                                "but was passed as a keyword"
                            )
                            msg = msg.format(arg=param.name)
                            raise TypeError(msg)
                        parameters_ex = (param,)
                        break
                    elif param.kind == VAR_KEYWORD or param.default is not _empty:
                        # That's fine too - we have a default value for this
                        # parameter.  So, lets start parsing `kwargs`, starting
                        # with the current parameter
                        parameters_ex = (param,)
                        break
                    else:
                        # No default, not VAR_KEYWORD, not VAR_POSITIONAL,
                        # not in `kwargs`
                        if partial:
                            parameters_ex = (param,)
                            break
                        else:
                            msg = "missing a required argument: {arg!r}"
                            msg = msg.format(arg=param.name)
                            raise TypeError(msg)
            else:
                # We have a positional argument to process
                try:
                    param = next(parameters)
                except StopIteration:
                    raise TypeError("too many positional arguments")
                else:
                    if param.kind in (VAR_KEYWORD, KEYWORD_ONLY):
                        # Looks like we have no parameter for this positional
                        # argument
                        raise TypeError("too many positional arguments")

                    if param.kind == VAR_POSITIONAL:
                        # We have an '*args'-like argument, let's fill it with
                        # all positional arguments we have left and move on to
                        # the next phase
                        values = [arg_val]
                        values.extend(arg_vals)
                        arguments[param.name] = tuple(values)
                        break

                    if param.name in kwargs:
                        raise TypeError(
                            "multiple values for argument {arg!r}".format(
                                arg=param.name
                            )
                        )

                    arguments[param.name] = arg_val

        # Now, we iterate through the remaining parameters to process
        # keyword arguments
        kwargs_param = None
        for param in itertools.chain(parameters_ex, parameters):
            if param.kind == VAR_KEYWORD:
                # Memorize that we have a '**kwargs'-like parameter
                kwargs_param = param
                continue

            if param.kind == VAR_POSITIONAL:
                # Named arguments don't refer to '*args'-like parameters.
                # We only arrive here if the positional arguments ended
                # before reaching the last parameter before *args.
                continue

            param_name = param.name
            try:
                arg_val = kwargs.pop(param_name)
            except KeyError:
                # We have no value for this parameter.  It's fine though,
                # if it has a default value, or it is an '*args'-like
                # parameter, left alone by the processing of positional
                # arguments.
                if (
                    not partial
                    and param.kind != VAR_POSITIONAL
                    and param.default is _empty
                ):
                    raise TypeError(
                        "missing a required argument: {arg!r}".format(arg=param_name)
                    )

            else:
                if param.kind == POSITIONAL_ONLY:
                    # This should never happen in case of a properly built
                    # Signature object (but let's have this check here
                    # to ensure correct behaviour just in case)
                    raise TypeError(
                        "{arg!r} parameter is positional only, "
                        "but was passed as a keyword".format(arg=param.name)
                    )

                arguments[param_name] = arg_val

        if kwargs:
            if kwargs_param is not None:
                # Process our '**kwargs'-like parameter
                arguments[kwargs_param.name] = kwargs
            else:
                raise TypeError(
                    "got an unexpected keyword argument {arg!r}".format(
                        arg=next(iter(kwargs))
                    )
                )

        return self._bound_arguments_cls(self, arguments)

    def bind(*args, **kwargs):
        """Get a BoundArguments object, that maps the passed `args`
        and `kwargs` to the function's signature.  Raises `TypeError`
        if the passed arguments can not be bound.
        """
        return args[0]._bind(args[1:], kwargs)

    def bind_partial(*args, **kwargs):
        """Get a BoundArguments object, that partially maps the
        passed `args` and `kwargs` to the function's signature.
        Raises `TypeError` if the passed arguments can not be bound.
        """
        return args[0]._bind(args[1:], kwargs, partial=True)

    def __reduce__(self):
        return (
            type(self),
            (tuple(self._parameters.values()),),
            {"_return_annotation": self._return_annotation},
        )

    def __setstate__(self, state):
        self._return_annotation = state["_return_annotation"]

    def __repr__(self):
        return "<{} {}>".format(self.__class__.__name__, self)

    def __str__(self):
        result = []
        render_pos_only_separator = False
        render_kw_only_separator = True
        for param in self.parameters.values():
            formatted = str(param)

            kind = param.kind

            if kind == POSITIONAL_ONLY:
                render_pos_only_separator = True
            elif render_pos_only_separator:
                # It's not a positional-only parameter, and the flag
                # is set to 'True' (there were pos-only params before.)
                result.append("/")
                render_pos_only_separator = False

            if kind == VAR_POSITIONAL:
                # OK, we have an '*args'-like parameter, so we won't need
                # a '*' to separate keyword-only arguments
                render_kw_only_separator = False
            elif kind == KEYWORD_ONLY and render_kw_only_separator:
                # We have a keyword-only parameter to render and we haven't
                # rendered an '*args'-like parameter before, so add a '*'
                # separator to the parameters list ("foo(arg1, *, arg2)" case)
                result.append("*")
                # This condition should be only triggered once, so
                # reset the flag
                render_kw_only_separator = False

            result.append(formatted)

        if render_pos_only_separator:
            # There were only positional-only parameters, hence the
            # flag was not reset to 'False'
            result.append("/")

        rendered = "({})".format(", ".join(result))

        if self.return_annotation is not _empty:
            anno = formatannotation(self.return_annotation)
            rendered += " -> {}".format(anno)

        return rendered
