# 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: 0.81.1
    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 pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from mixpeek.models.httpapi_header_credentials import HTTPAPIHeaderCredentials
from typing import Optional, Set
from typing_extensions import Self

class HTTPAPIConfig(BaseModel):
    """
    REST/HTTP JSON API configuration. source_path = API URL.  Enables Mixpeek to sync items from any JSON REST API endpoint. Each item in the API response becomes a bucket object with its JSON body stored as the blob.  Authentication:     - Optional HTTP headers (API keys, Bearer tokens, etc.)  Requirements:     - API must return JSON (or JSONL) response     - Response must contain an array of items (at root or nested path)     - Each item must have a unique ID field for deduplication  Use Cases:     - Sync data from public APIs (Hacker News, GitHub, etc.)     - Ingest records from internal REST services     - Poll third-party APIs (Stripe, Shopify, etc.)     - Monitor any JSON endpoint for new items
    """ # noqa: E501
    provider_type: Optional[StrictStr] = 'http_api'
    credentials: Optional[HTTPAPIHeaderCredentials] = Field(default=None, description="Optional HTTP headers for authenticated API endpoints.")
    http_method: Optional[StrictStr] = Field(default='GET', description="HTTP method to use when calling the API.")
    request_body: Optional[Dict[str, Any]] = Field(default=None, description="Optional JSON body for POST requests.")
    items_path: Optional[StrictStr] = Field(default='', description="Dot-notation path to the array of items in the JSON response. Examples: 'hits' for {hits: [...]}, 'data.items' for {data: {items: [...]}}. Leave empty if the response is a top-level array.")
    item_id_field: StrictStr = Field(description="REQUIRED. Field name in each item used as a unique ID for deduplication. Examples: 'id', 'objectID', 'uuid'.")
    item_modified_field: Optional[StrictStr] = Field(default=None, description="Optional field name for a timestamp used for incremental sync. Supports ISO 8601 strings and Unix timestamps. Examples: 'updated_at', 'created_at', 'modified'.")
    response_content_type: Optional[StrictStr] = Field(default='json', description="Response format: 'json' (default) or 'jsonl' (newline-delimited JSON).")
    user_agent: Optional[StrictStr] = Field(default='Mixpeek HTTP API Sync/1.0', description="User-Agent header for API requests.")
    request_timeout: Optional[Annotated[int, Field(le=120, strict=True, ge=5)]] = Field(default=30, description="HTTP request timeout in seconds.")
    __properties: ClassVar[List[str]] = ["provider_type", "credentials", "http_method", "request_body", "items_path", "item_id_field", "item_modified_field", "response_content_type", "user_agent", "request_timeout"]

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

        if value not in set(['http_api']):
            raise ValueError("must be one of enum values ('http_api')")
        return value

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

        if value not in set(['GET', 'POST']):
            raise ValueError("must be one of enum values ('GET', 'POST')")
        return value

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

        if value not in set(['json', 'jsonl']):
            raise ValueError("must be one of enum values ('json', 'jsonl')")
        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 HTTPAPIConfig 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 credentials
        if self.credentials:
            _dict['credentials'] = self.credentials.to_dict()
        return _dict

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

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

        _obj = cls.model_validate({
            "provider_type": obj.get("provider_type") if obj.get("provider_type") is not None else 'http_api',
            "credentials": HTTPAPIHeaderCredentials.from_dict(obj["credentials"]) if obj.get("credentials") is not None else None,
            "http_method": obj.get("http_method") if obj.get("http_method") is not None else 'GET',
            "request_body": obj.get("request_body"),
            "items_path": obj.get("items_path") if obj.get("items_path") is not None else '',
            "item_id_field": obj.get("item_id_field"),
            "item_modified_field": obj.get("item_modified_field"),
            "response_content_type": obj.get("response_content_type") if obj.get("response_content_type") is not None else 'json',
            "user_agent": obj.get("user_agent") if obj.get("user_agent") is not None else 'Mixpeek HTTP API Sync/1.0',
            "request_timeout": obj.get("request_timeout") if obj.get("request_timeout") is not None else 30
        })
        return _obj


