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

import dataclasses as d
import typing as h
from multiprocessing import current_process as CurrentProcess

import json_any as json
from mpss_tools_36.constant.generic import REQUEST_CLOSE, REQUEST_STATUS, REQUEST_STOP
from mpss_tools_36.constant.process import MAIN_PROCESS_NAME
from mpss_tools_36.constant.wrapper import (
    REQUEST_ATTRIBUTE,
    REQUEST_ATTRIBUTES,
    REQUEST_CALL,
)
from mpss_tools_36.hint.wrapper import server_status_h
from mpss_tools_36.type.client.wrapper import client_t
from mpss_tools_36.type.line import line_t
from mpss_tools_36.type.server.generic import server_t as base_t


@d.dataclass(slots=True, repr=False, eq=False)
class server_t(base_t):
    object: h.Any = None
    # None default added because mpss_tools_36.type.server.generic.server_t has
    #     attributes with defaults.

    @property
    def status(self) -> server_status_h:
        """"""
        return self.name, type(self.object).__name__, self._thread is not None

    def __post_init__(self) -> None:
        """"""
        assert CurrentProcess().name == MAIN_PROCESS_NAME

        reserved = client_t.ReservedAttributes()
        in_object = set(dir(self.object))
        assert in_object.intersection(reserved).__len__() == 0, (
            sorted(in_object),
            reserved,
            sorted(in_object.intersection(reserved)),
        )

    def _Run(self) -> None:
        """"""
        active_lines = list(self._lines)  # Work on a copy.
        while active_lines.__len__() > 0:
            for request_line_end, answer_line_end, request in base_t.ActiveRequests(
                active_lines
            ):
                if isinstance(request, tuple):
                    request, attribute, *args = request
                    if (args.__len__() > 0) and isinstance(args[-1], dict):
                        args, kwargs = args[:-1], args[-1]
                    else:
                        kwargs = {}
                else:
                    attribute, args, kwargs = None, (), {}
                # assert isinstance(request, str)

                output, still_to_be_sent = None, True
                if request == REQUEST_CALL:
                    output = getattr(self.object, attribute)(*args, **kwargs)
                elif request == REQUEST_ATTRIBUTE:
                    output = getattr(self.object, attribute)
                elif request == REQUEST_ATTRIBUTES:
                    output = tuple(
                        _
                        for _ in dir(self.object)
                        if not isinstance(getattr(self.object, _), h.Callable)
                    )
                elif request == REQUEST_STATUS:
                    answer_line_end.put(self.status)
                    still_to_be_sent = False
                elif request == REQUEST_CLOSE:
                    active_lines.remove(
                        line_t(request=request_line_end, answer=answer_line_end)
                    )
                    still_to_be_sent = False
                elif request == REQUEST_STOP:
                    active_lines.clear()
                    break
                else:
                    raise ValueError(
                        f'Unknown request "{request}" sent to '
                        f'data server "{self.name}".'
                    )

                if still_to_be_sent:
                    jsoned, issues = json.JsonStringOf(output)
                    if issues is None:
                        answer_line_end.put(jsoned)
                    else:
                        raise RuntimeError(
                            f"Un-jsonable object:\n{type(output).__name__}\n"
                            + "\n".join(issues)
                        )


"""
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.
"""
