# coding: utf-8

"""
    BeeL Public API

    Public invoicing API for self-employed professionals in Spain with full VeriFactu support.  **Authentication:** This API uses **API Keys** for authentication. Endpoints are designed for external integrations, automation, and programmatic access.  For browser-based authentication, use the Private API (with Session Cookies).  **Key Features:** - VeriFactu regulatory compliance - Complete invoice management (standard, corrective, simplified) - Customer management - Tax and invoice series configuration - PDF generation - Email sending - Duplicate prevention (idempotency)  **Idempotency:** Creation endpoints (POST) support the `Idempotency-Key` header to prevent duplicates in case of retries.  **Identifiers:** - All resources use UUIDs for technical identification - Invoice numbers are human-readable and searchable 

    The version of the OpenAPI document: 1.0.0
    Contact: it@beel.es
    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, StrictBool, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from beel_generated.models.counter_reset import CounterReset
from typing import Optional, Set
from typing_extensions import Self

class UpdateSeriesRequest(BaseModel):
    """
    Request to update an invoice series.  **IMPORTANT:** All fields are optional, but can only be modified when the series **has NO associated invoices**. If the series already has issued invoices, no fields can be updated to maintain numbering integrity. 
    """ # noqa: E501
    name: Optional[Annotated[str, Field(min_length=1, strict=True, max_length=100)]] = Field(default=None, description="Descriptive name of the series")
    code: Optional[Annotated[str, Field(min_length=1, strict=True, max_length=50)]] = Field(default=None, description="Alphanumeric series code (used in {CODIGO} variable). Allows uppercase letters, numbers, hyphens and underscores. ")
    description: Optional[Annotated[str, Field(strict=True, max_length=1000)]] = Field(default=None, description="Optional series description")
    format: Optional[Annotated[str, Field(min_length=1, strict=True, max_length=255)]] = Field(default=None, description="Format template with available variables (UPPERCASE ONLY): - {CODIGO}: Series code (e.g., \"FAC\") - {YYYY}: Year with 4 digits (e.g., \"2025\") - {YY}: Year with 2 digits (e.g., \"25\") - {MM}: Month with 2 digits (e.g., \"01\") - {NUM}: Sequential number without padding (e.g., \"1\") - {NUM:X}: Sequential number with padding (e.g., {NUM:4} → \"0001\")  **REQUIRED**: Must contain at least {NUM} or {NUM:X} **IMPORTANT**: Only uppercase (rejects {yy}, {mm}, {codigo}, etc.)  Valid examples: - \"{CODIGO}-{YYYY}-{NUM:4}\" → \"FAC-2025-0001\" - \"{CODIGO}/{NUM:6}\" → \"FAC/000001\" - \"{YYYY}{MM}-{NUM:3}\" → \"202501-001\" ")
    counter_reset: Optional[CounterReset] = CounterReset.ANNUAL
    initial_number: Optional[Annotated[int, Field(le=999999, strict=True, ge=1)]] = Field(default=None, description="Initial number for this series counter. Useful for adjusting numbering or resetting the counter. For example, if you want the next invoice to be 2025-0054, set initial_number=54. ")
    active: Optional[StrictBool] = Field(default=None, description="Whether the series is active.  **Restriction:** A default series cannot be deactivated (another must be set as default first). ")
    default_series: Optional[StrictBool] = Field(default=None, description="Whether this is the default series.  **Restriction:** An inactive series cannot be marked as default. ")
    __properties: ClassVar[List[str]] = ["name", "code", "description", "format", "counter_reset", "initial_number", "active", "default_series"]

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

        if not re.match(r"^[A-Z0-9\-_]{1,50}$", value):
            raise ValueError(r"must validate the regular expression /^[A-Z0-9\-_]{1,50}$/")
        return value

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

        if not re.match(r"^[A-Z0-9\-_\/{}:]*$", value):
            raise ValueError(r"must validate the regular expression /^[A-Z0-9\-_\/{}:]*$/")
        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 UpdateSeriesRequest 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,
        )
        # set to None if description (nullable) is None
        # and model_fields_set contains the field
        if self.description is None and "description" in self.model_fields_set:
            _dict['description'] = None

        return _dict

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

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

        _obj = cls.model_validate({
            "name": obj.get("name"),
            "code": obj.get("code"),
            "description": obj.get("description"),
            "format": obj.get("format"),
            "counter_reset": obj.get("counter_reset") if obj.get("counter_reset") is not None else CounterReset.ANNUAL,
            "initial_number": obj.get("initial_number"),
            "active": obj.get("active"),
            "default_series": obj.get("default_series")
        })
        return _obj


