# 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: 1.3.0
    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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from mixpeek.models.source1 import Source1
from typing import Optional, Set
from typing_extensions import Self

class FieldMappingEntry(BaseModel):
    """
    Maps a source value to a bucket schema field.  Used for mapping metadata, tags, columns, or extracted values to regular fields in the bucket schema (strings, numbers, arrays, etc.). Does NOT handle file content - use BlobMappingEntry for that.  Example: Map S3 tag \"category\" to bucket field \"content_category\"     {         \"target_type\": \"field\",         \"source\": {\"type\": \"tag\", \"key\": \"category\"}     }  Example: Map folder name to \"department\" with lowercase transform     {         \"target_type\": \"field\",         \"source\": {\"type\": \"folder_path\", \"segment\": 0},         \"transform\": \"lowercase\"     }  Example: Map filename regex capture to \"date\" field     {         \"target_type\": \"field\",         \"source\": {\"type\": \"filename_regex\", \"pattern\": \"^(\\d{4}-\\d{2}-\\d{2})\"},         \"required\": true     }  Attributes:     target_type: Must be \"field\" for schema field mappings     source: The source extractor defining where to get the value     transform: Optional transformation to apply (lowercase, uppercase, trim)     required: Whether missing values should fail the sync
    """ # noqa: E501
    target_type: Optional[StrictStr] = Field(default='field', description="Target type. Must be 'field' for regular schema fields.")
    source: Source1
    transform: Optional[StrictStr] = Field(default=None, description="Optional transformation to apply to the extracted value. Supported transforms: 'lowercase' - convert to lowercase, 'uppercase' - convert to uppercase, 'trim' - remove leading/trailing whitespace, 'json_parse' - parse JSON string to object/array. Transforms are applied after extraction, before storage.")
    required: Optional[StrictBool] = Field(default=False, description="If True, the sync will fail if this field cannot be extracted. If False (default), missing values result in the field being omitted. Use required=True for critical fields that must be present.")
    __properties: ClassVar[List[str]] = ["target_type", "source", "transform", "required"]

    @field_validator('target_type')
    def target_type_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(['field']):
            raise ValueError("must be one of enum values ('field')")
        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 FieldMappingEntry 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 source
        if self.source:
            _dict['source'] = self.source.to_dict()
        return _dict

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

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

        _obj = cls.model_validate({
            "target_type": obj.get("target_type") if obj.get("target_type") is not None else 'field',
            "source": Source1.from_dict(obj["source"]) if obj.get("source") is not None else None,
            "transform": obj.get("transform"),
            "required": obj.get("required") if obj.get("required") is not None else False
        })
        return _obj


