# coding: utf-8

"""
    Mixpeek API

    This is the Mixpeek API, providing access to various endpoints for data processing and retrieval.

    The version of the OpenAPI document: 1.3.0
    Contact: info@mixpeek.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 datetime import datetime
from pydantic import BaseModel, ConfigDict, Field, StrictBool, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from mixpeek.models.webhook_channel_output import WebhookChannelOutput
from mixpeek.models.webhook_event_type import WebhookEventType
from typing import Optional, Set
from typing_extensions import Self

class WebhookOutput(BaseModel):
    """
    Configured webhook subscription for organization event notifications.  Webhooks enable real-time notifications when events occur in the system. Each webhook subscribes to specific event types and delivers notifications via one or more configured channels (Slack, email, HTTP).  Webhook Lifecycle:     1. Created with event_types and channels configured     2. is_active=True enables notification delivery     3. Events matching event_types trigger notifications to all channels     4. is_active=False temporarily pauses notifications without deletion     5. Webhook can be updated to add/remove event types or channels     6. Permanent deletion removes the webhook configuration  Use Cases:     - Integrate Mixpeek events with external systems via HTTP webhooks     - Notify teams in Slack when ingestion jobs complete     - Send email alerts when critical failures occur     - Trigger automated workflows based on state changes     - Maintain audit trails by forwarding events to SIEM systems  Best Practices:     - Subscribe only to events you need (reduces noise)     - Use descriptive webhook_name for identification     - Configure multiple channels for critical events (redundancy)     - Set is_active=False to temporarily disable without losing config     - Monitor webhook delivery failures via last_error tracking
    """ # noqa: E501
    webhook_id: Optional[Annotated[str, Field(strict=True)]] = Field(default=None, description="Unique identifier for the webhook. Auto-generated with 'wh_' prefix followed by secure random token. Format: wh_{16-character hex}. Used for API operations and event tracking.")
    webhook_name: Annotated[str, Field(min_length=1, strict=True, max_length=200)] = Field(description="REQUIRED. Human-readable name for the webhook. Displayed in dashboards, logs, and notification metadata. Should describe the webhook's purpose or destination. Format: 1-200 characters.")
    event_types: Annotated[List[WebhookEventType], Field(min_length=1)] = Field(description="REQUIRED. List of event types that trigger this webhook. When any of these events occur, notifications are sent to all channels. Must contain at least one event type. Common patterns: - ['object.created', 'object.updated'] for object lifecycle tracking - ['cluster.execution.completed', 'cluster.execution.failed'] for job monitoring - ['*'] for all events (use cautiously, high volume)")
    channels: Annotated[List[WebhookChannelOutput], Field(min_length=1)] = Field(description="REQUIRED. List of notification channels for event delivery. When an event occurs, notifications are sent to ALL configured channels. Must contain at least one channel. Multiple channels provide redundancy and multi-audience delivery. Example: Send to both Slack (team) and email (manager) for critical events.")
    is_active: Optional[StrictBool] = Field(default=True, description="Whether the webhook is currently active and should send notifications. True: Events trigger notifications to channels. False: Webhook is paused, no notifications sent but config preserved. Use to temporarily disable webhooks without losing configuration. Default: True")
    created_at: Optional[datetime] = Field(default=None, description="UTC timestamp when the webhook was created. Auto-generated at creation time. Immutable after creation. Format: ISO 8601 datetime.")
    updated_at: Optional[datetime] = Field(default=None, description="UTC timestamp of the most recent webhook update. Updated automatically when event_types, channels, or is_active changes. Tracks configuration modifications. Format: ISO 8601 datetime.")
    __properties: ClassVar[List[str]] = ["webhook_id", "webhook_name", "event_types", "channels", "is_active", "created_at", "updated_at"]

    @field_validator('webhook_id')
    def webhook_id_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if value is None:
            return value

        if not re.match(r"^wh_[a-fA-F0-9]{16}$", value):
            raise ValueError(r"must validate the regular expression /^wh_[a-fA-F0-9]{16}$/")
        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 WebhookOutput 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 channels (list)
        _items = []
        if self.channels:
            for _item_channels in self.channels:
                if _item_channels:
                    _items.append(_item_channels.to_dict())
            _dict['channels'] = _items
        return _dict

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

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

        _obj = cls.model_validate({
            "webhook_id": obj.get("webhook_id"),
            "webhook_name": obj.get("webhook_name"),
            "event_types": obj.get("event_types"),
            "channels": [WebhookChannelOutput.from_dict(_item) for _item in obj["channels"]] if obj.get("channels") is not None else None,
            "is_active": obj.get("is_active") if obj.get("is_active") is not None else True,
            "created_at": obj.get("created_at"),
            "updated_at": obj.get("updated_at")
        })
        return _obj


