"""Main Vuzo client class."""

import os
import requests
from typing import Optional
from .exceptions import (
    AuthenticationError,
    InsufficientCreditsError,
    RateLimitError,
    InvalidRequestError,
    APIError,
)


class Vuzo:
    """
    Main client for Vuzo API.
    
    Usage:
        client = Vuzo("vz-sk_your_key_here")
        response = client.chat.complete("gpt-4o-mini", "Hello!")
    """
    
    def __init__(
        self,
        api_key: Optional[str] = None,
        base_url: str = "https://vuzo-api.onrender.com/v1"
    ):
        """
        Initialize Vuzo client.
        
        Args:
            api_key: Vuzo API key. If not provided, reads from VUZO_API_KEY env var.
            base_url: API base URL. Defaults to production.
        """
        self.api_key = api_key or os.getenv("VUZO_API_KEY")
        if not self.api_key:
            raise AuthenticationError(
                "API key is required. Pass it as argument or set VUZO_API_KEY environment variable."
            )
        
        self.base_url = base_url.rstrip("/")
        self._session = requests.Session()
        self._session.headers.update({
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json",
        })
        
        # Initialize sub-clients
        from .chat import ChatCompletions
        from .models import Models
        from .usage import Usage
        from .billing import Billing
        from .api_keys import APIKeys
        
        self.chat = ChatCompletions(self)
        self.models = Models(self)
        self.usage = Usage(self)
        self.billing = Billing(self)
        self.api_keys = APIKeys(self)
    
    def _request(self, method: str, endpoint: str, **kwargs):
        """Make HTTP request and handle errors."""
        url = f"{self.base_url}{endpoint}"
        
        try:
            response = self._session.request(method, url, **kwargs)
            
            # Handle HTTP errors
            if response.status_code == 401:
                raise AuthenticationError("Invalid API key")
            elif response.status_code == 402:
                raise InsufficientCreditsError(
                    response.json().get("detail", "Insufficient credits")
                )
            elif response.status_code == 429:
                raise RateLimitError("Rate limit exceeded")
            elif response.status_code == 400:
                raise InvalidRequestError(
                    response.json().get("detail", "Invalid request")
                )
            elif response.status_code >= 500:
                raise APIError(
                    f"Server error: {response.status_code}",
                    status_code=response.status_code
                )
            elif not response.ok:
                raise APIError(
                    f"API error: {response.status_code}",
                    status_code=response.status_code,
                    response=response.json() if response.text else None
                )
            
            return response
            
        except requests.RequestException as e:
            raise APIError(f"Request failed: {str(e)}")
    
    def _get(self, endpoint: str, params: dict = None):
        """Make GET request."""
        return self._request("GET", endpoint, params=params)
    
    def _post(self, endpoint: str, json: dict = None):
        """Make POST request."""
        return self._request("POST", endpoint, json=json)
    
    def _delete(self, endpoint: str):
        """Make DELETE request."""
        return self._request("DELETE", endpoint)
