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

import json_any as json
from mpss_tools_36.constant.data import (
    DELETION_DONE,
    REQUEST_CHECK,
    REQUEST_DELETE,
    REQUEST_GET,
    REQUEST_SET,
    REQUEST_SIZE,
    STORAGE_DONE,
)
from mpss_tools_36.constant.generic import REQUEST_STATUS
from mpss_tools_36.hint.data import server_status_h
from mpss_tools_36.type.line import line_end_t
from mpss_tools_36.type.server.data import server_t


@d.dataclass(slots=True, repr=False, eq=False)
class client_t:
    @classmethod
    def New(
        cls,
        *,
        server: server_t | None = None,
        request_line_end: line_end_t | None = None,
        answer_line_end: line_end_t | None = None,
    ) -> h.Self:
        """"""
        if server is None:
            return client_remote_t(
                request_line_end=request_line_end, answer_line_end=answer_line_end
            )
        return client_direct_t(server=server)


@d.dataclass(slots=True, repr=False, eq=False)
class client_direct_t(client_t):
    server: server_t

    def RequestedData(self, *names) -> h.Any | tuple[h.Any, ...]:
        """"""
        return self.server.RequestedData(*names)

    def Send(self, /, **data) -> None:
        """"""
        self.server.Store(**data)

    def RequestDeletion(self, *names) -> None:
        """"""
        self.server.Delete(*names)

    def ServerHasData(self, *names) -> bool | tuple[bool, ...]:
        """"""
        return self.server.Has(*names)

    def SizeOfServer(self) -> int:
        """"""
        return self.server.size

    def StatusOfServer(self) -> server_status_h:
        """"""
        return self.server.status


@d.dataclass(slots=True, repr=False, eq=False)
class client_remote_t(client_t):
    request_line_end: line_end_t
    answer_line_end: line_end_t

    def RequestedData(self, *names) -> h.Any | tuple[h.Any, ...]:
        """"""
        if names.__len__() == 0:
            request = REQUEST_GET
        else:
            request = (REQUEST_GET, *names)
        self.request_line_end.put(request)

        jsoned = self.answer_line_end.get()
        un_jsoned, issues = json.ObjectFromJsonString(jsoned)

        if issues is None:
            return un_jsoned

        raise RuntimeError(f"Un-de-jsonable object:\n{jsoned}\n" + "\n".join(issues))

    def Send(self, /, **data) -> None:
        """"""
        jsoned, issues = json.JsonStringOf(data)
        if issues is None:
            self.request_line_end.put((REQUEST_SET, jsoned))
        else:
            raise RuntimeError(f"Un-jsonable object:\n{data}\n" + "\n".join(issues))

        # Wait for setting confirmation for synchronization purposes. Thus, it will not
        # be possible to set again the same element before the current storage is
        # effective.
        acknowledgment = self.answer_line_end.get()
        if acknowledgment != STORAGE_DONE:
            raise RuntimeError(
                f"Unexpected storage acknowledgment received: {acknowledgment}"
            )

    def RequestDeletion(self, *names) -> None:
        """"""
        self.request_line_end.put((REQUEST_DELETE, *names))

        # Wait for deletion confirmation for synchronization purposes. Thus, the server
        # will not confirm the presence of in-the-course-of-deletion data.
        acknowledgment = self.answer_line_end.get()
        if acknowledgment != DELETION_DONE:
            raise RuntimeError(
                f"Unexpected deletion acknowledgment received: {acknowledgment}"
            )

    def ServerHasData(self, *names) -> bool | tuple[bool, ...]:
        """"""
        if names.__len__() == 0:
            request = REQUEST_CHECK
        else:
            request = (REQUEST_CHECK, *names)
        self.request_line_end.put(request)

        return self.answer_line_end.get()

    def SizeOfServer(self) -> int:
        """"""
        self.request_line_end.put(REQUEST_SIZE)
        return self.answer_line_end.get()

    def StatusOfServer(self) -> server_status_h:
        """"""
        self.request_line_end.put(REQUEST_STATUS)
        return self.answer_line_end.get()


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