"""
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 multiprocessing as prll
import os as o
import tempfile as tmpf
import time
import types as t
import typing as h
from multiprocessing.managers import BaseManager as base_t
from pathlib import Path as path_t
from threading import Thread as thread_t

from mpss_tools_36.constant.process import MAIN_PROCESS_NAME
from mpss_tools_36.extension.data_class import NO_CHOICE
from mpss_tools_36.extension.multiprocessing_manager import (
    ProxyWithAttributes,
    create,
    serve_client,
)

LOCAL_HOST = "127.0.0.1"
PROXY_CONNEXION_PORT = "PROXY_CONNEXION_PORT"
PROXY_CONNEXION_EXTENSION = ".connexion"
SHARING_PROXY = "SharingProxy"


@d.dataclass(init=False, slots=True, repr=False, eq=False)
class sharer_t(base_t):
    _instances: h.ClassVar[dict[str, h.Any]] = {}

    thread: thread_t | None = NO_CHOICE(None)

    @classmethod
    def _AddInstance(cls, instance: h.Any, name: str, /) -> None:
        """"""
        assert prll.current_process().name == MAIN_PROCESS_NAME
        assert name not in cls._instances
        cls._instances[name] = instance

    @classmethod
    def _GetInstance(cls, name: str, /) -> h.Any:
        """"""
        return cls._instances[name]

    def __init__(self, *args, **kwargs) -> None:
        """"""
        cls = self.__class__
        cls.register(
            SHARING_PROXY, callable=cls._GetInstance, proxytype=ProxyWithAttributes
        )
        base_t.__init__(self, *args, **kwargs)
        self.thread = None  # Because default __init__ is not used.

    @classmethod
    def New(cls, /, *, instance: h.Any = None, name: str | None = None) -> h.Self:
        """"""
        assert prll.current_process().name == MAIN_PROCESS_NAME

        if instance is not None:
            assert name is not None
            cls._AddInstance(instance, name)

        return cls(address=(LOCAL_HOST, 0))

    def Add(self, instance: h.Any, name: str, /) -> None:
        """"""
        assert prll.current_process().name == MAIN_PROCESS_NAME
        self.__class__._AddInstance(instance, name)

    def Start(self) -> None:
        """"""
        assert prll.current_process().name == MAIN_PROCESS_NAME

        server = self.get_server()
        server.serve_client = t.MethodType(serve_client, server)
        server.create = t.MethodType(create, server)

        self.thread = thread_t(target=server.serve_forever, daemon=True)
        self.thread.start()

        port = str(server.address[1])
        if prll.get_start_method() != "spawn":
            o.environ[PROXY_CONNEXION_PORT] = port
        else:
            # With the "spawn" start method, changes to os.environ are not inherited.
            with tmpf.NamedTemporaryFile(
                prefix=f"{PROXY_CONNEXION_PORT}-{time.time_ns()}-",
                suffix=PROXY_CONNEXION_EXTENSION,
                delete=False,
                mode="w",
            ) as accessor:
                accessor.write(port)

    @classmethod
    def Address(cls) -> tuple[str, int]:
        """"""
        if prll.get_start_method() != "spawn":
            return LOCAL_HOST, int(o.environ[PROXY_CONNEXION_PORT])

        return LOCAL_HOST, int(cls.PathOfPort().read_text())

    @staticmethod
    def PathOfPort() -> path_t:
        """"""
        paths = sorted(
            path_t(tmpf.gettempdir()).glob(
                f"{PROXY_CONNEXION_PORT}-*-*{PROXY_CONNEXION_EXTENSION}"
            )
        )
        assert paths.__len__() > 0

        return paths[-1]

    @classmethod
    def SharedInstanceProxy(cls, name: str, /) -> h.Any:
        """"""
        sharer = cls(address=cls.Address())
        sharer.connect()

        return getattr(sharer, SHARING_PROXY)(name)

    def Stop(self) -> None:
        """"""
        assert prll.current_process().name == MAIN_PROCESS_NAME

        cls = self.__class__

        cls._instances.clear()
        self.thread = None

        if prll.get_start_method() != "spawn":
            # del o.environ[PROXY_CONNEXION_PORT]  # Raises KeyError(?)
            o.environ[PROXY_CONNEXION_PORT] = ""
        else:
            cls.PathOfPort().unlink()


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