"""
AgniPod SDK — API Key Management
===================================

Usage::

    from agnipod import AgniPod

    client = AgniPod(api_key="agni_...")   # session-auth key for key management

    # Create a new API key
    created = client.keys.create(name="Production")
    print(created.key)   # agni_live_... — shown once, save it!

    # List all keys
    for k in client.keys.list():
        print(k.id, k.name, k.is_active)

    # Revoke a key
    client.keys.revoke(key_id=7)
"""

from __future__ import annotations
from typing import Optional

from ._client import HttpClient
from ._types import ApiKey, ApiKeyCreated, ApiKeyList


class Keys:
    """Namespace for ``/keys`` API key management operations.

    Note: These endpoints use session-based authentication in addition to
    the API key. When calling from the SDK, the API key is sent as the
    auth credential.
    """

    _PREFIX = "/keys"

    def __init__(self, client: HttpClient):
        self._client = client

    def create(self, *, name: str) -> ApiKeyCreated:
        """Create a new API key.

        The full key value is only returned once — save it immediately.

        Parameters
        ----------
        name : str
            A label for this key (e.g. ``"Production"``, ``"Test"``).

        Returns
        -------
        ApiKeyCreated
            Has ``.key`` (full secret), ``.id``, ``.key_prefix``.
        """
        data = self._client.post(self._PREFIX, json_data={"name": name})
        return ApiKeyCreated(data)

    def list(
        self,
        *,
        limit: int = 50,
        include_revoked: bool = False,
    ) -> ApiKeyList:
        """List API keys.

        Parameters
        ----------
        limit : int
            Max number of keys to return (default 50).
        include_revoked : bool
            Include revoked keys (default False).

        Returns
        -------
        ApiKeyList
            Iterable of ``ApiKey`` objects.
        """
        data = self._client.get(self._PREFIX, params={
            "limit": limit,
            "include_revoked": include_revoked,
        })
        return ApiKeyList(data)

    def get(self, key_id: int) -> ApiKey:
        """Get details of a specific API key.

        Parameters
        ----------
        key_id : int

        Returns
        -------
        ApiKey
        """
        data = self._client.get(f"{self._PREFIX}/{key_id}")
        key_data = data.get("key", data)
        return ApiKey(key_data)

    def revoke(self, key_id: int) -> bool:
        """Revoke (delete) an API key. This is irreversible.

        Parameters
        ----------
        key_id : int

        Returns
        -------
        bool
            ``True`` if the key was successfully revoked.
        """
        data = self._client.delete(f"{self._PREFIX}/{key_id}")
        return bool(data.get("success", True))
