from __future__ import annotations

from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar, cast

from attrs import define as _attrs_define
from attrs import field as _attrs_field

from ..models.bucket_schema_field_type import BucketSchemaFieldType
from ..types import UNSET, Unset

if TYPE_CHECKING:
    from ..models.blob_details import BlobDetails
    from ..models.blob_model_properties import BlobModelProperties


T = TypeVar("T", bound="BlobModel")


@_attrs_define
class BlobModel:
    """Model for a blob within a bucket object.

    Blobs store file references with a flat properties structure.
    All blob-specific data (formerly in separate 'data' and 'metadata' fields)
    is now unified in a single 'properties' dictionary.

    Example:
        {
            "blob_id": "blob_xyz123",
            "property": "video",
            "type": "video",
            "properties": {
                "url": "s3://bucket/video.mp4",
                "duration": 120,
                "resolution": "1920x1080",
                "author": "John Doe"  # All data unified here
            }
        }

        Attributes:
            property_ (str): Property name of the blob
            type_ (BucketSchemaFieldType): Supported data types for bucket schema fields.

                Types fall into two categories:

                1. **Metadata Types** (JSON types):
                   - Stored as object metadata
                   - Standard JSON-compatible types
                   - Not processed by extractors (unless explicitly mapped)
                   - Examples: string, number, boolean, date

                2. **File Types** (blobs):
                   - Stored as files/blobs
                   - Processed by extractors
                   - Require file content (URL or base64)
                   - Examples: text, image, video, pdf

                **GIF Special Handling**:
                    GIF files can be declared as either IMAGE or VIDEO type:

                    - As IMAGE: GIF is embedded as a single static image (first frame)
                    - As VIDEO: GIF is decomposed frame-by-frame with embeddings per frame

                    The multimodal extractor detects GIFs via MIME type (image/gif) and routes
                    them based on your schema declaration. Use VIDEO for animated GIFs where
                    frame-level search is needed, IMAGE for static/thumbnail use cases.

                NOTE: For retriever input schemas that need to accept document references
                (e.g., "find similar documents"), use RetrieverInputSchemaFieldType instead,
                which includes all bucket types plus document_reference.
            blob_id (str | Unset): Unique identifier for the blob
            key_prefix (None | str | Unset): Storage key/path of the blob, this will be used to retrieve the blob from the
                storage. It is similar to a file path. If not provided, it will be placed in the root of the bucket.
            properties (BlobModelProperties | Unset): All blob data and metadata unified (formerly separate 'data' and
                'metadata' fields). Contains URLs, dimensions, metadata, and any other blob-specific information.
            details (BlobDetails | Unset): File details for a bucket object, these are automatically generated by the
                system.
    """

    property_: str
    type_: BucketSchemaFieldType
    blob_id: str | Unset = UNSET
    key_prefix: None | str | Unset = UNSET
    properties: BlobModelProperties | Unset = UNSET
    details: BlobDetails | Unset = UNSET
    additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)

    def to_dict(self) -> dict[str, Any]:
        property_ = self.property_

        type_ = self.type_.value

        blob_id = self.blob_id

        key_prefix: None | str | Unset
        if isinstance(self.key_prefix, Unset):
            key_prefix = UNSET
        else:
            key_prefix = self.key_prefix

        properties: dict[str, Any] | Unset = UNSET
        if not isinstance(self.properties, Unset):
            properties = self.properties.to_dict()

        details: dict[str, Any] | Unset = UNSET
        if not isinstance(self.details, Unset):
            details = self.details.to_dict()

        field_dict: dict[str, Any] = {}
        field_dict.update(self.additional_properties)
        field_dict.update(
            {
                "property": property_,
                "type": type_,
            }
        )
        if blob_id is not UNSET:
            field_dict["blob_id"] = blob_id
        if key_prefix is not UNSET:
            field_dict["key_prefix"] = key_prefix
        if properties is not UNSET:
            field_dict["properties"] = properties
        if details is not UNSET:
            field_dict["details"] = details

        return field_dict

    @classmethod
    def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
        from ..models.blob_details import BlobDetails
        from ..models.blob_model_properties import BlobModelProperties

        d = dict(src_dict)
        property_ = d.pop("property")

        type_ = BucketSchemaFieldType(d.pop("type"))

        blob_id = d.pop("blob_id", UNSET)

        def _parse_key_prefix(data: object) -> None | str | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            return cast(None | str | Unset, data)

        key_prefix = _parse_key_prefix(d.pop("key_prefix", UNSET))

        _properties = d.pop("properties", UNSET)
        properties: BlobModelProperties | Unset
        if isinstance(_properties, Unset):
            properties = UNSET
        else:
            properties = BlobModelProperties.from_dict(_properties)

        _details = d.pop("details", UNSET)
        details: BlobDetails | Unset
        if isinstance(_details, Unset):
            details = UNSET
        else:
            details = BlobDetails.from_dict(_details)

        blob_model = cls(
            property_=property_,
            type_=type_,
            blob_id=blob_id,
            key_prefix=key_prefix,
            properties=properties,
            details=details,
        )

        blob_model.additional_properties = d
        return blob_model

    @property
    def additional_keys(self) -> list[str]:
        return list(self.additional_properties.keys())

    def __getitem__(self, key: str) -> Any:
        return self.additional_properties[key]

    def __setitem__(self, key: str, value: Any) -> None:
        self.additional_properties[key] = value

    def __delitem__(self, key: str) -> None:
        del self.additional_properties[key]

    def __contains__(self, key: str) -> bool:
        return key in self.additional_properties
