from __future__ import annotations
from typing import Any, cast, TYPE_CHECKING
from zempy.zosapi.tools.general.adapters.quick_focus import QuickFocus
from zempy.zosapi.core.interop import run_native, ensure_not_none
from zempy.bridge import zemax_exceptions as _exc
from zempy.zosapi.tools.protocols.system_tools import ISystemTools

if TYPE_CHECKING:
    from zempy.zosapi.core.IZosapi import IZosapi
    from zempy.zosapi.tools.general.protocols.quick_focus import IQuickFocus


class SystemTools(ISystemTools):
    """Concrete adapter over native ZOSAPI.Tools.IOpticalSystemTools."""
    __slots__ = ("_zosapi", "_n")

    def __init__(self, zosapi: IZosapi, native_tools: Any) -> None:
        self._zosapi = zosapi
        self._n = native_tools
        ensure_not_none(self._n, what="IOpticalSystemTools", exc_type=_exc.ZemaxSystemError)

    def _ensure_native(self) -> None:
        ensure_not_none(self._n, what="IOpticalSystemTools", exc_type=_exc.ZemaxSystemError)

    def open_quick_focus(self) -> IQuickFocus:
        native_qf = run_native(
            "Tools.OpenQuickFocus()",
            lambda: self._n.OpenQuickFocus(),
            ensure=self._ensure_native,
        )
        return cast(IQuickFocus, cast(object, QuickFocus(native_qf, self._zosapi)))

    def remove_all_variables(self) -> bool:
        return bool(run_native(
            "Tools.RemoveAllVariables()",
            lambda: getattr(self._n, "RemoveAllVariables")(),
            ensure=self._ensure_native,
        ))

    @property
    def raw(self) -> Any:
        return self._n