# 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, StrictBool, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from mixpeek.models.listing_status import ListingStatus
from mixpeek.models.listing_visibility import ListingVisibility
from mixpeek.models.subscription_tier_config import SubscriptionTierConfig
from typing import Optional, Set
from typing_extensions import Self

class MarketplaceListing(BaseModel):
    """
    A marketplace listing for a retriever.  This is the unified model for all public and marketplace retrievers. Replaces the PublishedRetriever system with a simpler, more flexible approach.  Free tier = public retriever (anyone can subscribe for free) Paid tiers = monetized marketplace offering
    """ # noqa: E501
    listing_id: Optional[StrictStr] = Field(default=None, description="Unique identifier for the listing")
    internal_id: StrictStr = Field(description="Organization that owns this listing (provider)")
    namespace_id: StrictStr = Field(description="Namespace containing the retriever")
    retriever_id: StrictStr = Field(description="Retriever being offered in the marketplace")
    title: StrictStr = Field(description="Public display title")
    description: StrictStr = Field(description="Public description of what this listing provides")
    public_name: Annotated[str, Field(min_length=3, strict=True, max_length=50)] = Field(description="Public URL-safe slug for the listing (e.g., 'video-search'). Used in public URL: mxp.co/m/{public_name}. Must be globally unique.")
    category: Optional[StrictStr] = Field(default=None, description="Category for browsing (e.g., 'Content Moderation', 'Search')")
    tags: Optional[List[StrictStr]] = Field(default=None, description="Tags for discovery")
    logo_url: Optional[StrictStr] = Field(default=None, description="URL to listing logo/icon")
    icon_base64: Optional[Annotated[str, Field(strict=True, max_length=300000)]] = Field(default=None, description="Base64 encoded icon/favicon (data URI format). Max size: ~200KB encoded. Use for small icons.")
    available_tiers: List[SubscriptionTierConfig] = Field(description="Available subscription tiers (must include at least one tier, typically FREE for public listings)")
    display_config: Optional[Dict[str, Any]] = Field(default=None, description="JSON-based UI configuration for the public interface. Follows a component-based schema (inspired by json-render): { 'components': [...], 'theme': {...}, 'layout': {...} }. If not provided, a default UI is generated from retriever input_schema.")
    password_secret_name: Optional[StrictStr] = Field(default=None, description="Optional organization secret name containing password for access protection. If set, users must provide password to subscribe (even for free tier).")
    status: Optional[ListingStatus] = Field(default=None, description="Publication status")
    visibility: Optional[ListingVisibility] = Field(default=None, description="Visibility level. 'listed' = shown in marketplace catalog & homepage showcase. 'unlisted' = accessible via direct link only (not in catalog).")
    is_active: Optional[StrictBool] = Field(default=True, description="DEPRECATED: Use 'status' field instead. Computed from status (True if PUBLISHED, False otherwise).")
    created_at: Optional[datetime] = Field(default=None, description="When the listing was created")
    updated_at: Optional[datetime] = Field(default=None, description="When the listing was last updated")
    published_at: Optional[datetime] = Field(default=None, description="When the listing was first published")
    total_subscribers: Optional[StrictInt] = Field(default=0, description="Total number of active subscribers")
    total_queries: Optional[StrictInt] = Field(default=0, description="Total queries executed across all subscribers")
    __properties: ClassVar[List[str]] = ["listing_id", "internal_id", "namespace_id", "retriever_id", "title", "description", "public_name", "category", "tags", "logo_url", "icon_base64", "available_tiers", "display_config", "password_secret_name", "status", "visibility", "is_active", "created_at", "updated_at", "published_at", "total_subscribers", "total_queries"]

    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 MarketplaceListing 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 available_tiers (list)
        _items = []
        if self.available_tiers:
            for _item_available_tiers in self.available_tiers:
                if _item_available_tiers:
                    _items.append(_item_available_tiers.to_dict())
            _dict['available_tiers'] = _items
        return _dict

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

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

        _obj = cls.model_validate({
            "listing_id": obj.get("listing_id"),
            "internal_id": obj.get("internal_id"),
            "namespace_id": obj.get("namespace_id"),
            "retriever_id": obj.get("retriever_id"),
            "title": obj.get("title"),
            "description": obj.get("description"),
            "public_name": obj.get("public_name"),
            "category": obj.get("category"),
            "tags": obj.get("tags"),
            "logo_url": obj.get("logo_url"),
            "icon_base64": obj.get("icon_base64"),
            "available_tiers": [SubscriptionTierConfig.from_dict(_item) for _item in obj["available_tiers"]] if obj.get("available_tiers") is not None else None,
            "display_config": obj.get("display_config"),
            "password_secret_name": obj.get("password_secret_name"),
            "status": obj.get("status"),
            "visibility": obj.get("visibility"),
            "is_active": obj.get("is_active") if obj.get("is_active") is not None else True,
            "created_at": obj.get("created_at"),
            "updated_at": obj.get("updated_at"),
            "published_at": obj.get("published_at"),
            "total_subscribers": obj.get("total_subscribers") if obj.get("total_subscribers") is not None else 0,
            "total_queries": obj.get("total_queries") if obj.get("total_queries") is not None else 0
        })
        return _obj


