# coding: utf-8

"""
    Instana REST API documentation

    Documentation for INSTANA REST API

    The version of the OpenAPI document: 1.309.1268
    Contact: support@instana.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, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from instana_client.models.database_integration import DatabaseIntegration
from instana_client.models.stack_trace_item import StackTraceItem
from typing import Optional, Set
from typing_extensions import Self

class SpanExcerpt(BaseModel):
    """
    Information about the logs attached to the call, if available.
    """ # noqa: E501
    data: Dict[str, Dict[str, Any]] = Field(description="Some information about the span, like service name, if it is an http call, then some information about it like, path, method, host, errors etc.")
    database_integrations: Optional[List[DatabaseIntegration]] = Field(default=None, alias="databaseIntegrations")
    duration: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(default=None, description="The total time taken for the entire operation of a call, from the moment the request was initiated to when the response was received. The time measured is in milliseconds. This is also known as latency of a call.")
    error_count: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(default=None, description="Represents whether the span is erroneous or not. 0 is not erroneous and 1 is erroneous.", alias="errorCount")
    foreign_parent_id: Optional[StrictStr] = Field(default=None, alias="foreignParentId")
    id: StrictStr = Field(description="The call ID. A unique identifier for an individual call. For example: `1bcad5c82338deaf`.")
    kind: StrictStr = Field(description="There are 4 types of span kind: 1. `ENTRY`: An entry span represents an incoming request into a traced service. 2. `EXIT`: An exit span represents an outgoing request that a service makes to some other service. 3. `INTERMEDIATE`: An intermediate span represents anything that happens inside a traced service where the flow of control neither enters nor leaves that service, but stays inside it. 4. `UNKNOWN`: Instana can't determine the span kind. ")
    name: StrictStr = Field(description="The technical type of the span. For example, `node.http.client` or `jdbc`.")
    parent_id: Optional[StrictStr] = Field(default=None, description="The parent call id, referring to another call in the same trace which triggered the processing associated with this call.", alias="parentId")
    stack_trace: List[StackTraceItem] = Field(description="For an erroneous call, if stack trace is available it will show a list of items containing file, method and line number of the code.", alias="stackTrace")
    start: Optional[Annotated[int, Field(strict=True, ge=1)]] = Field(default=None, description="The timestamp when the call or request was initiated. For example, Unix epoch time in milliseconds `1735532879870` is `Monday, 30 December 2024 04:27:59.870 GMT`")
    __properties: ClassVar[List[str]] = ["data", "databaseIntegrations", "duration", "errorCount", "foreignParentId", "id", "kind", "name", "parentId", "stackTrace", "start"]

    @field_validator('kind')
    def kind_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(['UNKNOWN', 'ENTRY', 'EXIT', 'INTERMEDIATE']):
            raise ValueError("must be one of enum values ('UNKNOWN', 'ENTRY', 'EXIT', 'INTERMEDIATE')")
        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 SpanExcerpt 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 each item in database_integrations (list)
        _items = []
        if self.database_integrations:
            for _item_database_integrations in self.database_integrations:
                if _item_database_integrations:
                    _items.append(_item_database_integrations.to_dict())
            _dict['databaseIntegrations'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in stack_trace (list)
        _items = []
        if self.stack_trace:
            for _item_stack_trace in self.stack_trace:
                if _item_stack_trace:
                    _items.append(_item_stack_trace.to_dict())
            _dict['stackTrace'] = _items
        return _dict

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

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

        _obj = cls.model_validate({
            "data": obj.get("data"),
            "databaseIntegrations": [DatabaseIntegration.from_dict(_item) for _item in obj["databaseIntegrations"]] if obj.get("databaseIntegrations") is not None else None,
            "duration": obj.get("duration"),
            "errorCount": obj.get("errorCount"),
            "foreignParentId": obj.get("foreignParentId"),
            "id": obj.get("id"),
            "kind": obj.get("kind"),
            "name": obj.get("name"),
            "parentId": obj.get("parentId"),
            "stackTrace": [StackTraceItem.from_dict(_item) for _item in obj["stackTrace"]] if obj.get("stackTrace") is not None else None,
            "start": obj.get("start")
        })
        return _obj


