# coding: utf-8

"""
Perigon API

The Perigon API provides access to comprehensive news and web content data. To use the API, simply sign up for a Perigon Business Solutions account to obtain your API key. Your available features may vary based on your plan. See the Authentication section for details on how to use your API key.

The version of the OpenAPI document: 1.0.0
Contact: data@perigon.io
Generated by OpenAPI Generator (https://openapi-generator.tech)

Do not edit the class manually.
"""  # noqa: E501


from __future__ import annotations

import json
import pprint
import re  # noqa: F401
from typing import Any, ClassVar, Dict, List, Optional, Set, Union

from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator
from typing_extensions import Annotated, Self


class SummaryBody(BaseModel):
    """
    Request body for the Search-Summarizer endpoint. Contains the user’s summary instructions, how many articles to include, which fields to use, the retrieval method, and LLM generation settings.
    """  # noqa: E501

    prompt: Optional[StrictStr] = Field(
        default="You are a helpful assistant tasked with summarizing the search results. In a casual, natural tone, craft a vivid, insightful synthesis in one fluid paragraph (no more than 125 words). Cover as many relevant points as possible, connect ideas, highlight themes, and surface anything interesting or surprising.",
        description="Instructions guiding how the summary should be written. Maximum length: 2 048 characters.",
    )
    max_article_count: Optional[Annotated[int, Field(le=100, strict=True, ge=1)]] = (
        Field(
            default=10,
            description="The maximum number of articles to factor into the summary.",
            alias="maxArticleCount",
        )
    )
    returned_article_count: Optional[
        Annotated[int, Field(le=100, strict=True, ge=1)]
    ] = Field(
        default=10,
        description="The maximum number of articles that should be returned in the response. This can be used to return fewer than maxArticleCount results.",
        alias="returnedArticleCount",
    )
    summarize_fields: Optional[List[StrictStr]] = Field(
        default=None,
        description="Which article fields to include when generating the summary. Up to three values from TITLE, CONTENT, SUMMARY.",
        alias="summarizeFields",
    )
    method: Optional[StrictStr] = Field(
        default="ARTICLES",
        description="Method for selecting articles: ARTICLES (include all matches) or CLUSTERS (one per cluster).",
    )
    model: Optional[StrictStr] = Field(
        default="gpt-4.1", description="The underlying LLM model to use for generation."
    )
    temperature: Optional[
        Union[
            Annotated[float, Field(le=2, strict=True, ge=0)],
            Annotated[int, Field(le=2, strict=True, ge=0)],
        ]
    ] = Field(
        default=0.7,
        description="Sampling temperature for the LLM (0.0 = deterministic to 2.0 = very creative).",
    )
    top_p: Optional[
        Union[
            Annotated[float, Field(le=1, strict=True, ge=0)],
            Annotated[int, Field(le=1, strict=True, ge=0)],
        ]
    ] = Field(
        default=1.0,
        description="Nucleus sampling (top-p) for the LLM (0.0 to 1.0).",
        alias="topP",
    )
    max_tokens: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(
        default=2048,
        description="Maximum number of tokens to generate in the summary.",
        alias="maxTokens",
    )
    __properties: ClassVar[List[str]] = [
        "prompt",
        "maxArticleCount",
        "returnedArticleCount",
        "summarizeFields",
        "method",
        "model",
        "temperature",
        "topP",
        "maxTokens",
    ]

    @field_validator("summarize_fields")
    def summarize_fields_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        for i in value:
            if i not in set(["TITLE", "CONTENT", "SUMMARY"]):
                raise ValueError(
                    "each list item must be one of ('TITLE', 'CONTENT', 'SUMMARY')"
                )
        return value

    @field_validator("method")
    def method_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

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

    @field_validator("model")
    def model_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(
            [
                "gpt-4o",
                "gpt-4o-mini",
                "gpt-4.1",
                "gpt-4.1-mini",
                "gpt-4.1-nano",
                "llama-3.3-70b-versatile",
                "deepseek-r1-distill-llama-70b",
            ]
        ):
            raise ValueError(
                "must be one of enum values ('gpt-4o', 'gpt-4o-mini', 'gpt-4.1', 'gpt-4.1-mini', 'gpt-4.1-nano', 'llama-3.3-70b-versatile', 'deepseek-r1-distill-llama-70b')"
            )
        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 SummaryBody 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 prompt (nullable) is None
        # and model_fields_set contains the field
        if self.prompt is None and "prompt" in self.model_fields_set:
            _dict["prompt"] = None

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

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

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

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

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

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

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

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

        return _dict

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

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

        _obj = cls.model_validate(
            {
                "prompt": (
                    obj.get("prompt")
                    if obj.get("prompt") is not None
                    else "You are a helpful assistant tasked with summarizing the search results. In a casual, natural tone, craft a vivid, insightful synthesis in one fluid paragraph (no more than 125 words). Cover as many relevant points as possible, connect ideas, highlight themes, and surface anything interesting or surprising."
                ),
                "maxArticleCount": (
                    obj.get("maxArticleCount")
                    if obj.get("maxArticleCount") is not None
                    else 10
                ),
                "returnedArticleCount": (
                    obj.get("returnedArticleCount")
                    if obj.get("returnedArticleCount") is not None
                    else 10
                ),
                "summarizeFields": obj.get("summarizeFields"),
                "method": (
                    obj.get("method") if obj.get("method") is not None else "ARTICLES"
                ),
                "model": (
                    obj.get("model") if obj.get("model") is not None else "gpt-4.1"
                ),
                "temperature": (
                    obj.get("temperature")
                    if obj.get("temperature") is not None
                    else 0.7
                ),
                "topP": obj.get("topP") if obj.get("topP") is not None else 1.0,
                "maxTokens": (
                    obj.get("maxTokens") if obj.get("maxTokens") is not None else 2048
                ),
            }
        )
        return _obj
