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 ..types import UNSET, Unset

if TYPE_CHECKING:
    from ..models.model_request_metadata_type_0 import ModelRequestMetadataType0
    from ..models.retry_prompt_part import RetryPromptPart
    from ..models.system_prompt_part import SystemPromptPart
    from ..models.tool_return_part import ToolReturnPart
    from ..models.user_prompt_part import UserPromptPart


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


@_attrs_define
class ModelRequest:
    """
    Attributes:
        parts (list[RetryPromptPart | SystemPromptPart | ToolReturnPart | UserPromptPart]):
        timestamp (datetime.datetime | None | Unset):
        instructions (None | str | Unset):
        kind (Literal['request'] | Unset):  Default: 'request'.
        run_id (None | str | Unset):
        metadata (ModelRequestMetadataType0 | None | Unset):
    """

    parts: list[RetryPromptPart | SystemPromptPart | ToolReturnPart | UserPromptPart]
    timestamp: datetime.datetime | None | Unset = UNSET
    instructions: None | str | Unset = UNSET
    kind: Literal["request"] | Unset = "request"
    run_id: None | str | Unset = UNSET
    metadata: ModelRequestMetadataType0 | None | Unset = UNSET
    additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)

    def to_dict(self) -> dict[str, Any]:
        from ..models.model_request_metadata_type_0 import ModelRequestMetadataType0
        from ..models.system_prompt_part import SystemPromptPart
        from ..models.tool_return_part import ToolReturnPart
        from ..models.user_prompt_part import UserPromptPart

        parts = []
        for parts_item_data in self.parts:
            parts_item: dict[str, Any]
            if isinstance(parts_item_data, SystemPromptPart):
                parts_item = parts_item_data.to_dict()
            elif isinstance(parts_item_data, UserPromptPart):
                parts_item = parts_item_data.to_dict()
            elif isinstance(parts_item_data, ToolReturnPart):
                parts_item = parts_item_data.to_dict()
            else:
                parts_item = parts_item_data.to_dict()

            parts.append(parts_item)

        timestamp: None | str | Unset
        if isinstance(self.timestamp, Unset):
            timestamp = UNSET
        elif isinstance(self.timestamp, datetime.datetime):
            timestamp = self.timestamp.isoformat()
        else:
            timestamp = self.timestamp

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

        kind = self.kind

        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, ModelRequestMetadataType0):
            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 timestamp is not UNSET:
            field_dict["timestamp"] = timestamp
        if instructions is not UNSET:
            field_dict["instructions"] = instructions
        if kind is not UNSET:
            field_dict["kind"] = kind
        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.model_request_metadata_type_0 import ModelRequestMetadataType0
        from ..models.retry_prompt_part import RetryPromptPart
        from ..models.system_prompt_part import SystemPromptPart
        from ..models.tool_return_part import ToolReturnPart
        from ..models.user_prompt_part import UserPromptPart

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

            def _parse_parts_item(data: object) -> RetryPromptPart | SystemPromptPart | ToolReturnPart | UserPromptPart:
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    parts_item_type_0 = SystemPromptPart.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 = UserPromptPart.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 = ToolReturnPart.from_dict(data)

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

                return parts_item_type_3

            parts_item = _parse_parts_item(parts_item_data)

            parts.append(parts_item)

        def _parse_timestamp(data: object) -> datetime.datetime | None | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            try:
                if not isinstance(data, str):
                    raise TypeError()
                timestamp_type_0 = isoparse(data)

                return timestamp_type_0
            except (TypeError, ValueError, AttributeError, KeyError):
                pass
            return cast(datetime.datetime | None | Unset, data)

        timestamp = _parse_timestamp(d.pop("timestamp", UNSET))

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

        instructions = _parse_instructions(d.pop("instructions", UNSET))

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

        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) -> ModelRequestMetadataType0 | 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 = ModelRequestMetadataType0.from_dict(data)

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

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

        model_request = cls(
            parts=parts,
            timestamp=timestamp,
            instructions=instructions,
            kind=kind,
            run_id=run_id,
            metadata=metadata,
        )

        model_request.additional_properties = d
        return model_request

    @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
