import requests
from typing import Dict, Any, Optional, Union, List
from requests.exceptions import RequestException
from adxp_sdk.auth import BaseCredentials
from adxp_sdk.base import BaseClient


class ApiKeyClient(BaseClient):
    """
    API Key Client for managing API keys (creation, retrieval, update, deletion).

    This client provides functionality for managing API keys used for accessing
    different gateway types (model, agent, mcp).

    How to use:
        >>> from adxp_sdk.auth import TokenCredentials
        >>> from adxp_sdk.apikey import ApiKeyClient
        >>> 
        >>> # Initialize client with credentials
        >>> credentials = TokenCredentials(
        ...     base_url="https://aip.sktai.io",
        ...     username="user",
        ...     password="pw",
        ...     client_id="cid"
        ... )
        >>> client = ApiKeyClient(credentials)
        >>> 
        >>> # List all API keys
        >>> apikeys = client.list_apikeys(page=1, size=10)
        >>> 
        >>> # Create a new API key
        >>> new_key = client.create_apikey({
        ...     "gateway_type": "model",
        ...     "is_master": True,
        ...     "project_id": "project-uuid}"
        ... })
        >>> 
        >>> # Update an API key
        >>> updated = client.update_apikey("api_key_id", {"is_master": False})
        >>> 
        >>> # Delete an API key
        >>> client.delete_apikey("api_key_id")
    """

    def __init__(self, credentials: BaseCredentials):
        """
        Initialize the ApiKeyClient.

        Args:
            credentials: Authentication credentials (BaseCredentials)
        """
        super().__init__(credentials)

    def list_apikeys(self, page: int = 1, size: int = 10, sort: Optional[str] = None, 
                    filter: Optional[str] = None, search: Optional[str] = None, fetch_mode: Optional[str] = "lazy") -> Union[Dict[str, Any], List[Any], Any]:
        """
        List API Keys via GET /api/v1/apikeys
        
        Args:
            page: Page number
            size: Page size
            sort: Sort condition
            filter: Filter condition
            search: Search keyword
            
        Returns:
            dict: The API response containing list of API keys
        """
        try:
            params = {
                "page": page,
                "size": size,
                "sort": sort,
                "filter": filter,
                "search": search,
                "fetch_mode": fetch_mode,
            }
            params = {k: v for k, v in params.items() if v is not None}
            return self._make_request(
                method="GET",
                endpoint="api/v1/apikeys",
                params=params,
            )
        except RequestException as e:
            raise Exception(f"Failed to list API keys: {str(e)}")

    def create_apikey(self, data: Dict[str, Any]) -> Union[Dict[str, Any], List[Any], Any]:
        """
        Create API Key via POST /api/v1/apikeys
        
        Args:
            data: API key creation data
            
        Required fields:
            - gateway_type: Gateway type (model, agent, mcp)
            - is_master: Whether this is a master key
            - project_id: Project ID
            - tag: Tag (list of strings)
            - serving_id: Serving ID array (list of strings)
                Note: serving_id is only required when is_master is False.
                For master keys, serving_id should be None.
            
        Returns:
            dict: The API response
        """
        try:
            return self._make_request(
                method="POST",
                endpoint="api/v1/apikeys",
                json_data=data,
            )
        except RequestException as e:
            raise Exception(f"Failed to create API key: {str(e)}")

    def update_apikey(self, api_key_id: str, data: Dict[str, Any]) -> Union[Dict[str, Any], List[Any], Any]:
        """
        Update API Key via PUT /api/v1/apikeys/{api_key_id}
        
        Args:
            api_key_id: API Key ID
            data: Update data
            
        Returns:
            dict: The API response
        """
        try:
            return self._make_request(
                method="PUT",
                endpoint=f"api/v1/apikeys/{api_key_id}",
                json_data=data
            )
        except RequestException as e:
            raise Exception(f"Failed to update API key: {str(e)}")
    
    def delete_apikey(self, api_key_id: str) -> Union[Dict[str, Any], List[Any], Any]:
        """
        Delete API Key via DELETE /api/v1/apikeys/{api_key_id}
        
        Args:
            api_key_id: API Key ID
            
        Returns:
            dict: The API response
        """
        try:
            return self._make_request(
                method="DELETE",
                endpoint=f"api/v1/apikeys/{api_key_id}"
            )
        except RequestException as e:
            raise Exception(f"Failed to delete API key: {str(e)}")

