"""Lithio API Client."""

from typing import Optional, Dict, Any
import os
import httpx
from .types import AddResponse, SearchResponse


class Client:
    """Client for interacting with the Lithio API.
    
    Usage:
        ```python
        from lithio import Client
        
        client = Client(
            api_key="your-api-key",
            base_url="https://api.example.com"
        )
        
        # Add a query
        response = client.add(query="example query", space="my-space")
        
        # Search
        results = client.search(
            query="search query",
            limit=10,
            match_threshold=0.5
        )
        ```
    """
    
    def __init__(
        self,
        api_key: Optional[str] = None,
        base_url: str = "https://api.lithio.dev",
        timeout: float = 30.0,
    ):
        """Initialize the Lithio client.
        
        Args:
            api_key: Your Lithio API key. If not provided, will use LITHIO_API_KEY env variable.
            base_url: Base URL for the API (default: http://localhost:8000)
            timeout: Request timeout in seconds (default: 30.0)
        """
        self.api_key = api_key or os.getenv("LITHIO_API_KEY")
        if not self.api_key:
            raise ValueError("api_key must be provided or LITHIO_API_KEY environment variable must be set")
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout
        self._client = httpx.Client(
            base_url=self.base_url,
            timeout=timeout,
            headers={
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json",
            },
        )
    
    def __enter__(self):
        """Context manager entry."""
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        """Context manager exit."""
        self.close()
    
    def close(self):
        """Close the HTTP client."""
        self._client.close()
    
    def add(
        self,
        query: str,
        space: Optional[str] = None,
        properties: Optional[Dict[str, Any]] = None,
    ) -> AddResponse:
        """Add a query to the system.
        
        Args:
            query: The query string to add
            space: Optional space identifier
            properties: Optional properties to include
            
        Returns:
            AddResponse containing the request status
            
        Raises:
            httpx.HTTPError: If the request fails
        """
        payload = {
            "query": query,
        }
        
        if space is not None:
            payload["space"] = space
        
        if properties:
            payload["properties"] = properties
        
        response = self._client.post("/add", json=payload)
        response.raise_for_status()
        return AddResponse(**response.json())
    
    def search(
        self,
        query: str,
        limit: Optional[int] = None,
        match_threshold: Optional[float] = None,
        rerank_alpha: Optional[float] = None,
        space: Optional[str] = None,
        properties: Optional[Dict[str, Any]] = None,
    ) -> SearchResponse:
        """Search for results.
        
        Args:
            query: The search query string
            limit: Maximum number of results to return (default: 5)
            match_threshold: Minimum match threshold (default: 0.4)
            rerank_alpha: Reranking alpha parameter (default: 0.2)
            space: Optional space identifier
            properties: Optional properties to include
            
        Returns:
            SearchResponse containing the search results
            
        Raises:
            httpx.HTTPError: If the request fails
        """
        payload = {
            "query": query,
        }
        
        if limit is not None:
            payload["limit"] = limit
        
        if match_threshold is not None:
            payload["match_threshold"] = match_threshold
        
        if rerank_alpha is not None:
            payload["rerank_alpha"] = rerank_alpha
        
        if space is not None:
            payload["space"] = space
        
        if properties:
            payload["properties"] = properties
        
        response = self._client.post("/search", json=payload)
        response.raise_for_status()
        return SearchResponse(**response.json())

