import requests
from typing import Dict, Optional, Any
from .exceptions import AISupportAuthError, AISupportRateLimitError, AISupportAPIError
from .models import InquiryResponse, UsageStats

class AISupport:
    """Client for interacting with the AI Support API."""
    
    def __init__(
        self,
        api_key: str,
        project_id: str,
        base_url: str = "https://api.aisupport.com/v1"
    ):
        """Initialize the AI Support client.
        
        Args:
            api_key: Your API key
            project_id: Your project ID
            base_url: Base URL for the API (optional)
        """
        self.api_key = api_key
        self.project_id = project_id
        self.base_url = base_url.rstrip('/')
        self.session = requests.Session()
        self.session.headers.update({
            "Authorization": f"Bearer {api_key}",
            "X-Project-ID": project_id,
            "Content-Type": "application/json",
        })

    def _handle_response(self, response: requests.Response) -> Dict[str, Any]:
        """Handle API response and raise appropriate exceptions."""
        if response.status_code == 401:
            raise AISupportAuthError("Invalid API key")
        elif response.status_code == 429:
            raise AISupportRateLimitError("Rate limit exceeded")
        elif response.status_code >= 400:
            raise AISupportAPIError(f"API error: {response.text}")
        
        return response.json()

    def handle_inquiry(
        self,
        message: str,
        inquiry_type: str = "chat",
        context: Optional[Dict[str, Any]] = None
    ) -> InquiryResponse:
        """Handle a customer inquiry.
        
        Args:
            message: The customer's message
            inquiry_type: Type of inquiry ("chat", "voice", or "email")
            context: Additional context for the AI
            
        Returns:
            InquiryResponse object containing the AI's response
        """
        url = f"{self.base_url}/inquiries"
        data = {
            "message": message,
            "type": inquiry_type,
            "context": context or {}
        }
        
        response = self.session.post(url, json=data)
        result = self._handle_response(response)
        
        return InquiryResponse(**result)

    def get_usage(self) -> UsageStats:
        """Get current API usage statistics.
        
        Returns:
            UsageStats object containing usage information
        """
        url = f"{self.base_url}/usage"
        response = self.session.get(url)
        result = self._handle_response(response)
        
        return UsageStats(**result)