# coding: utf-8

"""
    STACKIT Audit Log API

    API Endpoints to retrieve recorded actions and resulting changes in the system.  ### Documentation The user documentation with explanations how to use the api can be found  [here](https://docs.stackit.cloud/stackit/en/retrieve-audit-log-per-api-request-134415907.html).  ### Audit Logging Changes on organizations, folders and projects and respective cloud resources are logged and collected in the audit  log.  ### API Constraints The audit log API allows to download messages from the last 90 days. The maximum duration that can be queried at  once is 24 hours. Requests are rate limited - the current maximum is 60 requests per minute.

    The version of the OpenAPI document: 2.0
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501

from __future__ import annotations

import json
import pprint
import re  # noqa: F401
from datetime import datetime
from typing import Any, ClassVar, Dict, List, Optional, Set

from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator
from typing_extensions import Annotated, Self

from stackit.auditlog.models.audit_log_entry_context_response import (
    AuditLogEntryContextResponse,
)
from stackit.auditlog.models.audit_log_entry_initiator_response import (
    AuditLogEntryInitiatorResponse,
)
from stackit.auditlog.models.audit_log_entry_request_response import (
    AuditLogEntryRequestResponse,
)
from stackit.auditlog.models.audit_log_entry_service_account_delegation_info_response import (
    AuditLogEntryServiceAccountDelegationInfoResponse,
)


class AuditLogEntryResponse(BaseModel):
    """
    AuditLogEntryResponse
    """  # noqa: E501

    context: Optional[AuditLogEntryContextResponse] = None
    correlation_id: Optional[Annotated[str, Field(min_length=1, strict=True, max_length=255)]] = Field(
        default=None,
        description="Unique ID which identifies the request from the sender point of view.",
        alias="correlationId",
    )
    details: Optional[Dict[str, Any]] = Field(
        default=None,
        description="Additional information about the event that is not part of the request or response. May contain arbitrary data.",
    )
    event_name: Annotated[str, Field(min_length=1, strict=True, max_length=255)] = Field(
        description="Name of the operation this event represents.", alias="eventName"
    )
    event_source: StrictStr = Field(
        description="The service in which the causing event was handled.", alias="eventSource"
    )
    event_time_stamp: datetime = Field(
        description="Timestamp at which the event was triggered.", alias="eventTimeStamp"
    )
    event_type: StrictStr = Field(
        description='Type that can be assigned to the event. For example, an event "Organization created" can be assigned to the type ADMIN_EVENT',
        alias="eventType",
    )
    event_version: StrictStr = Field(description="Version of the log event format.", alias="eventVersion")
    id: StrictStr = Field(description="Unique ID generated by the audit log.")
    initiator: AuditLogEntryInitiatorResponse
    received_time_stamp: datetime = Field(
        description="Timestamp at which the event was received by the audit log.", alias="receivedTimeStamp"
    )
    region: StrictStr = Field(description="Region from which the event has been emitted.")
    request: AuditLogEntryRequestResponse
    resource_id: Optional[Annotated[str, Field(min_length=1, strict=True, max_length=255)]] = Field(
        default=None, description="Unique id of the resource that is target of the operation", alias="resourceId"
    )
    resource_name: Optional[Annotated[str, Field(min_length=1, strict=True, max_length=255)]] = Field(
        default=None, description="Name of the resource that is target of the operation", alias="resourceName"
    )
    result: Optional[Dict[str, Any]] = Field(
        default=None,
        description="Object representing the change resulting from this event. May be omitted if no change has been applied. May contain arbitrary data.",
    )
    service_account_delegation_info: Optional[AuditLogEntryServiceAccountDelegationInfoResponse] = Field(
        default=None, alias="serviceAccountDelegationInfo"
    )
    severity: StrictStr = Field(description="The severity of this request.")
    source_ip_address: StrictStr = Field(
        description="IP address that the request was made from", alias="sourceIpAddress"
    )
    user_agent: Annotated[str, Field(min_length=1, strict=True, max_length=255)] = Field(
        description="Agent through which the request was made from (e.g. Portal, CLI, SDK, ...) ", alias="userAgent"
    )
    visibility: StrictStr = Field(
        description="PUBLIC for entries that are intended for end users, while PRIVATE entries can only be viewed with system privileges."
    )
    __properties: ClassVar[List[str]] = [
        "context",
        "correlationId",
        "details",
        "eventName",
        "eventSource",
        "eventTimeStamp",
        "eventType",
        "eventVersion",
        "id",
        "initiator",
        "receivedTimeStamp",
        "region",
        "request",
        "resourceId",
        "resourceName",
        "result",
        "serviceAccountDelegationInfo",
        "severity",
        "sourceIpAddress",
        "userAgent",
        "visibility",
    ]

    @field_validator("event_time_stamp", mode="before")
    def event_time_stamp_change_year_zero_to_one(cls, value):
        """Workaround which prevents year 0 issue"""
        if isinstance(value, str):
            # Check for year "0000" at the beginning of the string
            # This assumes common date formats like YYYY-MM-DDTHH:MM:SS+00:00 or YYYY-MM-DDTHH:MM:SSZ
            if value.startswith("0000-01-01T") and re.match(
                r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\+\d{2}:\d{2}|Z)$", value
            ):
                # Workaround: Replace "0000" with "0001"
                return "0001" + value[4:]  # Take "0001" and append the rest of the string
        return value

    @field_validator("event_type")
    def event_type_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(["ADMIN_ACTIVITY", "SYSTEM_EVENT", "POLICY_DENIED"]):
            raise ValueError("must be one of enum values ('ADMIN_ACTIVITY', 'SYSTEM_EVENT', 'POLICY_DENIED')")
        return value

    @field_validator("received_time_stamp", mode="before")
    def received_time_stamp_change_year_zero_to_one(cls, value):
        """Workaround which prevents year 0 issue"""
        if isinstance(value, str):
            # Check for year "0000" at the beginning of the string
            # This assumes common date formats like YYYY-MM-DDTHH:MM:SS+00:00 or YYYY-MM-DDTHH:MM:SSZ
            if value.startswith("0000-01-01T") and re.match(
                r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\+\d{2}:\d{2}|Z)$", value
            ):
                # Workaround: Replace "0000" with "0001"
                return "0001" + value[4:]  # Take "0001" and append the rest of the string
        return value

    @field_validator("severity")
    def severity_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(["INFO", "ERROR"]):
            raise ValueError("must be one of enum values ('INFO', 'ERROR')")
        return value

    @field_validator("visibility")
    def visibility_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(["PUBLIC", "PRIVATE"]):
            raise ValueError("must be one of enum values ('PUBLIC', 'PRIVATE')")
        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 AuditLogEntryResponse 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 context
        if self.context:
            _dict["context"] = self.context.to_dict()
        # override the default output from pydantic by calling `to_dict()` of initiator
        if self.initiator:
            _dict["initiator"] = self.initiator.to_dict()
        # override the default output from pydantic by calling `to_dict()` of request
        if self.request:
            _dict["request"] = self.request.to_dict()
        # override the default output from pydantic by calling `to_dict()` of service_account_delegation_info
        if self.service_account_delegation_info:
            _dict["serviceAccountDelegationInfo"] = self.service_account_delegation_info.to_dict()
        return _dict

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

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

        _obj = cls.model_validate(
            {
                "context": (
                    AuditLogEntryContextResponse.from_dict(obj["context"]) if obj.get("context") is not None else None
                ),
                "correlationId": obj.get("correlationId"),
                "details": obj.get("details"),
                "eventName": obj.get("eventName"),
                "eventSource": obj.get("eventSource"),
                "eventTimeStamp": obj.get("eventTimeStamp"),
                "eventType": obj.get("eventType"),
                "eventVersion": obj.get("eventVersion"),
                "id": obj.get("id"),
                "initiator": (
                    AuditLogEntryInitiatorResponse.from_dict(obj["initiator"])
                    if obj.get("initiator") is not None
                    else None
                ),
                "receivedTimeStamp": obj.get("receivedTimeStamp"),
                "region": obj.get("region"),
                "request": (
                    AuditLogEntryRequestResponse.from_dict(obj["request"]) if obj.get("request") is not None else None
                ),
                "resourceId": obj.get("resourceId"),
                "resourceName": obj.get("resourceName"),
                "result": obj.get("result"),
                "serviceAccountDelegationInfo": (
                    AuditLogEntryServiceAccountDelegationInfoResponse.from_dict(obj["serviceAccountDelegationInfo"])
                    if obj.get("serviceAccountDelegationInfo") is not None
                    else None
                ),
                "severity": obj.get("severity"),
                "sourceIpAddress": obj.get("sourceIpAddress"),
                "userAgent": obj.get("userAgent"),
                "visibility": obj.get("visibility"),
            }
        )
        return _obj
