# 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
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from mixpeek.models.schema_mapping_input import SchemaMappingInput
from mixpeek.models.sync_mode import SyncMode
from typing import Optional, Set
from typing_extensions import Self

class SyncCreateRequest(BaseModel):
    """
    Request to create a bucket sync configuration.  Establishes automated synchronization between a storage connection and a bucket. The sync monitors the source path for changes and ingests files according to the specified mode and filters.  Supported Storage Providers:     - google_drive: Google Drive and Workspace shared drives     - s3: Amazon S3 and S3-compatible (MinIO, DigitalOcean Spaces, Wasabi)     - snowflake: Snowflake data warehouse tables (rows become objects)     - sharepoint: Microsoft SharePoint and OneDrive for Business     - tigris: Tigris globally distributed object storage  Robustness Features (built-in):     - Dead Letter Queue (DLQ): Failed objects tracked with 3 retries before quarantine     - Idempotent ingestion: Deduplication via (bucket_id, source_provider, source_object_id)     - Distributed locking: Prevents concurrent execution of same sync config     - Rate limit handling: Automatic backoff on provider 429 responses     - Metrics: Duration, files synced/failed, batches created, rate limit hits  Sync Modes:     - continuous: Real-time monitoring with polling interval     - one_time: Single bulk import then stops     - scheduled: Polling-based batch imports  Requirements:     - connection_id: REQUIRED, must be an existing connection     - source_path: REQUIRED, path must exist in the storage provider     - sync_mode: OPTIONAL, defaults to 'continuous'     - All other fields are OPTIONAL with sensible defaults
    """ # noqa: E501
    connection_id: StrictStr = Field(description="REQUIRED. Storage connection identifier to sync from. Must reference an existing connection created via POST /organizations/connections. The connection defines the storage provider and credentials. Supported providers: google_drive, s3, snowflake, sharepoint, tigris.")
    source_path: StrictStr = Field(description="REQUIRED. Source path within the storage provider to monitor and sync. Path format varies by provider: - s3/tigris: 'bucket-name/prefix' or 'bucket-name'. - google_drive: folder ID or path like '/Marketing/Assets'. - sharepoint: '/sites/SiteName/Shared Documents/folder'. - snowflake: 'DATABASE.SCHEMA.TABLE' or just 'TABLE' if defaults set.")
    sync_mode: Optional[SyncMode] = Field(default=None, description="Synchronization mode determining how files are monitored and ingested. OPTIONAL. Defaults to 'continuous'. 'continuous': Actively monitors for new files and syncs immediately. 'one_time': Performs a single sync of existing files then stops. 'scheduled': Syncs on polling intervals only.")
    file_filters: Optional[Dict[str, Any]] = Field(default=None, description="OPTIONAL. Filters to control which files are synced. When omitted, all files in source_path are synced. Supported filters: - include_patterns: Glob patterns to include (e.g., ['*.mp4', '*.mov']). - exclude_patterns: Glob patterns to exclude (e.g., ['*.tmp', '.DS_Store']). - extensions: File extensions to include (e.g., ['.mp4', '.jpg']). - min_size_bytes: Minimum file size in bytes. - max_size_bytes: Maximum file size in bytes. - modified_after: ISO datetime, only sync files modified after this time. - mime_types: List of MIME types to include (e.g., ['video/*', 'image/jpeg']).")
    schema_mapping: Optional[SchemaMappingInput] = Field(default=None, description="OPTIONAL. Defines how source data maps to bucket schema fields and blobs. When provided, enables structured extraction of metadata from the sync source. Keys are target bucket schema field names, values define the source extraction method.   **Blob Mappings** (target_type='blob'): Map files or URLs to blob fields. Use source.type='file' for the synced file itself, or source.type='column'/'metadata' for URLs.   **Field Mappings** (target_type='field'): Map metadata to schema fields. Source options by provider: - S3/Tigris: 'tag' (object tags), 'metadata' (x-amz-meta-*) - Snowflake: 'column' (table columns) - Google Drive: 'drive_property' (file properties) - All: 'filename_regex', 'folder_path', 'constant'   If omitted, default behavior depends on provider - typically maps file to 'content' blob.")
    polling_interval_seconds: Optional[Annotated[int, Field(le=900, strict=True, ge=30)]] = Field(default=300, description="Interval in seconds between polling checks for new files. OPTIONAL. Defaults to 300 seconds (5 minutes). Must be between 30 and 900 seconds (0.5 to 15 minutes). Only applies to 'continuous' and 'scheduled' sync modes. Lower values mean faster detection but higher API usage.")
    batch_size: Optional[Annotated[int, Field(le=100, strict=True, ge=1)]] = Field(default=50, description="Number of files to process in each batch during sync. OPTIONAL. Defaults to 50 files per batch. Must be between 1 and 100. Larger batches improve throughput but require more memory. Smaller batches provide more granular progress tracking.")
    skip_batch_submission: Optional[StrictBool] = Field(default=False, description="If True, sync objects to the bucket without creating or submitting batches for collection processing. Objects are created in the bucket but no tier processing is triggered. Useful for bulk data migration or when you want to manually control when processing occurs. OPTIONAL. Defaults to False (batches are created and submitted).")
    metadata: Optional[Dict[str, Any]] = Field(default=None, description="Optional custom metadata to attach to the sync configuration. NOT REQUIRED. Arbitrary key-value pairs for tagging and organization. Common uses: project tags, environment labels, cost centers. Maximum 50 keys, values must be JSON-serializable.")
    __properties: ClassVar[List[str]] = ["connection_id", "source_path", "sync_mode", "file_filters", "schema_mapping", "polling_interval_seconds", "batch_size", "skip_batch_submission", "metadata"]

    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 SyncCreateRequest 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 schema_mapping
        if self.schema_mapping:
            _dict['schema_mapping'] = self.schema_mapping.to_dict()
        return _dict

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

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

        _obj = cls.model_validate({
            "connection_id": obj.get("connection_id"),
            "source_path": obj.get("source_path"),
            "sync_mode": obj.get("sync_mode"),
            "file_filters": obj.get("file_filters"),
            "schema_mapping": SchemaMappingInput.from_dict(obj["schema_mapping"]) if obj.get("schema_mapping") is not None else None,
            "polling_interval_seconds": obj.get("polling_interval_seconds") if obj.get("polling_interval_seconds") is not None else 300,
            "batch_size": obj.get("batch_size") if obj.get("batch_size") is not None else 50,
            "skip_batch_submission": obj.get("skip_batch_submission") if obj.get("skip_batch_submission") is not None else False,
            "metadata": obj.get("metadata")
        })
        return _obj


