# 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 datetime import datetime
from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from typing import Optional, Set
from typing_extensions import Self

class BlobURLRef(BaseModel):
    """
    Reference to a document-related blob with automatic presigned URL generation.  Represents any file or asset associated with a document, including source media, processed outputs, thumbnails, and artifacts. All blobs with S3 URLs automatically receive presigned URLs when documents are retrieved from the API.  Use Cases:     - Track source media: Original videos, images, or files from buckets     - Reference processed outputs: Video segments, extracted frames, thumbnails     - Link artifacts: Generated reports, analysis results, derived media     - Maintain lineage: Connect processed blobs back to their source blobs  Role Definitions:     - source: Original input media (e.g., uploaded video, bucket object)     - processed: Derived/transformed content (e.g., video segments, extracted frames)     - thumbnail: Preview images for visual content     - artifact: Generated files (reports, analysis outputs)     - aux: Supporting/auxiliary files  Presigned URL Flow:     1. During processing: Store S3 URLs in document_blobs (no presigned URL yet)     2. During retrieval: API automatically adds presigned_url field to each blob     3. Client receives: Both permanent S3 URL and time-limited HTTPS presigned URL  Requirements:     - field: REQUIRED. Semantic label for the blob (e.g., 'video_segment', 'thumbnail')     - url: REQUIRED. S3 or HTTP URL to the blob content     - role: REQUIRED. Semantic role for UX grouping and behavior     - All other fields: OPTIONAL but recommended for better tracking
    """ # noqa: E501
    var_field: Annotated[str, Field(min_length=1, strict=True)] = Field(description="REQUIRED. Stable semantic label for this blob. Use descriptive names like 'video_segment', 'thumbnail', 'source_video', etc. Avoid internal implementation details like array indices. This field is used for programmatic access and should be consistent across documents.", alias="field")
    role: Optional[StrictStr] = Field(default='source', description="REQUIRED. Semantic role determining how this blob should be treated. 'source': Original input media from buckets or uploads. 'processed': Derived content created by feature extractors (segments, frames). 'thumbnail': Preview images for UI display. 'artifact': Generated outputs (reports, analysis results). 'aux': Supporting or auxiliary files. Used by UI for grouping and displaying blobs appropriately.")
    type: Optional[StrictStr] = Field(default='other', description="REQUIRED. Media type of the blob content. Determines how the blob should be rendered or processed. Use 'other' for custom or unknown types.")
    url: Annotated[str, Field(min_length=1, strict=True)] = Field(description="REQUIRED. Permanent URL to the blob content. S3 URLs (s3://bucket/key) are automatically converted to presigned HTTPS URLs by the API. HTTP/HTTPS URLs are returned as-is. This is the canonical reference to the blob that persists across API calls.")
    filename: Optional[StrictStr] = Field(default=None, description="OPTIONAL. Original filename or leaf name of the blob. Useful for downloads and display purposes. Example: 'segment_0.mp4', 'thumbnail.jpg'")
    size_bytes: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(default=None, description="OPTIONAL. Size of the blob in bytes. Useful for progress indicators and storage tracking.")
    content_type: Optional[StrictStr] = Field(default=None, description="OPTIONAL. MIME type of the blob content. Used for proper content-type headers when serving files. Example: 'video/mp4', 'image/jpeg', 'application/pdf'")
    checksum: Optional[StrictStr] = Field(default=None, description="OPTIONAL. Checksum or hash of the blob content for integrity verification. Format: 'algorithm:hash' (e.g., 'sha256:abc123...')")
    created_at: Optional[datetime] = Field(default=None, description="OPTIONAL. Timestamp when the blob was created or uploaded. ISO 8601 format. Useful for tracking blob lifecycle and cleanup.")
    source_blob_id: Optional[StrictStr] = Field(default=None, description="OPTIONAL. Cross-reference to the source blob ID from the bucket object. Used for lineage tracking: connects processed blobs back to their original sources. Example: A video segment references the original video blob that it was extracted from.")
    presigned_url: Optional[Annotated[str, Field(min_length=1, strict=True)]] = Field(default=None, description="RESPONSE ONLY. Time-limited HTTPS URL for direct access to the blob. Automatically generated by the API when documents are retrieved. NOT REQUIRED when creating blobs - leave empty, API will populate. Typically expires after 1 hour. Use for immediate media playback or download.")
    __properties: ClassVar[List[str]] = ["field", "role", "type", "url", "filename", "size_bytes", "content_type", "checksum", "created_at", "source_blob_id", "presigned_url"]

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

        if value not in set(['source', 'processed', 'thumbnail', 'artifact', 'aux']):
            raise ValueError("must be one of enum values ('source', 'processed', 'thumbnail', 'artifact', 'aux')")
        return value

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

        if value not in set(['video', 'image', 'audio', 'text', 'pdf', 'other']):
            raise ValueError("must be one of enum values ('video', 'image', 'audio', 'text', 'pdf', 'other')")
        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 BlobURLRef 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,
        )
        return _dict

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

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

        _obj = cls.model_validate({
            "field": obj.get("field"),
            "role": obj.get("role") if obj.get("role") is not None else 'source',
            "type": obj.get("type") if obj.get("type") is not None else 'other',
            "url": obj.get("url"),
            "filename": obj.get("filename"),
            "size_bytes": obj.get("size_bytes"),
            "content_type": obj.get("content_type"),
            "checksum": obj.get("checksum"),
            "created_at": obj.get("created_at"),
            "source_blob_id": obj.get("source_blob_id"),
            "presigned_url": obj.get("presigned_url")
        })
        return _obj


