# coding: utf-8

"""
    Mixpeek API

    This is the Mixpeek API, providing access to various endpoints for data processing and retrieval.

    The version of the OpenAPI document: 0.81.1
    Contact: info@mixpeek.com
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501


from __future__ import annotations
import pprint
import re  # noqa: F401
import json

from datetime import datetime
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from mixpeek.models.api_key_type import APIKeyType
from mixpeek.models.key_status import KeyStatus
from mixpeek.models.permission import Permission
from mixpeek.models.resource_scope_output import ResourceScopeOutput
from typing import Optional, Set
from typing_extensions import Self

class RetrieverAPIKeyResponse(BaseModel):
    """
    Response model including the plaintext key (shown only once).  This response is returned immediately after key creation. The plaintext key is shown ONLY in this response and cannot be retrieved later. Users should save the key immediately for secure storage.  Security note:     The `key` field contains the plaintext secret and should be:     - Stored securely by the user (environment variables, secrets manager)     - Never committed to version control     - Never logged or exposed in error messages     - Rotated/revoked if accidentally exposed
    """ # noqa: E501
    key_id: Optional[StrictStr] = Field(default=None, description="Public identifier for the API key.")
    key_hash: StrictStr = Field(description="SHA-256 hash of the plaintext key.")
    key_prefix: Optional[Annotated[str, Field(min_length=10, strict=True, max_length=13)]] = Field(default=None, description="Visible prefix of the API key for user identification (e.g., 'sk_abc123...'). Shows the first 10 characters of the plaintext key to help users identify which key is which in lists, without exposing the full secret. This follows industry best practices from GitHub, Stripe, and AWS. Generated automatically for new keys. Older keys may not have this field.")
    key_type: Optional[APIKeyType] = Field(default=None, description="Type of API key. STANDARD for regular organization keys, MARKETPLACE_SUBSCRIPTION for marketplace subscription access tokens.")
    subscription_id: Optional[StrictStr] = Field(default=None, description="Marketplace subscription ID if this is a marketplace subscription key. Only set when key_type is MARKETPLACE_SUBSCRIPTION.")
    internal_id: StrictStr = Field(description="Organization internal identifier.")
    organization_id: Optional[StrictStr] = Field(default=None, description="Organization public identifier (denormalized).")
    user_id: StrictStr = Field(description="Identifier of the user who owns the key.")
    name: StrictStr = Field(description="Human-friendly key label.")
    description: Optional[StrictStr] = Field(default='', description="Optional description explaining the key usage.")
    permissions: Optional[List[Permission]] = Field(default=None, description="Permissions granted to the key (least privilege recommended).")
    scopes: Optional[List[ResourceScopeOutput]] = Field(default=None, description="Resource-level scopes restricting the key.")
    rate_limit_override: Optional[StrictInt] = Field(default=None, description="Optional per-key rate limit override in requests per minute.")
    status: Optional[KeyStatus] = Field(default=None, description="Lifecycle status of the key (active, revoked, expired).")
    expires_at: Optional[datetime] = Field(default=None, description="UTC timestamp when the key automatically expires.")
    last_used_at: Optional[datetime] = Field(default=None, description="UTC timestamp of the last successful request using the key.")
    created_at: Optional[datetime] = Field(default=None, description="UTC timestamp when the key was created.")
    created_by: Optional[StrictStr] = Field(default=None, description="User identifier that created the key.")
    revoked_at: Optional[datetime] = Field(default=None, description="UTC timestamp when the key was revoked (if applicable).")
    revoked_by: Optional[StrictStr] = Field(default=None, description="User identifier that revoked the key (if applicable).")
    allowed_origins: Optional[List[StrictStr]] = Field(default=None, description="Optional list of allowed HTTP origins for this API key. When set, requests must include an Origin header matching one of these values. Supports exact matches (e.g., 'https://docs.example.com') and wildcard subdomains (e.g., 'https://*.example.com'). Only enforced for browser requests (defense-in-depth, not a security boundary). Null means no origin restriction.")
    key: StrictStr = Field(description="Plaintext API key (shown only once). Prefix: ret_sk_. Store securely immediately after creation.")
    __properties: ClassVar[List[str]] = ["key_id", "key_hash", "key_prefix", "key_type", "subscription_id", "internal_id", "organization_id", "user_id", "name", "description", "permissions", "scopes", "rate_limit_override", "status", "expires_at", "last_used_at", "created_at", "created_by", "revoked_at", "revoked_by", "allowed_origins", "key"]

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
    )


    def to_str(self) -> str:
        """Returns the string representation of the model using alias"""
        return pprint.pformat(self.model_dump(by_alias=True))

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
        return json.dumps(self.to_dict())

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of RetrieverAPIKeyResponse from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(self) -> Dict[str, Any]:
        """Return the dictionary representation of the model using alias.

        This has the following differences from calling pydantic's
        `self.model_dump(by_alias=True)`:

        * `None` is only added to the output dict for nullable fields that
          were set at model initialization. Other fields with value `None`
          are ignored.
        """
        excluded_fields: Set[str] = set([
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of each item in scopes (list)
        _items = []
        if self.scopes:
            for _item_scopes in self.scopes:
                if _item_scopes:
                    _items.append(_item_scopes.to_dict())
            _dict['scopes'] = _items
        return _dict

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of RetrieverAPIKeyResponse from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        _obj = cls.model_validate({
            "key_id": obj.get("key_id"),
            "key_hash": obj.get("key_hash"),
            "key_prefix": obj.get("key_prefix"),
            "key_type": obj.get("key_type"),
            "subscription_id": obj.get("subscription_id"),
            "internal_id": obj.get("internal_id"),
            "organization_id": obj.get("organization_id"),
            "user_id": obj.get("user_id"),
            "name": obj.get("name"),
            "description": obj.get("description") if obj.get("description") is not None else '',
            "permissions": obj.get("permissions"),
            "scopes": [ResourceScopeOutput.from_dict(_item) for _item in obj["scopes"]] if obj.get("scopes") is not None else None,
            "rate_limit_override": obj.get("rate_limit_override"),
            "status": obj.get("status"),
            "expires_at": obj.get("expires_at"),
            "last_used_at": obj.get("last_used_at"),
            "created_at": obj.get("created_at"),
            "created_by": obj.get("created_by"),
            "revoked_at": obj.get("revoked_at"),
            "revoked_by": obj.get("revoked_by"),
            "allowed_origins": obj.get("allowed_origins"),
            "key": obj.get("key")
        })
        return _obj


