from __future__ import annotations
from typing import Any, Optional, TYPE_CHECKING
from zempy.zosapi.tools.general.protocols.quick_focus import QuickFocusSettings, IQuickFocus
from zempy.zosapi.tools.general.enums.quick_focus_criterion import QuickFocusCriterion
from zempy.zosapi.tools.enums.run_status import RunStatus
from zempy.zosapi.tools.protocols.system_tool import RunResult

if TYPE_CHECKING:
    from zempy.zosapi.core.IZosapi import IZosapi


class QuickFocus(IQuickFocus):
    """Adapter wrapping ZOSAPI.Tools.General.IQuickFocus."""

    def __init__(self,  native: Any, zosapi: IZosapi | None = None):
        self._n = native  # native ZOSAPI.Tools.General.IQuickFocus
        self._zosapi = zosapi if zosapi is not None else getattr(native, "zosapi", None)

    def __enter__(self) -> "QuickFocus":
        return self

    def __exit__(self, exc_type, exc_val, exc_tb) -> None:
        try:
            self.close()
        except Exception:
            pass


    def close(self) -> bool:
        return bool(self._n.Close())

    def run_and_wait_for_completion(self) -> bool:
        return bool(self._n.RunAndWaitForCompletion())


    def run_with_settings(
        self,
        settings: Optional[QuickFocusSettings] = None,
        timeout_s: Optional[float] = None
    ) -> RunResult:
        if settings is None:
            settings = QuickFocusSettings(
                criterion=QuickFocusCriterion.SPOT_SIZE_RADIAL,
                use_centroid=True,
            )

        self.criterion = settings.criterion
        self.use_centroid = settings.use_centroid

        if timeout_s is not None:
            rs_native = self._n.RunAndWaitWithTimeout(float(timeout_s))
            status = RunStatus.from_native(self._zosapi, rs_native)  # <- use _zosapi
            return RunResult(status)

        ok = bool(self._n.RunAndWaitForCompletion())
        return RunResult(RunStatus.COMPLETED if ok else RunStatus.FAILED_TO_START)

    @property
    def use_centroid(self) -> bool:
        return bool(self._n.UseCentroid)

    @use_centroid.setter
    def use_centroid(self, value: bool) -> None:
        self._n.UseCentroid = bool(value)

    @property
    def criterion(self) -> QuickFocusCriterion:
        # if your native object doesn't expose .zosapi, pass it in via __init__
        return QuickFocusCriterion.from_native(self._zosapi, self._n.Criterion)

    @criterion.setter
    def criterion(self, value: QuickFocusCriterion) -> None:
        self._n.Criterion = QuickFocusCriterion.to_native(self._zosapi, value)