# 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, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from instana_client.models.action_instance_metadata_entry import ActionInstanceMetadataEntry
from instana_client.models.action_instance_parameter import ActionInstanceParameter
from typing import Optional, Set
from typing_extensions import Self

class ActionInstance(BaseModel):
    """
    ActionInstance
    """ # noqa: E501
    action_description: Optional[StrictStr] = Field(default=None, description="Action description of the action to run.", alias="actionDescription")
    action_id: StrictStr = Field(description="Action identifier of the action to run.", alias="actionId")
    action_instance_id: Optional[StrictStr] = Field(default=None, description="Action run identifier.", alias="actionInstanceId")
    action_name: StrictStr = Field(description="Action name of the action to run.", alias="actionName")
    action_snapshot: Optional[StrictStr] = Field(default=None, description="Snapshot of the action definition.", alias="actionSnapshot")
    actor_id: Optional[StrictStr] = Field(default=None, description="User identifier, API token or the policy identifier that started the action run.", alias="actorId")
    actor_name: Optional[StrictStr] = Field(default=None, description="Name of the user, API token or the policy that started the action run.", alias="actorName")
    actor_type: Optional[StrictStr] = Field(default=None, description="Type of Actor. Valid values are listed in the enum definition.", alias="actorType")
    created_date: Optional[StrictInt] = Field(default=None, description="Action run created timestamp. The timestamp at which the action run got submitted.", alias="createdDate")
    end_date: Optional[StrictInt] = Field(default=None, description="Action run end timestamp. The timestamp at which the action run ended on the agent host.", alias="endDate")
    error_message: Optional[StrictStr] = Field(default=None, description="Error message, if any, of action run on the agent host.", alias="errorMessage")
    event_entity_type: Optional[StrictStr] = Field(default=None, description="Event entity type set in the event that triggered this action run.", alias="eventEntityType")
    event_id: Optional[StrictStr] = Field(default=None, description="Event identifier of the event that triggered this action run.", alias="eventId")
    event_specification_id: Optional[StrictStr] = Field(default=None, description="Event specification identifier of the event that triggered this action run.", alias="eventSpecificationId")
    external_source_type: Optional[StrictStr] = Field(default=None, description="If the action type is external this field contains the name of the external source.", alias="externalSourceType")
    host_snapshot_id: Optional[StrictStr] = Field(default=None, description="Host snapshot identifier of the agent on which the action ran.", alias="hostSnapshotId")
    input_parameters: Optional[List[ActionInstanceParameter]] = Field(default=None, description="List of input parameters to this action run.", alias="inputParameters")
    metadata: Optional[List[ActionInstanceMetadataEntry]] = Field(default=None, description="List of metadata parameters set to this action run by sensors.")
    output: Optional[StrictStr] = Field(default=None, description="Action run output.")
    policy_id: Optional[StrictStr] = Field(default=None, description="Identifier of the policy that triggered this action run.", alias="policyId")
    problem_text: Optional[StrictStr] = Field(default=None, description="Event problem text of the event that triggered this action run.", alias="problemText")
    return_code: Optional[StrictInt] = Field(default=None, description="Return code of action run on the agent host.", alias="returnCode")
    start_date: Optional[StrictInt] = Field(default=None, description="Action run start timestamp. The timestamp at which the action run started on the agent host.", alias="startDate")
    status: Optional[StrictStr] = Field(default=None, description="Action run status. Valid values are listed in the enum definition.")
    target_snapshot_id: Optional[StrictStr] = Field(default=None, description="Action target entity identifier set in the event that triggered this action run. This is the identifier of the entity on which an incident or issue was raised.", alias="targetSnapshotId")
    type: StrictStr = Field(description="Action type. Valid values are listed in the enum definition.")
    __properties: ClassVar[List[str]] = ["actionDescription", "actionId", "actionInstanceId", "actionName", "actionSnapshot", "actorId", "actorName", "actorType", "createdDate", "endDate", "errorMessage", "eventEntityType", "eventId", "eventSpecificationId", "externalSourceType", "hostSnapshotId", "inputParameters", "metadata", "output", "policyId", "problemText", "returnCode", "startDate", "status", "targetSnapshotId", "type"]

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

        if value not in set(['ACTOR_UNKNOWN', 'USER', 'APITOKEN', 'POLICY']):
            raise ValueError("must be one of enum values ('ACTOR_UNKNOWN', 'USER', 'APITOKEN', 'POLICY')")
        return value

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

        if value not in set(['STATUS_UNKNOWN', 'SUBMITTED', 'IN_PROGRESS', 'SUCCESS', 'FAILED', 'READY', 'TIMEOUT']):
            raise ValueError("must be one of enum values ('STATUS_UNKNOWN', 'SUBMITTED', 'IN_PROGRESS', 'SUCCESS', 'FAILED', 'READY', 'TIMEOUT')")
        return value

    @field_validator('type')
    def type_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(['SCRIPT', 'HTTP', 'ANSIBLE', 'EXTERNAL', 'GITHUB', 'GITLAB', 'JIRA', 'MANUAL', 'DOC_LINK']):
            raise ValueError("must be one of enum values ('SCRIPT', 'HTTP', 'ANSIBLE', 'EXTERNAL', 'GITHUB', 'GITLAB', 'JIRA', 'MANUAL', 'DOC_LINK')")
        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 ActionInstance 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.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        """
        excluded_fields: Set[str] = set([
            "action_instance_id",
            "action_snapshot",
        ])

        _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 input_parameters (list)
        _items = []
        if self.input_parameters:
            for _item_input_parameters in self.input_parameters:
                if _item_input_parameters:
                    _items.append(_item_input_parameters.to_dict())
            _dict['inputParameters'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in metadata (list)
        _items = []
        if self.metadata:
            for _item_metadata in self.metadata:
                if _item_metadata:
                    _items.append(_item_metadata.to_dict())
            _dict['metadata'] = _items
        return _dict

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

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

        _obj = cls.model_validate({
            "actionDescription": obj.get("actionDescription"),
            "actionId": obj.get("actionId"),
            "actionInstanceId": obj.get("actionInstanceId"),
            "actionName": obj.get("actionName"),
            "actionSnapshot": obj.get("actionSnapshot"),
            "actorId": obj.get("actorId"),
            "actorName": obj.get("actorName"),
            "actorType": obj.get("actorType"),
            "createdDate": obj.get("createdDate"),
            "endDate": obj.get("endDate"),
            "errorMessage": obj.get("errorMessage"),
            "eventEntityType": obj.get("eventEntityType"),
            "eventId": obj.get("eventId"),
            "eventSpecificationId": obj.get("eventSpecificationId"),
            "externalSourceType": obj.get("externalSourceType"),
            "hostSnapshotId": obj.get("hostSnapshotId"),
            "inputParameters": [ActionInstanceParameter.from_dict(_item) for _item in obj["inputParameters"]] if obj.get("inputParameters") is not None else None,
            "metadata": [ActionInstanceMetadataEntry.from_dict(_item) for _item in obj["metadata"]] if obj.get("metadata") is not None else None,
            "output": obj.get("output"),
            "policyId": obj.get("policyId"),
            "problemText": obj.get("problemText"),
            "returnCode": obj.get("returnCode"),
            "startDate": obj.get("startDate"),
            "status": obj.get("status"),
            "targetSnapshotId": obj.get("targetSnapshotId"),
            "type": obj.get("type")
        })
        return _obj


