"""Octen API synchronous client"""

import os
from typing import Optional
from .core.http_client import HTTPClient
from .resources.search import SearchResource
from .resources.embedding import EmbeddingResource
from .resources.chat import ChatResource
from .utils.constants import DEFAULT_BASE_URL, DEFAULT_TIMEOUT, DEFAULT_MAX_RETRIES


class Octen:
    """Octen API synchronous client

    Provides convenient access to the Octen API with search, embedding,
    and chat capabilities.

    Attributes:
        search: Search API resource
        embedding: Embedding API resource
        chat: Chat API resource

    Example:
        Basic usage::

            from octen import Octen

            # Using context manager (recommended)
            with Octen(api_key="your-api-key") as client:
                # Search
                response = client.search.search("Python programming", count=5)
                for result in response.results:
                    print(result['title'])

                # Create embedding
                embedding = client.embedding.create("Hello, world!")
                vector = embedding.get_first_embedding()

        Custom configuration::

            with Octen(
                api_key="your-api-key",
                base_url="https://api.octen.ai",
                timeout=60.0,
                max_retries=5
            ) as client:
                # Using custom timeout
                response = client.search.search(
                    "complex query",
                    timeout=120.0
                )

        Without context manager::

            client = Octen(api_key="your-api-key")
            try:
                response = client.search.search("query")
            finally:
                client.close()  # Ensure connection closed
    """

    def __init__(
        self,
        api_key: Optional[str] = None,
        base_url: str = DEFAULT_BASE_URL,
        timeout: float = DEFAULT_TIMEOUT,
        max_retries: int = DEFAULT_MAX_RETRIES,
        http2: bool = True,
    ):
        """Initialize Octen client

        Args:
            api_key: Octen API key. If not provided, reads from the
                ``OCTEN_API_KEY`` environment variable.
            base_url: API base URL (default: https://api.octen.ai)
            timeout: Default request timeout in seconds (default: 30.0)
            max_retries: Maximum number of retries (default: 3)
            http2: Whether to enable HTTP/2 (default: True)

        Raises:
            OctenAuthenticationError: if no api_key is provided and
                ``OCTEN_API_KEY`` is not set.
        """
        api_key = api_key or os.environ.get("OCTEN_API_KEY")
        if not api_key:
            from .core.exceptions import OctenAuthenticationError
            raise OctenAuthenticationError(
                "No API key provided. Pass api_key or set the OCTEN_API_KEY "
                "environment variable."
            )

        # Create HTTP client (core request layer)
        self._http_client = HTTPClient(
            base_url=base_url,
            api_key=api_key,
            timeout=timeout,
            max_retries=max_retries,
            http2=http2,
        )

        # Initialize resources (business layer)
        self.search = SearchResource(self._http_client)
        self.embedding = EmbeddingResource(self._http_client)
        self.chat = ChatResource(self._http_client)

    def close(self):
        """Close client and release connection pool resources

        Should be called manually when not using context manager.
        """
        self._http_client.close()

    def __enter__(self):
        """Support context manager protocol"""
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """Automatically close client when exiting context manager"""
        self.close()
        return False

    def __repr__(self) -> str:
        """Return string representation of client"""
        return f"Octen(base_url={self._http_client.base_url!r})"
