"""Main BeeL client."""

from typing import Optional
from beel_generated import ApiClient, Configuration, ApiException
from .resources import Invoices, Customers, Products, Series, Companies, Config


class BeeLError(Exception):
    """BeeL SDK error with optional HTTP status code."""
    
    def __init__(self, message: str, status_code: int = 0):
        super().__init__(message)
        self.status_code = status_code


class BeeL:
    """
    Main BeeL SDK client.
    Validates the API key on construction.
    
    Args:
        api_key: Your BeeL API key (starts with beel_sk_)
        base_url: Optional custom base URL (default: https://app.beel.es/api)
        skip_validation: Skip API key validation (default: False)
    
    Raises:
        BeeLError: If the API key is invalid or the API is unreachable
    
    Example:
        >>> client = BeeL('your-api-key')
        >>> invoices = client.invoices.list()
        
        >>> # With context manager
        >>> with BeeL('your-api-key') as client:
        ...     invoices = client.invoices.list()
    """
    
    def __init__(self, api_key: str, base_url: Optional[str] = None, skip_validation: bool = False):
        if not api_key:
            raise BeeLError("API key is required. Get yours at https://app.beel.es")

        config = Configuration()
        config.host = base_url or 'https://app.beel.es/api'
        config.access_token = api_key  # Bearer token auth
        
        self._api_client = ApiClient(config)
        
        # Initialize resource clients
        self.invoices = Invoices(self._api_client)
        self.customers = Customers(self._api_client)
        self.products = Products(self._api_client)
        self.series = Series(self._api_client)
        self.companies = Companies(self._api_client)
        self.config = Config(self._api_client)

        if not skip_validation:
            self.ping()
    
    def ping(self):
        """
        Validate the API key by making a lightweight request.
        
        Raises:
            BeeLError: If the API key is invalid or the API is unreachable
        """
        try:
            self.series.list()
        except ApiException as e:
            if e.status == 401:
                raise BeeLError(
                    "Invalid API key. Check your key at https://app.beel.es or contact support.",
                    status_code=401
                ) from e
            elif e.status == 403:
                raise BeeLError(
                    "API key doesn't have permission to access this resource.",
                    status_code=403
                ) from e
        except Exception as e:
            if 'ConnectionError' in type(e).__name__ or 'ConnectTimeout' in type(e).__name__:
                raise BeeLError(
                    f"Could not connect to BeeL API. Check your network connection or base URL."
                ) from e
            # Other errors - don't fail construction
    
    def get_api_client(self) -> ApiClient:
        """Get the underlying ApiClient for advanced use cases."""
        return self._api_client
    
    def __enter__(self):
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        if self._api_client:
            self._api_client.close()
