"""Simple application store for shared state.

This module provides a minimal store that holds:
- API credentials (read-only config)
- Shared ApiClient instance (lazy initialization)
- Agent cache for cross-screen sharing

This replaces the previous ELM-style architecture with Textual's
recommended "App as Store" pattern - simple and direct.
"""

from alloy_runtime_sdk.api_client.client import ApiClient
from alloy_runtime_types.dtos.agents import AgentSummary


class AppStore:
    """Simple app-wide store for shared state.

    Usage:
        store = AppStore(api_url="...", api_key="...")
        client = await store.get_client()

    Screens access via self.app.store (Textual's recommended pattern).
    """

    def __init__(self, api_url: str, api_key: str) -> None:
        """Initialize the store.

        Args:
            api_url: Base URL for the API server
            api_key: API key for authentication
        """
        self.api_url = api_url.rstrip("/")
        self.api_key = api_key
        self._client: ApiClient | None = None
        self._client_entered: bool = False

        # Cross-screen cache for agent picker in chat
        self.agent_cache: list[AgentSummary] = []

    async def get_client(self) -> ApiClient:
        """Get the shared server client instance.

        Creates and connects on first use, reuses thereafter.

        Returns:
            Connected ApiClient instance

        Raises:
            Exception: If connection fails
        """
        if self._client is None:
            self._client = ApiClient(
                base_url=self.api_url,
                api_key=self.api_key,
                timeout=30.0,
            )

        if not self._client_entered:
            await self._client.__aenter__()
            self._client_entered = True

        return self._client

    async def close(self) -> None:
        """Close the client connection.

        Should be called when the application exits.
        """
        if self._client and self._client_entered:
            await self._client.__aexit__(None, None, None)
            self._client_entered = False
            self._client = None
