"""Detection state with dynamic lazy-loading providers."""

from typing import Any, Callable
from ..core.environment import Environment


class DetectionState:
    """Shared state for detectors with lazy-loading cache.

    Detectors can provide expensive operations that are cached
    and shared with subsequent detectors.
    """

    def __init__(self, env: Environment) -> None:
        """Initialize with environment data.

        Args:
            env: Environment data gathered from system
        """
        self.env = env
        self._cache: dict[str, Any] = {}  # Any is fine here - cache holds various types
        self.contexts: dict[
            str, Any
        ] = {}  # Any is fine - contexts have varied metadata
        self.flags: set[str] = set()

    def get(
        self, key: str, provider: Callable[[Environment], Any] | None = None
    ) -> Any:
        """Get or compute a lazy value.

        Args:
            key: Cache key to retrieve
            provider: Optional function to compute value if not cached

        Returns:
            Cached or computed value, None if not available

        Example:
            # First detector provides expensive operation
            content = state.get('pane_content', lambda env: env.get_pane_content())

            # Later detectors just use cached value
            content = state.get('pane_content')
        """
        if key not in self._cache:
            if provider:
                self._cache[key] = provider(self.env)
            else:
                return None
        return self._cache[key]

    def set(self, key: str, value: Any) -> None:
        """Explicitly set a cached value.

        Args:
            key: Cache key
            value: Value to cache
        """
        self._cache[key] = value

    def has(self, key: str) -> bool:
        """Check if a key exists in cache.

        Args:
            key: Cache key to check

        Returns:
            True if key is cached
        """
        return key in self._cache
