# coding: utf-8

"""
    OneLogin API Python SDK

    Official Python SDK for the OneLogin API
"""


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


from typing import Optional
from pydantic import BaseModel, Field, StrictBool, StrictInt, StrictStr, ValidationError, conlist, field_validator
from onelogin.models.action_obj import ActionObj
from onelogin.models.condition import Condition

class Mapping(BaseModel):
    """
    Mapping
    """
    id: Optional[StrictInt] = None
    name: StrictStr = Field(..., description="The name of the mapping.")
    enabled: StrictBool = Field(..., description="Indicates if the mapping is enabled or not.")
    match: StrictStr = Field(..., description="Indicates how conditions should be matched.")
    position: Optional[StrictInt] = Field(None, description="Indicates the order of the mapping. When `null` this will default to last position.")
    conditions: conlist(Condition) = Field(..., description="An array of conditions that the user must meet in order for the mapping to be applied.")
    actions: conlist(ActionObj) = Field(..., description="An array of actions that will be applied to the users that are matched by the conditions.")
    __properties = ["id", "name", "enabled", "match", "position", "conditions", "actions"]

    @field_validator('match')
    @classmethod
    def match_validate_enum(cls, value):
        """Validates the enum"""
        if value not in ('all', 'any'):
            raise ValueError("must be one of enum values ('all', 'any')")
        return value

    """Pydantic configuration"""
    model_config = {
        "validate_by_name": True,
        "validate_by_alias": True,
        "validate_assignment": True
    }

    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"""
        return json.dumps(self.to_dict())

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

    def to_dict(self):
        """Returns the dictionary representation of the model using alias"""
        _dict = self.model_dump(by_alias=True,
                          exclude={
                          },
                          exclude_none=True)
        # override the default output from pydantic by calling `to_dict()` of each item in conditions (list)
        _items = []
        if self.conditions:
            for _item in self.conditions:
                if _item:
                    _items.append(_item.to_dict())
            _dict['conditions'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in actions (list)
        _items = []
        if self.actions:
            for _item in self.actions:
                if _item:
                    _items.append(_item.to_dict())
            _dict['actions'] = _items
        return _dict

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

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

        _data = {
            "id": obj.get("id"),
            "name": obj.get("name"),
            "enabled": obj.get("enabled"),
            "match": obj.get("match"),
            "position": obj.get("position"),
            "conditions": [Condition.from_dict(_item) for _item in obj.get("conditions")] if obj.get("conditions") is not None else None,
            "actions": [ActionObj.from_dict(_item) for _item in obj.get("actions")] if obj.get("actions") is not None else None
        }

        # Create Mapping can return a partial payload (e.g., {"id": ...}).
        # Validate strictly, but fall back to model_construct for the narrow
        # id-only case so successful creates do not raise.
        try:
            return Mapping.model_validate(_data)
        except ValidationError:
            if set(obj.keys()) == {"id"} and obj.get("id") is not None:
                return Mapping.model_construct(**_data)
            raise
