"""API Key models for the Danube SDK."""

from typing import Any, Dict, List, Optional

from pydantic import BaseModel


class APIKeyPermissions(BaseModel):
    """Permissions for an API key."""

    allowed_services: Optional[List[str]] = None
    allowed_tools: Optional[List[str]] = None
    max_spend_per_call_cents: Optional[int] = None
    max_spend_per_day_cents: Optional[int] = None

    model_config = {"extra": "ignore"}


class APIKeyResponse(BaseModel):
    """An API key (without the secret)."""

    id: str = ""
    key_prefix: str = ""
    name: str = ""
    created_at: Optional[str] = None
    last_used: Optional[str] = None
    permissions: Optional[APIKeyPermissions] = None

    model_config = {"extra": "ignore"}

    @classmethod
    def from_api_response(cls, data: Dict[str, Any]) -> "APIKeyResponse":
        perms = data.get("permissions")
        return cls(
            id=data.get("id", ""),
            key_prefix=data.get("key_prefix", ""),
            name=data.get("name", ""),
            created_at=data.get("created_at"),
            last_used=data.get("last_used"),
            permissions=APIKeyPermissions(**perms) if perms else None,
        )


class APIKeyWithSecret(APIKeyResponse):
    """An API key including the plaintext secret (returned only on create/rotate)."""

    key: str = ""

    @classmethod
    def from_api_response(cls, data: Dict[str, Any]) -> "APIKeyWithSecret":
        perms = data.get("permissions")
        return cls(
            id=data.get("id", ""),
            key=data.get("key", ""),
            key_prefix=data.get("key_prefix", ""),
            name=data.get("name", ""),
            created_at=data.get("created_at"),
            last_used=data.get("last_used"),
            permissions=APIKeyPermissions(**perms) if perms else None,
        )


class SpendingLimits(BaseModel):
    """User's USDC spending limit settings."""

    id: str = ""
    user_id: str = ""
    max_per_call_atomic: int = 5_000_000
    daily_limit_atomic: Optional[int] = None
    created_at: Optional[str] = None
    updated_at: Optional[str] = None

    model_config = {"extra": "ignore"}

    @classmethod
    def from_api_response(cls, data: Dict[str, Any]) -> "SpendingLimits":
        return cls(
            id=data.get("id", ""),
            user_id=data.get("user_id", ""),
            max_per_call_atomic=data.get("max_per_call_atomic", 5_000_000),
            daily_limit_atomic=data.get("daily_limit_atomic"),
            created_at=data.get("created_at"),
            updated_at=data.get("updated_at"),
        )
