# coding: utf-8

"""
    BioT Settings Service

    APIs document description for Settings service

    The version of the OpenAPI document: 2.44.1
    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
from typing import Any, ClassVar, Dict, List, Optional
from biotmed_settings_sdk.models.json_nullable_list_cors_allowed_http_method_enum import JsonNullableListCorsAllowedHttpMethodEnum
from biotmed_settings_sdk.models.json_nullable_list_string import JsonNullableListString

from typing import Optional, Set
from typing_extensions import Self

# BioT Code Start: extra/custom attributes support imports
from typing import Any, Dict, ClassVar, List
from pydantic import Field, model_validator
# BioT Code End

class PartialPluginCorsConfig(BaseModel):
    """
    Partial CORS configuration for plugin updates. Only provided fields will be updated. These settings affect which browser origins are allowed to call the plugin and what request/response properties are permitted. They impact browser-enforced access (CORS), not server-to-server calls.

    Note: This model supports custom attributes. Recommended access:
      - Pass custom fields via dict unpacking: Model(..., **{"custom_field": "value"})
      - Read custom fields via model.get("custom_field") or model["custom_field"]
    """ # noqa: E501
    allow_origins: Optional[JsonNullableListString] = Field(default=None, description="List of allowed origins. Controls which browser origins can access the plugin. '*' allows any origin (useful for development; best to avoid in production). Specify explicit origins like 'https://app.example.com' (optionally with port) to restrict access. If an origin is not listed, the browser will block requests from that page even if the server responds. Omit this field to keep the current origins. Sending [] removes all origins. Providing a list replaces the existing value.", alias="allowOrigins")
    allow_methods: Optional[JsonNullableListCorsAllowedHttpMethodEnum] = Field(default=None, description="List of allowed HTTP methods for CORS. Only GET, PUT, POST, DELETE, HEAD, and PATCH are supported. Methods not included may be blocked by the browser during preflight or actual requests (even if the backend supports them). Omit this field to keep the current allowed methods. Sending [] removes all methods. Providing a list replaces the existing value.", alias="allowMethods")
    allow_headers: Optional[JsonNullableListString] = Field(default=None, description="List of request headers the browser is allowed to send. Include any custom or non-simple headers (e.g. 'authorization', 'x-request-id'), otherwise the browser will fail the CORS preflight. Omit this field to keep the current allowed headers. Sending [] removes all headers. Providing a list replaces the existing value.", alias="allowHeaders")
    expose_headers: Optional[JsonNullableListString] = Field(default=None, description="List of response headers that should be readable by browser clients (via fetch/XHR). Without listing here, only CORS-safelisted headers are visible to client code. This does not gate access; it only controls header visibility. Omit this field to keep the current expose headers. Sending [] removes all headers. Providing a list replaces the existing value.", alias="exposeHeaders")
    # BioT Code Start: Store custom attributes in a dedicated dict (safe default)
    additional_properties: Dict[str, Any] = Field(default_factory=dict)
    # BioT Code End
    __properties: ClassVar[List[str]] = ["allowOrigins", "allowMethods", "allowHeaders", "exposeHeaders"]

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
        # BioT Code Start: Allow extra fields for custom attributes
        extra='allow',
        # BioT Code End
    )

    # BioT Code Start: Sync Pydantic v2 extras into additional_properties
    @model_validator(mode='after')
    def _sync_additional_properties(self):
        """
        Sync unknown fields from Pydantic v2 `model_extra` into additional_properties.

        - When `extra='allow'`, unknown fields are stored in `model_extra`.
        - We copy them into additional_properties for OpenAPI Generator compatibility.
        """
        if self.model_extra:
            self.additional_properties.update(self.model_extra)
        return self
    # BioT Code End

    # BioT Code Start: Make dot-access to custom attributes type-check as Any (pyright-friendly)
    def __getattr__(self, item: str) -> Any:
        """
        Fallback for dynamic/custom attributes.

        This makes `model.some_custom_attr` resolve to `Any` in static type checkers
        instead of raising `reportUnknownMemberType`.
        """
        if item in self.additional_properties:
            return self.additional_properties[item]
        # also check model_extra directly (in case sync didn't run yet)
        if self.model_extra and item in self.model_extra:
            return self.model_extra[item]
        raise AttributeError(f"'{self.__class__.__name__}' has no field or custom property '{item}'")
    # BioT Code End

    # BioT Code Start: Dict-style access for custom attributes (and fields)
    def __getitem__(self, key: str) -> Any:
        """
        Support dict-style access:
          - defined fields by python name (e.g. 'name')
          - defined fields by alias (e.g. '_name') via to_dict fallback
          - custom attributes stored in additional_properties
        """
        if key in self.additional_properties:
            return self.additional_properties[key]
        if self.model_extra and key in self.model_extra:
            return self.model_extra[key]

        # Try direct attribute (python field name)
        if hasattr(self, key):
            try:
                return getattr(self, key)
            except AttributeError:
                pass

        # Try alias / serialized keys through to_dict()
        d = self.to_dict()
        if key in d:
            return d[key]

        raise KeyError(f"'{self.__class__.__name__}' has no field or custom property '{key}'")

    def get(self, key: str, default: Any = None) -> Any:
        """dict.get() style safe access."""
        try:
            return self[key]
        except KeyError:
            return default
    # BioT Code End

    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())

    # BioT Code Start: Override model_dump_json to flatten custom attributes to top level
    def model_dump_json(self, *, indent: Optional[int] = None, by_alias: bool = True, **kwargs: Any) -> str:
        """Return JSON representation with custom attributes flattened to top level."""
        json_kwargs = {k: v for k, v in kwargs.items()
                      if k not in ['by_alias', 'exclude', 'exclude_none', 'exclude_unset',
                                   'exclude_defaults', 'include', 'mode', 'round_trip',
                                   'warnings', 'serialize_as_any']}
        return json.dumps(self.to_dict(), indent=indent, default=str, **json_kwargs)
    # BioT Code End

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of PartialPluginCorsConfig 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.
        * Fields in `self.additional_properties` are added to the output dict.
        """
        excluded_fields: Set[str] = set([
            "additional_properties",
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of allow_origins
        if self.allow_origins:
            _dict['allowOrigins'] = self.allow_origins.to_dict()
        # override the default output from pydantic by calling `to_dict()` of allow_methods
        if self.allow_methods:
            _dict['allowMethods'] = self.allow_methods.to_dict()
        # override the default output from pydantic by calling `to_dict()` of allow_headers
        if self.allow_headers:
            _dict['allowHeaders'] = self.allow_headers.to_dict()
        # override the default output from pydantic by calling `to_dict()` of expose_headers
        if self.expose_headers:
            _dict['exposeHeaders'] = self.expose_headers.to_dict()
        # BioT Code Start: puts key-value pairs in additional_properties in the top level
        if self.additional_properties is not None:
            for _key, _value in self.additional_properties.items():
                _dict[_key] = _value
        # BioT Code End
        return _dict

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

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

        _obj = cls.model_validate({
            "allowOrigins": JsonNullableListString.from_dict(obj["allowOrigins"]) if obj.get("allowOrigins") is not None else None,
            "allowMethods": JsonNullableListCorsAllowedHttpMethodEnum.from_dict(obj["allowMethods"]) if obj.get("allowMethods") is not None else None,
            "allowHeaders": JsonNullableListString.from_dict(obj["allowHeaders"]) if obj.get("allowHeaders") is not None else None,
            "exposeHeaders": JsonNullableListString.from_dict(obj["exposeHeaders"]) if obj.get("exposeHeaders") is not None else None
        })
        # store additional fields in additional_properties
        for _key in obj.keys():
            if _key not in cls.__properties:
                _obj.additional_properties[_key] = obj.get(_key)

        return _obj


