# coding: utf-8

"""
    Lance Namespace Specification

    This OpenAPI specification is a part of the Lance namespace specification. It contains 2 parts:  The `components/schemas`, `components/responses`, `components/examples`, `tags` sections define the request and response shape for each operation in a Lance Namespace across all implementations. See https://lance.org/format/namespace/operations for more details.  The `servers`, `security`, `paths`, `components/parameters` sections are for the Lance REST Namespace implementation, which defines a complete REST server that can work with Lance datasets. See https://lance.org/format/namespace/rest for more details. 

    The version of the OpenAPI document: 1.0.0
    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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from lance_namespace_urllib3_client.models.identity import Identity
from lance_namespace_urllib3_client.models.materialized_view_udtf_entry import MaterializedViewUdtfEntry
from typing import Optional, Set
from typing_extensions import Self

class CreateMaterializedViewRequest(BaseModel):
    """
    CreateMaterializedViewRequest
    """ # noqa: E501
    identity: Optional[Identity] = None
    context: Optional[Dict[str, StrictStr]] = Field(default=None, description="Arbitrary context as key-value pairs. How to use the context is custom to the specific implementation.  On a request, it carries caller-provided context to the implementation. On a response, it carries implementation-provided context back to the caller.  REST NAMESPACE ONLY Context entries are mapped to and from HTTP headers using the `header.` prefix: - On a request, any entry whose key starts with `header.` is sent as an HTTP   request header with the prefix stripped. For example, the entry   `{\"header.Authorization\": \"Bearer abc\"}` is sent as the request header   `Authorization: Bearer abc`. - On a response, every HTTP response header is returned as an entry whose key is the   header name prefixed with `header.`. For example, the response header   `x-request-id: abc123` is returned as the entry `{\"header.x-request-id\": \"abc123\"}`. ")
    id: Optional[List[StrictStr]] = Field(default=None, description="View identifier path (namespace + view name)")
    kind: StrictStr = Field(description="The materialized view kind. - `query` — plain query-backed view (no UDTF), 1:1 rows. - `udtf` — batch UDTF-backed view (N:M rows, full refresh). - `chunker`, aka 'scalar_udtf' — chunker view (1:N row expansion, incremental refresh). ")
    source_query: StrictStr = Field(description="Opaque serialized representation of the source query that defines the view's input. The format is defined by the client; the namespace server stores it without interpreting it. ")
    output_schema: StrictStr = Field(description="Base64-encoded Arrow schema of the view output")
    udtf_spec: Optional[MaterializedViewUdtfEntry] = None
    with_no_data: Optional[StrictBool] = Field(default=True, description="If false, the server kicks off an initial refresh immediately after creating the view and the response includes a job ID. ")
    auto_refresh: Optional[StrictBool] = Field(default=False, description="If true, the view is automatically refreshed when source-table data changes past the deployment-level threshold. Boolean opt-in only; the threshold and cooldown are configured on the deployment, not per-view. ")
    __properties: ClassVar[List[str]] = ["identity", "context", "id", "kind", "source_query", "output_schema", "udtf_spec", "with_no_data", "auto_refresh"]

    @field_validator('kind')
    def kind_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(['query', 'udtf', 'chunker']):
            raise ValueError("must be one of enum values ('query', 'udtf', 'chunker')")
        return value

    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 CreateMaterializedViewRequest 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 identity
        if self.identity:
            _dict['identity'] = self.identity.to_dict()
        # override the default output from pydantic by calling `to_dict()` of udtf_spec
        if self.udtf_spec:
            _dict['udtf_spec'] = self.udtf_spec.to_dict()
        # set to None if udtf_spec (nullable) is None
        # and model_fields_set contains the field
        if self.udtf_spec is None and "udtf_spec" in self.model_fields_set:
            _dict['udtf_spec'] = None

        # set to None if auto_refresh (nullable) is None
        # and model_fields_set contains the field
        if self.auto_refresh is None and "auto_refresh" in self.model_fields_set:
            _dict['auto_refresh'] = None

        return _dict

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

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

        _obj = cls.model_validate({
            "identity": Identity.from_dict(obj["identity"]) if obj.get("identity") is not None else None,
            "context": obj.get("context"),
            "id": obj.get("id"),
            "kind": obj.get("kind"),
            "source_query": obj.get("source_query"),
            "output_schema": obj.get("output_schema"),
            "udtf_spec": MaterializedViewUdtfEntry.from_dict(obj["udtf_spec"]) if obj.get("udtf_spec") is not None else None,
            "with_no_data": obj.get("with_no_data") if obj.get("with_no_data") is not None else True,
            "auto_refresh": obj.get("auto_refresh") if obj.get("auto_refresh") is not None else False
        })
        return _obj


