"""
Copyright CNRS (https://www.cnrs.fr/index.php/en)
Contributor(s): Eric Debreuve (eric.debreuve@cnrs.fr) since 2025
SEE COPYRIGHT NOTICE BELOW
"""

from multiprocessing import process
from multiprocessing.managers import BaseProxy as base_t
from multiprocessing.managers import Token, dispatch, listener_client, public_methods
from traceback import format_exc


def all_attributes(obj):
    """"""
    temp = []
    for name in dir(obj):
        func = getattr(obj, name)
        if not callable(func):
            temp.append(name)
    return temp


def public_attributes(obj):
    """"""
    return ["." + name for name in all_attributes(obj) if name[0] != "_"]


def serve_client(self, conn):
    """"""
    recv = conn.recv
    send = conn.send
    id_to_obj = self.id_to_obj

    while not self.stop_event.is_set():
        try:
            methodname = obj = None
            request = recv()
            ident, methodname, args, kwds = request
            try:
                obj, exposed, gettypeid = id_to_obj[ident]
            except KeyError as ke:
                try:
                    obj, exposed, gettypeid = self.id_to_local_proxy_obj[ident]
                except KeyError:
                    raise ke

            if is_attribute := (methodname[0] == "."):
                methodname = methodname[1:]
            function = getattr(obj, methodname)

            try:
                if is_attribute:
                    res = function
                else:
                    res = function(*args, **kwds)
            except Exception as e:
                msg = ("#ERROR", e)
            else:
                typeid = gettypeid and gettypeid.get(methodname, None)
                if typeid:
                    rident, rexposed = self.create(conn, typeid, res)
                    token = Token(typeid, self.address, rident)
                    msg = ("#PROXY", (rexposed, token))
                else:
                    msg = ("#RETURN", res)

        except AttributeError:
            if methodname is None:
                msg = ("#TRACEBACK", format_exc())
            else:
                try:
                    fallback_func = self.fallback_mapping[methodname]
                    result = fallback_func(self, conn, ident, obj, *args, **kwds)
                    msg = ("#RETURN", result)
                except Exception:
                    msg = ("#TRACEBACK", format_exc())

        except EOFError:
            import sys

            sys.exit(0)

        except Exception:
            msg = ("#TRACEBACK", format_exc())

        try:
            try:
                send(msg)
            except Exception:
                send(("#UNSERIALIZABLE", format_exc()))
        except Exception as e:
            import sys

            conn.close()
            sys.exit(1)


def create(self, c, typeid, /, *args, **kwds):
    """"""
    with self.mutex:
        callable, exposed, method_to_typeid, proxytype = self.registry[typeid]

        if callable is None:
            if kwds or (len(args) != 1):
                raise ValueError("Without callable, must have one non-keyword argument")
            obj = args[0]
        else:
            obj = callable(*args, **kwds)

        if exposed is None:
            exposed = public_methods(obj) + public_attributes(obj)
        if method_to_typeid is not None:
            if not isinstance(method_to_typeid, dict):
                raise TypeError(
                    "Method_to_typeid {0!r}: type {1!s}, not dict".format(
                        method_to_typeid, type(method_to_typeid)
                    )
                )
            exposed = list(exposed) + list(method_to_typeid)

        ident = "%x" % id(obj)  # convert to string because xmlrpclib
        # only has 32 bit signed integers

        self.id_to_obj[ident] = (obj, set(exposed), method_to_typeid)
        if ident not in self.id_to_refcount:
            self.id_to_refcount[ident] = 0

    self.incref(c, ident)
    return ident, tuple(exposed)


def MakeProxyType(name, exposed, _cache={}):
    """"""
    exposed = tuple(exposed)
    try:
        return _cache[(name, exposed)]
    except KeyError:
        pass

    dic = {}

    for meth in exposed:
        if meth[0] == ".":
            exec(
                """@property
def %s(self):
            return self._callmethod(%r, (), {})"""
                % (meth[1:], meth),
                dic,
            )
        else:
            exec(
                """def %s(self, /, *args, **kwds):
            return self._callmethod(%r, args, kwds)"""
                % (meth, meth),
                dic,
            )

    ProxyType = type(name, (base_t,), dic)
    ProxyType._exposed_ = exposed
    _cache[(name, exposed)] = ProxyType
    return ProxyType


def ProxyWithAttributes(
    token,
    serializer,
    manager=None,
    authkey=None,
    exposed=None,
    incref=True,
    manager_owned=False,
):
    """"""
    _Client = listener_client[serializer][1]

    if exposed is None:
        conn = _Client(token.address, authkey=authkey)
        try:
            exposed = dispatch(conn, None, "get_methods", (token,))
        finally:
            conn.close()

    if authkey is None and manager is not None:
        authkey = manager._authkey
    if authkey is None:
        authkey = process.current_process().authkey

    ProxyType = MakeProxyType("ProxyWithAttributes[%s]" % token.typeid, exposed)
    proxy = ProxyType(
        token,
        serializer,
        manager=manager,
        authkey=authkey,
        incref=incref,
        manager_owned=manager_owned,
    )
    proxy._isauto = True
    return proxy


"""
COPYRIGHT NOTICE

This software is governed by the CeCILL  license under French law and
abiding by the rules of distribution of free software.  You can  use,
modify and/ or redistribute the software under the terms of the CeCILL
license as circulated by CEA, CNRS and INRIA at the following URL
"http://www.cecill.info".

As a counterpart to the access to the source code and  rights to copy,
modify and redistribute granted by the license, users are provided only
with a limited warranty  and the software's author,  the holder of the
economic rights,  and the successive licensors  have only  limited
liability.

In this respect, the user's attention is drawn to the risks associated
with loading,  using,  modifying and/or developing or reproducing the
software by the user in light of its specific status of free software,
that may mean  that it is complicated to manipulate,  and  that  also
therefore means  that it is reserved for developers  and  experienced
professionals having in-depth computer knowledge. Users are therefore
encouraged to load and test the software's suitability as regards their
requirements in conditions enabling the security of their systems and/or
data to be ensured and,  more generally, to use and operate it in the
same conditions as regards security.

The fact that you are presently reading this means that you have had
knowledge of the CeCILL license and that you accept its terms.

SEE LICENCE NOTICE: file README-LICENCE-utf8.txt at project source root.
"""
