# coding: utf-8

"""
    ibl-data-manager

    API for iblai

    The version of the OpenAPI document: 4.202.1-ai-plus
    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, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from uuid import UUID
from iblai.models.consumer_channel import ConsumerChannel
from iblai.models.human_support_recipient_mode_enum import HumanSupportRecipientModeEnum
from iblai.models.periodic_frequency_enum import PeriodicFrequencyEnum
from iblai.models.periodic_learner_scope_enum import PeriodicLearnerScopeEnum
from iblai.models.spa import Spa
from typing import Optional, Set
from typing_extensions import Self

class PatchedNotificationTemplateDetail(BaseModel):
    """
    Serializer for detailed template view and editing
    """ # noqa: E501
    id: Optional[UUID] = Field(default=None, description="Unique identifier for this notification template.")
    type: Optional[StrictStr] = Field(default=None, description="Select the type of notification from the available options.  * `ADMIN_NOTIF_COURSE_ENROLLMENT` - Admin Notif Course Enrollment * `APP_REGISTRATION` - App Registration * `COURSE_INVITATION` - Course Invitation * `COURSE_LICENSE_ASSIGNMENT` - Course License Assignment * `COURSE_LICENSE_GROUP_ASSIGNMENT` - Course License Group Assignment * `CUSTOM_NOTIFICATION` - Custom Notification * `DEFAULT_TEMPLATE` - Default Template * `HUMAN_SUPPORT_NOTIFICATION` - Human Support Notification * `PLATFORM_INVITATION` - Platform Invitation * `POLICY_ASSIGNMENT` - Policy Assignment * `PROACTIVE_LEARNER_NOTIFICATION` - Proactive Learner Notification * `PROGRAM_INVITATION` - Program Invitation * `PROGRAM_LICENSE_ASSIGNMENT` - Program License Assignment * `PROGRAM_LICENSE_GROUP_ASSIGNMENT` - Program License Group Assignment * `REPORT_COMPLETED` - Report Completed * `ROLE_CHANGE` - Role Change * `USER_LICENSE_ASSIGNMENT` - User License Assignment * `USER_LICENSE_GROUP_ASSIGNMENT` - User License Group Assignment * `USER_NOTIF_COURSE_COMPLETION` - User Notif Course Completion * `USER_NOTIF_COURSE_ENROLLMENT` - User Notif Course Enrollment * `USER_NOTIF_CREDENTIALS` - User Notif Credentials * `USER_NOTIF_LEARNER_PROGRESS` - User Notif Learner Progress * `USER_NOTIF_USER_INACTIVITY` - User Notif User Inactivity * `USER_NOTIF_USER_REGISTRATION` - User Notif User Registration")
    name: Optional[Annotated[str, Field(strict=True, max_length=255)]] = Field(default=None, description="Template display name")
    description: Optional[StrictStr] = Field(default=None, description="Description of when this notification is sent")
    message_title: Optional[Annotated[str, Field(strict=True, max_length=255)]] = Field(default=None, description="Title for push/in-app notifications")
    message_body: Optional[StrictStr] = Field(default=None, description="Body text (supports Django template syntax)")
    short_message_body: Optional[StrictStr] = Field(default=None, description="Short version for SMS or preview")
    email_subject: Optional[Annotated[str, Field(strict=True, max_length=255)]] = Field(default=None, description="Email subject line (supports {{ variables }})")
    email_from_address: Optional[Annotated[str, Field(strict=True, max_length=255)]] = Field(default=None, description="Sender email address")
    email_html_template: Optional[StrictStr] = Field(default=None, description="HTML email body (supports Django template syntax)")
    spas_detail: Optional[List[Spa]] = None
    allowed_channels_detail: Optional[List[ConsumerChannel]] = None
    spa_ids: Optional[List[StrictInt]] = Field(default=None, description="IDs of SPAs that can use this template")
    channel_ids: Optional[List[StrictInt]] = Field(default=None, description="IDs of delivery channels (email, push, etc.)")
    is_inherited: Optional[StrictBool] = Field(default=None, description="True if using main platform template (no platform override)")
    is_enabled: Optional[StrictBool] = Field(default=None, description="True if notification is enabled for this platform")
    source_platform: Optional[StrictStr] = Field(default=None, description="Platform key of the template source")
    can_customize: Optional[StrictBool] = Field(default=None, description="True if platform admin can edit template content")
    metadata: Optional[Any] = Field(default=None, description="JSON config (periodic_config, policy_config, etc.)")
    available_context: Optional[StrictStr] = Field(default=None, description="Context variables available for template rendering")
    proactive_prompt_message: Optional[StrictStr] = Field(default=None, description="Default prompt message for AI mentor notifications")
    periodic_config: Optional[StrictStr] = Field(default=None, description="Periodic report configuration (PROACTIVE_LEARNER_NOTIFICATION only)")
    periodic_learner_scope: Optional[PeriodicLearnerScopeEnum] = Field(default=None, description="Which learners to include: ACTIVE_LEARNERS or ALL_LEARNERS  * `ACTIVE_LEARNERS` - ACTIVE_LEARNERS * `ALL_LEARNERS` - ALL_LEARNERS")
    periodic_report_period_days: Optional[Annotated[int, Field(le=365, strict=True, ge=1)]] = Field(default=None, description="Number of days to include in the report period")
    periodic_frequency: Optional[PeriodicFrequencyEnum] = Field(default=None, description="How often to send: DAILY, WEEKLY, MONTHLY, or CUSTOM  * `DAILY` - DAILY * `WEEKLY` - WEEKLY * `MONTHLY` - MONTHLY * `CUSTOM` - CUSTOM")
    periodic_custom_interval_days: Optional[Annotated[int, Field(le=365, strict=True, ge=1)]] = Field(default=None, description="Custom interval in days (when frequency is CUSTOM)")
    periodic_execution_time: Optional[StrictStr] = Field(default=None, description="Time to run in HH:MM format (24-hour)")
    periodic_timezone: Optional[StrictStr] = Field(default=None, description="Timezone for execution time (e.g. America/New_York)")
    periodic_mentors: Optional[List[Dict[str, Any]]] = Field(default=None, description="List of mentor configurations: [{\"unique_id\": \"uuid\", \"prompt\": \"...\", \"name\": \"...\"}]")
    policy_config: Optional[StrictStr] = Field(default=None, description="Policy assignment notification config (POLICY_ASSIGNMENT only)")
    policy_enabled_policies: Optional[List[Dict[str, Any]]] = Field(default=None, description="Per-role config: [{\"role_name\": \"Analytics Viewer\", \"enabled\": True, \"subject\": \"Custom subject for {{role_name}}\"}, ...]")
    policy_notify_on_assignment: Optional[StrictBool] = Field(default=None, description="Send notification when policy is assigned")
    policy_notify_on_removal: Optional[StrictBool] = Field(default=None, description="Send notification when policy is removed")
    human_support_config: Optional[StrictStr] = Field(default=None, description="Human support notification config (HUMAN_SUPPORT_NOTIFICATION only)")
    human_support_recipient_mode: Optional[HumanSupportRecipientModeEnum] = Field(default=None, description="Who receives human support ticket notifications  * `platform_admins_and_mentor_owner` - platform_admins_and_mentor_owner * `platform_admins_only` - platform_admins_only * `mentor_owner_only` - mentor_owner_only * `custom` - custom")
    human_support_custom_recipients: Optional[List[Dict[str, Any]]] = Field(default=None, description="Custom targets: user: {type, id}; user_group: {type, id}; rbac_policy: {type, policy_name}")
    created_at: Optional[datetime] = Field(default=None, description="Timestamp when this template was created")
    updated_at: Optional[datetime] = Field(default=None, description="Timestamp when this template was last updated")
    __properties: ClassVar[List[str]] = ["id", "type", "name", "description", "message_title", "message_body", "short_message_body", "email_subject", "email_from_address", "email_html_template", "spas_detail", "allowed_channels_detail", "spa_ids", "channel_ids", "is_inherited", "is_enabled", "source_platform", "can_customize", "metadata", "available_context", "proactive_prompt_message", "periodic_config", "periodic_learner_scope", "periodic_report_period_days", "periodic_frequency", "periodic_custom_interval_days", "periodic_execution_time", "periodic_timezone", "periodic_mentors", "policy_config", "policy_enabled_policies", "policy_notify_on_assignment", "policy_notify_on_removal", "human_support_config", "human_support_recipient_mode", "human_support_custom_recipients", "created_at", "updated_at"]

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

        if value not in set(['ADMIN_NOTIF_COURSE_ENROLLMENT', 'APP_REGISTRATION', 'COURSE_INVITATION', 'COURSE_LICENSE_ASSIGNMENT', 'COURSE_LICENSE_GROUP_ASSIGNMENT', 'CUSTOM_NOTIFICATION', 'DEFAULT_TEMPLATE', 'HUMAN_SUPPORT_NOTIFICATION', 'PLATFORM_INVITATION', 'POLICY_ASSIGNMENT', 'PROACTIVE_LEARNER_NOTIFICATION', 'PROGRAM_INVITATION', 'PROGRAM_LICENSE_ASSIGNMENT', 'PROGRAM_LICENSE_GROUP_ASSIGNMENT', 'REPORT_COMPLETED', 'ROLE_CHANGE', 'USER_LICENSE_ASSIGNMENT', 'USER_LICENSE_GROUP_ASSIGNMENT', 'USER_NOTIF_COURSE_COMPLETION', 'USER_NOTIF_COURSE_ENROLLMENT', 'USER_NOTIF_CREDENTIALS', 'USER_NOTIF_LEARNER_PROGRESS', 'USER_NOTIF_USER_INACTIVITY', 'USER_NOTIF_USER_REGISTRATION']):
            raise ValueError("must be one of enum values ('ADMIN_NOTIF_COURSE_ENROLLMENT', 'APP_REGISTRATION', 'COURSE_INVITATION', 'COURSE_LICENSE_ASSIGNMENT', 'COURSE_LICENSE_GROUP_ASSIGNMENT', 'CUSTOM_NOTIFICATION', 'DEFAULT_TEMPLATE', 'HUMAN_SUPPORT_NOTIFICATION', 'PLATFORM_INVITATION', 'POLICY_ASSIGNMENT', 'PROACTIVE_LEARNER_NOTIFICATION', 'PROGRAM_INVITATION', 'PROGRAM_LICENSE_ASSIGNMENT', 'PROGRAM_LICENSE_GROUP_ASSIGNMENT', 'REPORT_COMPLETED', 'ROLE_CHANGE', 'USER_LICENSE_ASSIGNMENT', 'USER_LICENSE_GROUP_ASSIGNMENT', 'USER_NOTIF_COURSE_COMPLETION', 'USER_NOTIF_COURSE_ENROLLMENT', 'USER_NOTIF_CREDENTIALS', 'USER_NOTIF_LEARNER_PROGRESS', 'USER_NOTIF_USER_INACTIVITY', 'USER_NOTIF_USER_REGISTRATION')")
        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 PatchedNotificationTemplateDetail 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.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        """
        excluded_fields: Set[str] = set([
            "id",
            "type",
            "spas_detail",
            "allowed_channels_detail",
            "is_inherited",
            "is_enabled",
            "source_platform",
            "can_customize",
            "available_context",
            "periodic_config",
            "policy_config",
            "human_support_config",
            "created_at",
            "updated_at",
        ])

        _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 spas_detail (list)
        _items = []
        if self.spas_detail:
            for _item_spas_detail in self.spas_detail:
                if _item_spas_detail:
                    _items.append(_item_spas_detail.to_dict())
            _dict['spas_detail'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in allowed_channels_detail (list)
        _items = []
        if self.allowed_channels_detail:
            for _item_allowed_channels_detail in self.allowed_channels_detail:
                if _item_allowed_channels_detail:
                    _items.append(_item_allowed_channels_detail.to_dict())
            _dict['allowed_channels_detail'] = _items
        # set to None if type (nullable) is None
        # and model_fields_set contains the field
        if self.type is None and "type" in self.model_fields_set:
            _dict['type'] = None

        # set to None if name (nullable) is None
        # and model_fields_set contains the field
        if self.name is None and "name" in self.model_fields_set:
            _dict['name'] = None

        # set to None if message_title (nullable) is None
        # and model_fields_set contains the field
        if self.message_title is None and "message_title" in self.model_fields_set:
            _dict['message_title'] = None

        # set to None if email_subject (nullable) is None
        # and model_fields_set contains the field
        if self.email_subject is None and "email_subject" in self.model_fields_set:
            _dict['email_subject'] = None

        # set to None if email_from_address (nullable) is None
        # and model_fields_set contains the field
        if self.email_from_address is None and "email_from_address" in self.model_fields_set:
            _dict['email_from_address'] = None

        # set to None if email_html_template (nullable) is None
        # and model_fields_set contains the field
        if self.email_html_template is None and "email_html_template" in self.model_fields_set:
            _dict['email_html_template'] = None

        # set to None if metadata (nullable) is None
        # and model_fields_set contains the field
        if self.metadata is None and "metadata" in self.model_fields_set:
            _dict['metadata'] = None

        # set to None if proactive_prompt_message (nullable) is None
        # and model_fields_set contains the field
        if self.proactive_prompt_message is None and "proactive_prompt_message" in self.model_fields_set:
            _dict['proactive_prompt_message'] = None

        return _dict

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

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

        _obj = cls.model_validate({
            "id": obj.get("id"),
            "type": obj.get("type"),
            "name": obj.get("name"),
            "description": obj.get("description"),
            "message_title": obj.get("message_title"),
            "message_body": obj.get("message_body"),
            "short_message_body": obj.get("short_message_body"),
            "email_subject": obj.get("email_subject"),
            "email_from_address": obj.get("email_from_address"),
            "email_html_template": obj.get("email_html_template"),
            "spas_detail": [Spa.from_dict(_item) for _item in obj["spas_detail"]] if obj.get("spas_detail") is not None else None,
            "allowed_channels_detail": [ConsumerChannel.from_dict(_item) for _item in obj["allowed_channels_detail"]] if obj.get("allowed_channels_detail") is not None else None,
            "spa_ids": obj.get("spa_ids"),
            "channel_ids": obj.get("channel_ids"),
            "is_inherited": obj.get("is_inherited"),
            "is_enabled": obj.get("is_enabled"),
            "source_platform": obj.get("source_platform"),
            "can_customize": obj.get("can_customize"),
            "metadata": obj.get("metadata"),
            "available_context": obj.get("available_context"),
            "proactive_prompt_message": obj.get("proactive_prompt_message"),
            "periodic_config": obj.get("periodic_config"),
            "periodic_learner_scope": obj.get("periodic_learner_scope"),
            "periodic_report_period_days": obj.get("periodic_report_period_days"),
            "periodic_frequency": obj.get("periodic_frequency"),
            "periodic_custom_interval_days": obj.get("periodic_custom_interval_days"),
            "periodic_execution_time": obj.get("periodic_execution_time"),
            "periodic_timezone": obj.get("periodic_timezone"),
            "periodic_mentors": obj.get("periodic_mentors"),
            "policy_config": obj.get("policy_config"),
            "policy_enabled_policies": obj.get("policy_enabled_policies"),
            "policy_notify_on_assignment": obj.get("policy_notify_on_assignment"),
            "policy_notify_on_removal": obj.get("policy_notify_on_removal"),
            "human_support_config": obj.get("human_support_config"),
            "human_support_recipient_mode": obj.get("human_support_recipient_mode"),
            "human_support_custom_recipients": obj.get("human_support_custom_recipients"),
            "created_at": obj.get("created_at"),
            "updated_at": obj.get("updated_at")
        })
        return _obj


