# coding: utf-8

"""
    Vayu API

    The Vayu API is a RESTful API that allows you to submit events for processing and storage & manage billing related entities.           The API is secured using the Bearer Authentication scheme with JWT tokens.           To obtain a JWT token, please contact Vayu at team@withvayu.com

    The version of the OpenAPI document: 1.0.0
    Contact: dev@withvayu.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, StrictFloat, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing_extensions import Annotated
from openapi.models.partner_submission_detail import PartnerSubmissionDetail
from openapi.models.usage_window import UsageWindow
from typing import Optional, Set
from typing_extensions import Self

class CloudUsageResult(BaseModel):
    """
    CloudUsageResult
    """ # noqa: E501
    status: StrictStr = Field(description="The status of the cloud usage submission result")
    error_code: Optional[StrictStr] = Field(default=None, description="Error code if the submission was rejected", alias="errorCode")
    usage_window: UsageWindow = Field(alias="usageWindow")
    error_message: Optional[StrictStr] = Field(default=None, description="Detailed error message if the submission was rejected", alias="errorMessage")
    correlation_id: StrictStr = Field(description="Unique identifier for tracing the submission through the system", alias="correlationId")
    idempotency_key: Annotated[str, Field(strict=True)] = Field(description="Key used to ensure the submission is processed exactly once", alias="idempotencyKey")
    meter_dimension: StrictStr = Field(description="The dimension of the meter being reported (e.g., API_CALLS, STORAGE_GB)", alias="meterDimension")
    accepted_quantity: Union[StrictFloat, StrictInt] = Field(description="The quantity that was accepted by the cloud provider", alias="acceptedQuantity")
    partner_submission: Dict[str, PartnerSubmissionDetail] = Field(description="Details of submissions to partner systems, keyed by request ID", alias="partnerSubmission")
    quantity_submitted: Union[StrictFloat, StrictInt] = Field(description="The total quantity that was submitted", alias="quantitySubmitted")
    timestamp_submitted: datetime = Field(description="The timestamp when the usage was submitted", alias="timestampSubmitted")
    aws_customer_identifier: StrictStr = Field(description="The AWS customer identifier associated with this usage", alias="awsCustomerIdentifier")
    additional_properties: Dict[str, Any] = {}
    __properties: ClassVar[List[str]] = ["status", "errorCode", "usageWindow", "errorMessage", "correlationId", "idempotencyKey", "meterDimension", "acceptedQuantity", "partnerSubmission", "quantitySubmitted", "timestampSubmitted", "awsCustomerIdentifier"]

    @field_validator('status')
    def status_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(['ACCEPTED', 'REJECTED']):
            raise ValueError("must be one of enum values ('ACCEPTED', 'REJECTED')")
        return value

    @field_validator('idempotency_key')
    def idempotency_key_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if not re.match(r"^vayu-\S{24}-\S{24}-\S{24}-\S{24}$", value):
            raise ValueError(r"must validate the regular expression /^vayu-\S{24}-\S{24}-\S{24}-\S{24}$/")
        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 CloudUsageResult 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 usage_window
        if self.usage_window:
            _dict['usageWindow'] = self.usage_window.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each value in partner_submission (dict)
        _field_dict = {}
        if self.partner_submission:
            for _key_partner_submission in self.partner_submission:
                if self.partner_submission[_key_partner_submission]:
                    _field_dict[_key_partner_submission] = self.partner_submission[_key_partner_submission].to_dict()
            _dict['partnerSubmission'] = _field_dict
        # 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

        return _dict

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

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

        _obj = cls.model_validate({
            "status": obj.get("status"),
            "errorCode": obj.get("errorCode"),
            "usageWindow": UsageWindow.from_dict(obj["usageWindow"]) if obj.get("usageWindow") is not None else None,
            "errorMessage": obj.get("errorMessage"),
            "correlationId": obj.get("correlationId"),
            "idempotencyKey": obj.get("idempotencyKey"),
            "meterDimension": obj.get("meterDimension"),
            "acceptedQuantity": obj.get("acceptedQuantity"),
            "partnerSubmission": dict(
                (_k, PartnerSubmissionDetail.from_dict(_v))
                for _k, _v in obj["partnerSubmission"].items()
            )
            if obj.get("partnerSubmission") is not None
            else None,
            "quantitySubmitted": obj.get("quantitySubmitted"),
            "timestampSubmitted": obj.get("timestampSubmitted"),
            "awsCustomerIdentifier": obj.get("awsCustomerIdentifier")
        })
        # 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


