"""Main Worqhat client."""

from typing import Optional

from .http_client import HTTPClient
from .resources import DatabaseResource, FlowsResource, StorageResource


class Worqhat:
    """
    Worqhat API client.

    Example:
        >>> from worqhat import Worqhat
        >>> client = Worqhat(api_key="your-api-key")
        >>> response = client.db.execute_query(query="SELECT * FROM users")
        >>> print(response["data"])
    """

    def __init__(
        self,
        api_key: Optional[str] = None,
        base_url: str = "https://api.worqhat.app",
        target: Optional[str] = None,
        timeout: int = 60,
    ):
        """
        Initialize the Worqhat client.

        Args:
            api_key: API key for authentication. Defaults to WORQHAT_API_KEY environment variable.
            base_url: Base URL for the API (default: https://api.worqhat.app).
            target: Backend target ('app' or 'fyi').
            timeout: Request timeout in seconds (default: 60).

        Raises:
            AuthenticationError: If no API key is provided.
        """
        self._http_client = HTTPClient(
            api_key=api_key, base_url=base_url, target=target, timeout=timeout
        )

        # Initialize resources
        self.db = DatabaseResource(self._http_client)
        self.flows = FlowsResource(self._http_client)
        self.storage = StorageResource(self._http_client)

    def close(self) -> None:
        """Close the HTTP client session."""
        self._http_client.close()

    def __enter__(self) -> "Worqhat":
        """Context manager entry."""
        return self

    def __exit__(self, *args: object) -> None:
        """Context manager exit."""
        self.close()

    def __repr__(self) -> str:
        """String representation."""
        return f"Worqhat(base_url='{self._http_client.base_url}')"
