# coding: utf-8

"""
    ibl-data-manager

    API for iblai

    The version of the OpenAPI document: 4.202.1-ai-plus
    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, StrictBool, StrictFloat, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, Union
from iblai.models.course_recommendation import CourseRecommendation
from typing import Optional, Set
from typing_extensions import Self

class V2RecommendationResponse(BaseModel):
    """
    Response serializer for V2 Course Recommendations.  Returns a list of recommended courses with AI-generated reasoning. Includes metadata about the recommendation method used (RAG vs LLM).
    """ # noqa: E501
    recommendations: List[CourseRecommendation] = Field(description="List of course recommendations with reasoning")
    user_context: Optional[Dict[str, Any]] = Field(default=None, description="Summary of user context used for recommendations")
    recommendation_id: Optional[StrictStr] = Field(default=None, description="Unique ID for this recommendation set (for tracking)")
    generated_at: datetime = Field(description="When these recommendations were generated")
    platform_key: StrictStr = Field(description="Platform key for these recommendations")
    method_used: Optional[StrictStr] = Field(default=None, description="Method used to generate recommendations: 'rag_only', 'llm_only', or 'rag_plus_llm'")
    search_query_used: Optional[StrictStr] = Field(default=None, description="The actual search query used for RAG similarity search (if applicable)")
    candidates_retrieved: Optional[StrictInt] = Field(default=None, description="Number of candidates retrieved via RAG before filtering (if applicable)")
    includes_main_catalog: Optional[StrictBool] = Field(default=False, description="Whether the results include items from the 'main' tenant catalog")
    processing_time_seconds: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="Time taken to generate recommendations (in seconds)")
    success: Optional[StrictBool] = Field(default=True, description="Whether the request was successful")
    count: Optional[StrictInt] = Field(default=None, description="Total number of recommendations available")
    next: Optional[StrictStr] = Field(default=None, description="URL for the next page of results (if pagination is enabled)")
    previous: Optional[StrictStr] = Field(default=None, description="URL for the previous page of results (if pagination is enabled)")
    __properties: ClassVar[List[str]] = ["recommendations", "user_context", "recommendation_id", "generated_at", "platform_key", "method_used", "search_query_used", "candidates_retrieved", "includes_main_catalog", "processing_time_seconds", "success", "count", "next", "previous"]

    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 V2RecommendationResponse 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 each item in recommendations (list)
        _items = []
        if self.recommendations:
            for _item_recommendations in self.recommendations:
                if _item_recommendations:
                    _items.append(_item_recommendations.to_dict())
            _dict['recommendations'] = _items
        # set to None if next (nullable) is None
        # and model_fields_set contains the field
        if self.next is None and "next" in self.model_fields_set:
            _dict['next'] = None

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

        return _dict

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

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

        _obj = cls.model_validate({
            "recommendations": [CourseRecommendation.from_dict(_item) for _item in obj["recommendations"]] if obj.get("recommendations") is not None else None,
            "user_context": obj.get("user_context"),
            "recommendation_id": obj.get("recommendation_id"),
            "generated_at": obj.get("generated_at"),
            "platform_key": obj.get("platform_key"),
            "method_used": obj.get("method_used"),
            "search_query_used": obj.get("search_query_used"),
            "candidates_retrieved": obj.get("candidates_retrieved"),
            "includes_main_catalog": obj.get("includes_main_catalog") if obj.get("includes_main_catalog") is not None else False,
            "processing_time_seconds": obj.get("processing_time_seconds"),
            "success": obj.get("success") if obj.get("success") is not None else True,
            "count": obj.get("count"),
            "next": obj.get("next"),
            "previous": obj.get("previous")
        })
        return _obj


