"""
Snowflake Dynamic Table API.

The Snowflake Dynamic Table API is a REST API that you can use to access, update, and perform certain actions on Dynamic Tables resource in a Snowflake database.  # noqa: E501

The version of the OpenAPI document: 0.0.1
Contact: support@snowflake.com
Generated by: https://openapi-generator.tech

Do not edit this file manually.
"""

from __future__ import annotations

import json
import pprint
import re  # noqa: F401

from datetime import datetime
from typing import Any, List, Optional

from pydantic import BaseModel, ConfigDict, StrictBool, StrictInt, StrictStr, field_validator

from snowflake.core.dynamic_table._generated.models.dynamic_table_column import (
    DynamicTableColumn,
    DynamicTableColumnModel,
)
from snowflake.core.dynamic_table._generated.models.target_lag import TargetLag, TargetLagModel


class DynamicTable(BaseModel):
    """A model object representing the DynamicTable resource.

    Constructs an object of type DynamicTable with the provided properties.

    Parameters
    __________
    name : str
        Specifies the name for the dynamic table, must be unique for the schema in which the dynamic table is created
    target_lag : TargetLag

    warehouse : str
        Specifies the name of the warehouse that provides the compute resources for refreshing the dynamic table
    query : str
        Specifies the query whose results the dynamic table should contain
    kind : str,  default 'PERMANENT'
        Specifies the dynamic table type, permanent (default) or transient.
    columns : list[DynamicTableColumn], optional

    refresh_mode : str, optional
        Specifies the refresh type for the dynamic table
    initialize : str, optional
        Specifies the behavior of the initial refresh of the dynamic table
    cluster_by : list[str], optional
        Specifies one or more columns or column expressions in the dynamic table as the clustering key
    data_retention_time_in_days : int, optional
        Specifies the retention period for the dynamic table so that Time Travel actions (SELECT, CLONE) can be performed on historical data in the dynamic table
    max_data_extension_time_in_days : int, optional
        Specifies the retention period for the dynamic table so that Time Travel actions (SELECT, CLONE) can be performed on historical data in the dynamic table
    comment : str, optional
        Specifies a comment for the dynamic table.
    created_on : datetime, optional
        Date and time when the dynamic table was created — **Read-only:** *any user-provided value will be ignored.*
    database_name : str, optional
        Database in which the dynamic table is stored — **Read-only:** *any user-provided value will be ignored.*
    schema_name : str, optional
        Schema in which the dynamic table is stored — **Read-only:** *any user-provided value will be ignored.*
    rows : int, optional
        Number of rows in the dynamic table — **Read-only:** *any user-provided value will be ignored.*
    bytes : int, optional
        Number of bytes that will be scanned if the entire table is scanned in a query. Note that this number may be different than the number of actual physical bytes stored on-disk for the table — **Read-only:** *any user-provided value will be ignored.*
    scheduling_state : str, optional
        Scheduling state (RUNNING or SUSPENDED) — **Read-only:** *any user-provided value will be ignored.*
    automatic_clustering : bool, optional
        If Automatic Clustering is enabled for your account, specifies whether it is explicitly enabled or disabled for the dynamic table — **Read-only:** *any user-provided value will be ignored.*
    owner : str, optional
        Role that owns the table — **Read-only:** *any user-provided value will be ignored.*
    owner_role_type : str, optional
        The type of role that owns the object — **Read-only:** *any user-provided value will be ignored.*
    budget : str, optional
        Name of the budget if the object is monitored by a budget — **Read-only:** *any user-provided value will be ignored.*
    """

    name: StrictStr

    kind: Optional[StrictStr] = "PERMANENT"

    columns: Optional[List[DynamicTableColumn]] = None

    target_lag: TargetLag

    refresh_mode: Optional[StrictStr] = None

    initialize: Optional[StrictStr] = None

    warehouse: StrictStr

    cluster_by: Optional[List[StrictStr]] = None

    query: StrictStr

    data_retention_time_in_days: Optional[StrictInt] = None

    max_data_extension_time_in_days: Optional[StrictInt] = None

    comment: Optional[StrictStr] = None

    created_on: Optional[datetime] = None

    database_name: Optional[StrictStr] = None

    schema_name: Optional[StrictStr] = None

    rows: Optional[StrictInt] = None

    bytes: Optional[StrictInt] = None

    scheduling_state: Optional[StrictStr] = None

    automatic_clustering: Optional[StrictBool] = None

    owner: Optional[StrictStr] = None

    owner_role_type: Optional[StrictStr] = None

    budget: Optional[StrictStr] = None

    __properties = [
        "name",
        "kind",
        "columns",
        "target_lag",
        "refresh_mode",
        "initialize",
        "warehouse",
        "cluster_by",
        "query",
        "data_retention_time_in_days",
        "max_data_extension_time_in_days",
        "comment",
        "created_on",
        "database_name",
        "schema_name",
        "rows",
        "bytes",
        "scheduling_state",
        "automatic_clustering",
        "owner",
        "owner_role_type",
        "budget",
    ]

    @field_validator("kind")
    def kind_validate_enum(cls, v):
        if v is None:
            return v
        if v not in ("PERMANENT", "TRANSIENT"):
            raise ValueError("must validate the enum values ('PERMANENT','TRANSIENT')")
        return v

    @field_validator("refresh_mode")
    def refresh_mode_validate_enum(cls, v):
        if v is None:
            return v
        if v not in ("AUTO", "FULL", "INCREMENTAL"):
            raise ValueError("must validate the enum values ('AUTO','FULL','INCREMENTAL')")
        return v

    @field_validator("initialize")
    def initialize_validate_enum(cls, v):
        if v is None:
            return v
        if v not in ("ON_CREATE", "ON_SCHEDULE"):
            raise ValueError("must validate the enum values ('ON_CREATE','ON_SCHEDULE')")
        return v

    @field_validator("scheduling_state")
    def scheduling_state_validate_enum(cls, v):
        if v is None:
            return v
        if v not in ("RUNNING", "SUSPENDED"):
            raise ValueError("must validate the enum values ('RUNNING','SUSPENDED')")
        return v

    model_config = ConfigDict(
        validate_by_name=True,
        validate_assignment=True,
    )

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

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias."""
        return json.dumps(self.to_dict())

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

    def to_dict(
        self,
        hide_readonly_properties: bool = False,
    ) -> dict[str, Any]:
        """Returns the dictionary representation of the model using alias."""
        exclude_properties = set()

        if hide_readonly_properties:
            exclude_properties.update(
                {
                    "created_on",
                    "database_name",
                    "schema_name",
                    "rows",
                    "bytes",
                    "scheduling_state",
                    "automatic_clustering",
                    "owner",
                    "owner_role_type",
                    "budget",
                }
            )

        _dict = self.model_dump(serialize_as_any=True, by_alias=True, exclude=exclude_properties, exclude_none=True)

        # override the default output from pydantic by calling `to_dict()` of each item in columns (list)
        _items = []
        if self.columns:
            for _item in self.columns:
                if _item:
                    _items.append(_item.to_dict())
            _dict["columns"] = _items

        # override the default output from pydantic by calling `to_dict()` of target_lag
        if self.target_lag:
            _dict["target_lag"] = self.target_lag.to_dict()

        return _dict

    def to_dict_without_readonly_properties(self) -> dict[str, Any]:
        """Return the dictionary representation of the model without readonly properties."""
        return self.to_dict(hide_readonly_properties=True)

    @classmethod
    def from_dict(cls, obj: dict) -> DynamicTable:
        """Create an instance of DynamicTable from a dict."""
        if obj is None:
            return None

        if type(obj) is not dict:
            return DynamicTable.model_validate(obj)

        _obj = DynamicTable.model_validate(
            {
                "name": obj.get("name"),
                "kind": obj.get("kind") if obj.get("kind") is not None else "PERMANENT",
                "columns": [DynamicTableColumn.from_dict(_item) for _item in obj.get("columns")]
                if obj.get("columns") is not None
                else None,
                "target_lag": TargetLag.from_dict(obj.get("target_lag")) if obj.get("target_lag") is not None else None,
                "refresh_mode": obj.get("refresh_mode"),
                "initialize": obj.get("initialize"),
                "warehouse": obj.get("warehouse"),
                "cluster_by": obj.get("cluster_by"),
                "query": obj.get("query"),
                "data_retention_time_in_days": obj.get("data_retention_time_in_days"),
                "max_data_extension_time_in_days": obj.get("max_data_extension_time_in_days"),
                "comment": obj.get("comment"),
                "created_on": obj.get("created_on"),
                "database_name": obj.get("database_name"),
                "schema_name": obj.get("schema_name"),
                "rows": obj.get("rows"),
                "bytes": obj.get("bytes"),
                "scheduling_state": obj.get("scheduling_state"),
                "automatic_clustering": obj.get("automatic_clustering"),
                "owner": obj.get("owner"),
                "owner_role_type": obj.get("owner_role_type"),
                "budget": obj.get("budget"),
            }
        )

        return _obj


class DynamicTableModel:
    def __init__(
        self,
        name: str,
        target_lag: TargetLag,
        warehouse: str,
        query: str,
        # optional properties
        kind: Optional[str] = "PERMANENT",
        columns: Optional[list[DynamicTableColumn]] = None,
        refresh_mode: Optional[str] = None,
        initialize: Optional[str] = None,
        cluster_by: Optional[list[str]] = None,
        data_retention_time_in_days: Optional[int] = None,
        max_data_extension_time_in_days: Optional[int] = None,
        comment: Optional[str] = None,
        created_on: Optional[datetime] = None,
        database_name: Optional[str] = None,
        schema_name: Optional[str] = None,
        rows: Optional[int] = None,
        bytes: Optional[int] = None,
        scheduling_state: Optional[str] = None,
        automatic_clustering: Optional[bool] = None,
        owner: Optional[str] = None,
        owner_role_type: Optional[str] = None,
        budget: Optional[str] = None,
    ):
        """A model object representing the DynamicTable resource.

        Constructs an object of type DynamicTable with the provided properties.

        Parameters
        __________
        name : str
            Specifies the name for the dynamic table, must be unique for the schema in which the dynamic table is created
        target_lag : TargetLag

        warehouse : str
            Specifies the name of the warehouse that provides the compute resources for refreshing the dynamic table
        query : str
            Specifies the query whose results the dynamic table should contain
        kind : str,  default 'PERMANENT'
            Specifies the dynamic table type, permanent (default) or transient.
        columns : list[DynamicTableColumn], optional

        refresh_mode : str, optional
            Specifies the refresh type for the dynamic table
        initialize : str, optional
            Specifies the behavior of the initial refresh of the dynamic table
        cluster_by : list[str], optional
            Specifies one or more columns or column expressions in the dynamic table as the clustering key
        data_retention_time_in_days : int, optional
            Specifies the retention period for the dynamic table so that Time Travel actions (SELECT, CLONE) can be performed on historical data in the dynamic table
        max_data_extension_time_in_days : int, optional
            Specifies the retention period for the dynamic table so that Time Travel actions (SELECT, CLONE) can be performed on historical data in the dynamic table
        comment : str, optional
            Specifies a comment for the dynamic table.
        created_on : datetime, optional
            Date and time when the dynamic table was created.
        database_name : str, optional
            Database in which the dynamic table is stored
        schema_name : str, optional
            Schema in which the dynamic table is stored
        rows : int, optional
            Number of rows in the dynamic table.
        bytes : int, optional
            Number of bytes that will be scanned if the entire table is scanned in a query. Note that this number may be different than the number of actual physical bytes stored on-disk for the table
        scheduling_state : str, optional
            Scheduling state (RUNNING or SUSPENDED)
        automatic_clustering : bool, optional
            If Automatic Clustering is enabled for your account, specifies whether it is explicitly enabled or disabled for the dynamic table.
        owner : str, optional
            Role that owns the table
        owner_role_type : str, optional
            The type of role that owns the object.
        budget : str, optional
            Name of the budget if the object is monitored by a budget
        """
        self.name = name
        self.kind = kind
        self.columns = columns
        self.target_lag = target_lag
        self.refresh_mode = refresh_mode
        self.initialize = initialize
        self.warehouse = warehouse
        self.cluster_by = cluster_by
        self.query = query
        self.data_retention_time_in_days = data_retention_time_in_days
        self.max_data_extension_time_in_days = max_data_extension_time_in_days
        self.comment = comment
        self.created_on = created_on
        self.database_name = database_name
        self.schema_name = schema_name
        self.rows = rows
        self.bytes = bytes
        self.scheduling_state = scheduling_state
        self.automatic_clustering = automatic_clustering
        self.owner = owner
        self.owner_role_type = owner_role_type
        self.budget = budget

    __properties = [
        "name",
        "kind",
        "columns",
        "target_lag",
        "refresh_mode",
        "initialize",
        "warehouse",
        "cluster_by",
        "query",
        "data_retention_time_in_days",
        "max_data_extension_time_in_days",
        "comment",
        "created_on",
        "database_name",
        "schema_name",
        "rows",
        "bytes",
        "scheduling_state",
        "automatic_clustering",
        "owner",
        "owner_role_type",
        "budget",
    ]

    def __repr__(self) -> str:
        return repr(self._to_model())

    def _to_model(self):
        return DynamicTable(
            name=self.name,
            kind=self.kind,
            columns=[x._to_model() for x in self.columns] if self.columns is not None else None,
            target_lag=self.target_lag._to_model() if self.target_lag is not None else None,
            refresh_mode=self.refresh_mode,
            initialize=self.initialize,
            warehouse=self.warehouse,
            cluster_by=self.cluster_by,
            query=self.query,
            data_retention_time_in_days=self.data_retention_time_in_days,
            max_data_extension_time_in_days=self.max_data_extension_time_in_days,
            comment=self.comment,
            created_on=self.created_on,
            database_name=self.database_name,
            schema_name=self.schema_name,
            rows=self.rows,
            bytes=self.bytes,
            scheduling_state=self.scheduling_state,
            automatic_clustering=self.automatic_clustering,
            owner=self.owner,
            owner_role_type=self.owner_role_type,
            budget=self.budget,
        )

    @classmethod
    def _from_model(cls, model) -> DynamicTableModel:
        return DynamicTableModel(
            name=model.name,
            kind=model.kind,
            columns=[DynamicTableColumnModel._from_model(x) for x in model.columns] if model.columns else None,
            target_lag=TargetLagModel._from_model(model.target_lag) if model.target_lag else None,
            refresh_mode=model.refresh_mode,
            initialize=model.initialize,
            warehouse=model.warehouse,
            cluster_by=model.cluster_by,
            query=model.query,
            data_retention_time_in_days=model.data_retention_time_in_days,
            max_data_extension_time_in_days=model.max_data_extension_time_in_days,
            comment=model.comment,
            created_on=model.created_on,
            database_name=model.database_name,
            schema_name=model.schema_name,
            rows=model.rows,
            bytes=model.bytes,
            scheduling_state=model.scheduling_state,
            automatic_clustering=model.automatic_clustering,
            owner=model.owner,
            owner_role_type=model.owner_role_type,
            budget=model.budget,
        )

    def to_dict(self):
        """Create a dictionary of the properties from a DynamicTable.

        This method constructs a dictionary with the key-value entries corresponding to the properties of the DynamicTable object.

        Returns
        _______
        dict
            A dictionary object created using the input model.
        """
        return self._to_model().to_dict()

    @classmethod
    def from_dict(cls, obj: dict) -> DynamicTableModel:
        """Create an instance of DynamicTable from a dict.

        This method constructs a DynamicTable object from a dictionary with the key-value pairs of its properties.

        Parameters
        ----------
        obj : dict
            A dictionary whose keys and values correspond to the properties of the resource object.

        Returns
        _______
        DynamicTable
            A DynamicTable object created using the input dictionary; this will fail if the required properties are missing.
        """
        return cls._from_model(DynamicTable.from_dict(obj))


DynamicTable._model_class = DynamicTableModel
