from __future__ import annotations

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

from attrs import define as _attrs_define
from attrs import field as _attrs_field
from dateutil.parser import isoparse

from ..models.model_response_finish_reason_type_0 import ModelResponseFinishReasonType0
from ..types import UNSET, Unset

if TYPE_CHECKING:
    from ..models.builtin_tool_call_part import BuiltinToolCallPart
    from ..models.builtin_tool_return_part import BuiltinToolReturnPart
    from ..models.file_part import FilePart
    from ..models.model_response_metadata_type_0 import ModelResponseMetadataType0
    from ..models.model_response_provider_details_type_0 import ModelResponseProviderDetailsType0
    from ..models.request_usage import RequestUsage
    from ..models.text_part import TextPart
    from ..models.thinking_part import ThinkingPart
    from ..models.tool_call_part import ToolCallPart


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


@_attrs_define
class ModelResponse:
    """
    Attributes:
        parts (list[BuiltinToolCallPart | BuiltinToolReturnPart | FilePart | TextPart | ThinkingPart | ToolCallPart]):
        usage (RequestUsage | Unset):
        model_name (None | str | Unset):
        timestamp (datetime.datetime | Unset):
        kind (Literal['response'] | Unset):  Default: 'response'.
        provider_name (None | str | Unset):
        provider_url (None | str | Unset):
        provider_details (ModelResponseProviderDetailsType0 | None | Unset):
        provider_response_id (None | str | Unset):
        finish_reason (ModelResponseFinishReasonType0 | None | Unset):
        run_id (None | str | Unset):
        metadata (ModelResponseMetadataType0 | None | Unset):
    """

    parts: list[BuiltinToolCallPart | BuiltinToolReturnPart | FilePart | TextPart | ThinkingPart | ToolCallPart]
    usage: RequestUsage | Unset = UNSET
    model_name: None | str | Unset = UNSET
    timestamp: datetime.datetime | Unset = UNSET
    kind: Literal["response"] | Unset = "response"
    provider_name: None | str | Unset = UNSET
    provider_url: None | str | Unset = UNSET
    provider_details: ModelResponseProviderDetailsType0 | None | Unset = UNSET
    provider_response_id: None | str | Unset = UNSET
    finish_reason: ModelResponseFinishReasonType0 | None | Unset = UNSET
    run_id: None | str | Unset = UNSET
    metadata: ModelResponseMetadataType0 | None | Unset = UNSET
    additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)

    def to_dict(self) -> dict[str, Any]:
        from ..models.builtin_tool_call_part import BuiltinToolCallPart
        from ..models.builtin_tool_return_part import BuiltinToolReturnPart
        from ..models.model_response_metadata_type_0 import ModelResponseMetadataType0
        from ..models.model_response_provider_details_type_0 import ModelResponseProviderDetailsType0
        from ..models.text_part import TextPart
        from ..models.thinking_part import ThinkingPart
        from ..models.tool_call_part import ToolCallPart

        parts = []
        for parts_item_data in self.parts:
            parts_item: dict[str, Any]
            if isinstance(parts_item_data, TextPart):
                parts_item = parts_item_data.to_dict()
            elif isinstance(parts_item_data, ToolCallPart):
                parts_item = parts_item_data.to_dict()
            elif isinstance(parts_item_data, BuiltinToolCallPart):
                parts_item = parts_item_data.to_dict()
            elif isinstance(parts_item_data, BuiltinToolReturnPart):
                parts_item = parts_item_data.to_dict()
            elif isinstance(parts_item_data, ThinkingPart):
                parts_item = parts_item_data.to_dict()
            else:
                parts_item = parts_item_data.to_dict()

            parts.append(parts_item)

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

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

        timestamp: str | Unset = UNSET
        if not isinstance(self.timestamp, Unset):
            timestamp = self.timestamp.isoformat()

        kind = self.kind

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

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

        provider_details: dict[str, Any] | None | Unset
        if isinstance(self.provider_details, Unset):
            provider_details = UNSET
        elif isinstance(self.provider_details, ModelResponseProviderDetailsType0):
            provider_details = self.provider_details.to_dict()
        else:
            provider_details = self.provider_details

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

        finish_reason: None | str | Unset
        if isinstance(self.finish_reason, Unset):
            finish_reason = UNSET
        elif isinstance(self.finish_reason, ModelResponseFinishReasonType0):
            finish_reason = self.finish_reason.value
        else:
            finish_reason = self.finish_reason

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

        metadata: dict[str, Any] | None | Unset
        if isinstance(self.metadata, Unset):
            metadata = UNSET
        elif isinstance(self.metadata, ModelResponseMetadataType0):
            metadata = self.metadata.to_dict()
        else:
            metadata = self.metadata

        field_dict: dict[str, Any] = {}
        field_dict.update(self.additional_properties)
        field_dict.update(
            {
                "parts": parts,
            }
        )
        if usage is not UNSET:
            field_dict["usage"] = usage
        if model_name is not UNSET:
            field_dict["model_name"] = model_name
        if timestamp is not UNSET:
            field_dict["timestamp"] = timestamp
        if kind is not UNSET:
            field_dict["kind"] = kind
        if provider_name is not UNSET:
            field_dict["provider_name"] = provider_name
        if provider_url is not UNSET:
            field_dict["provider_url"] = provider_url
        if provider_details is not UNSET:
            field_dict["provider_details"] = provider_details
        if provider_response_id is not UNSET:
            field_dict["provider_response_id"] = provider_response_id
        if finish_reason is not UNSET:
            field_dict["finish_reason"] = finish_reason
        if run_id is not UNSET:
            field_dict["run_id"] = run_id
        if metadata is not UNSET:
            field_dict["metadata"] = metadata

        return field_dict

    @classmethod
    def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
        from ..models.builtin_tool_call_part import BuiltinToolCallPart
        from ..models.builtin_tool_return_part import BuiltinToolReturnPart
        from ..models.file_part import FilePart
        from ..models.model_response_metadata_type_0 import ModelResponseMetadataType0
        from ..models.model_response_provider_details_type_0 import ModelResponseProviderDetailsType0
        from ..models.request_usage import RequestUsage
        from ..models.text_part import TextPart
        from ..models.thinking_part import ThinkingPart
        from ..models.tool_call_part import ToolCallPart

        d = dict(src_dict)
        parts = []
        _parts = d.pop("parts")
        for parts_item_data in _parts:

            def _parse_parts_item(
                data: object,
            ) -> BuiltinToolCallPart | BuiltinToolReturnPart | FilePart | TextPart | ThinkingPart | ToolCallPart:
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    parts_item_type_0 = TextPart.from_dict(data)

                    return parts_item_type_0
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    parts_item_type_1 = ToolCallPart.from_dict(data)

                    return parts_item_type_1
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    parts_item_type_2 = BuiltinToolCallPart.from_dict(data)

                    return parts_item_type_2
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    parts_item_type_3 = BuiltinToolReturnPart.from_dict(data)

                    return parts_item_type_3
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    parts_item_type_4 = ThinkingPart.from_dict(data)

                    return parts_item_type_4
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                if not isinstance(data, dict):
                    raise TypeError()
                parts_item_type_5 = FilePart.from_dict(data)

                return parts_item_type_5

            parts_item = _parse_parts_item(parts_item_data)

            parts.append(parts_item)

        _usage = d.pop("usage", UNSET)
        usage: RequestUsage | Unset
        if isinstance(_usage, Unset):
            usage = UNSET
        else:
            usage = RequestUsage.from_dict(_usage)

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

        model_name = _parse_model_name(d.pop("model_name", UNSET))

        _timestamp = d.pop("timestamp", UNSET)
        timestamp: datetime.datetime | Unset
        if isinstance(_timestamp, Unset):
            timestamp = UNSET
        else:
            timestamp = isoparse(_timestamp)

        kind = cast(Literal["response"] | Unset, d.pop("kind", UNSET))
        if kind != "response" and not isinstance(kind, Unset):
            raise ValueError(f"kind must match const 'response', got '{kind}'")

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

        provider_name = _parse_provider_name(d.pop("provider_name", UNSET))

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

        provider_url = _parse_provider_url(d.pop("provider_url", UNSET))

        def _parse_provider_details(data: object) -> ModelResponseProviderDetailsType0 | None | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            try:
                if not isinstance(data, dict):
                    raise TypeError()
                provider_details_type_0 = ModelResponseProviderDetailsType0.from_dict(data)

                return provider_details_type_0
            except (TypeError, ValueError, AttributeError, KeyError):
                pass
            return cast(ModelResponseProviderDetailsType0 | None | Unset, data)

        provider_details = _parse_provider_details(d.pop("provider_details", UNSET))

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

        provider_response_id = _parse_provider_response_id(d.pop("provider_response_id", UNSET))

        def _parse_finish_reason(data: object) -> ModelResponseFinishReasonType0 | None | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            try:
                if not isinstance(data, str):
                    raise TypeError()
                finish_reason_type_0 = ModelResponseFinishReasonType0(data)

                return finish_reason_type_0
            except (TypeError, ValueError, AttributeError, KeyError):
                pass
            return cast(ModelResponseFinishReasonType0 | None | Unset, data)

        finish_reason = _parse_finish_reason(d.pop("finish_reason", UNSET))

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

        run_id = _parse_run_id(d.pop("run_id", UNSET))

        def _parse_metadata(data: object) -> ModelResponseMetadataType0 | None | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            try:
                if not isinstance(data, dict):
                    raise TypeError()
                metadata_type_0 = ModelResponseMetadataType0.from_dict(data)

                return metadata_type_0
            except (TypeError, ValueError, AttributeError, KeyError):
                pass
            return cast(ModelResponseMetadataType0 | None | Unset, data)

        metadata = _parse_metadata(d.pop("metadata", UNSET))

        model_response = cls(
            parts=parts,
            usage=usage,
            model_name=model_name,
            timestamp=timestamp,
            kind=kind,
            provider_name=provider_name,
            provider_url=provider_url,
            provider_details=provider_details,
            provider_response_id=provider_response_id,
            finish_reason=finish_reason,
            run_id=run_id,
            metadata=metadata,
        )

        model_response.additional_properties = d
        return model_response

    @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
