"""Protected module containing the ECMSystemSync namespace class."""

from __future__ import annotations

from typing import TYPE_CHECKING

from ecmind_blue_client.ecm.definition import ECMDefinition
from ecmind_blue_client.rpc._jobs import Jobs

if TYPE_CHECKING:
    from ecmind_blue_client.ecm.synchron._ecm_sync import ECMSync


class ECMSystemSync:  # pylint: disable=too-few-public-methods
    """Synchronous system-level operations namespace.

    Provides access to server-wide metadata that is not tied to individual DMS objects.
    Accessed via ``ecm.system`` on an ``ECMSync`` instance.
    """

    def __init__(self, ecm: "ECMSync") -> None:
        """Initialize the system namespace.

        Args:
            ecm: The parent ``ECMSync`` instance used to execute server requests.
        """
        self._ecm = ecm
        self._definition_cache: ECMDefinition | None = None

    def definition(self, *, force_reload: bool = False) -> ECMDefinition:
        """Return the parsed ECM object definition.

        Retrieves the asobjdef XML from the server via ``dms.GetObjDef`` on the first
        call and caches the result.  Subsequent calls return the cached instance.

        Args:
            force_reload: If ``True``, discard the cached definition and fetch it
                from the server again.  Defaults to ``False``.

        Returns:
            The parsed ``ECMDefinition`` containing all cabinet, object, and field
            definitions for the connected server.
        """
        if self._definition_cache is None or force_reload:
            result = self._ecm.execute(Jobs.DMS_GETOBJDEF, Flags=0)
            self._definition_cache = ECMDefinition(result.files[0].bytes())
        return self._definition_cache
