# Copyright (c) 2025, Palo Alto Networks
#
# Licensed under the Polyform Internal Use License 1.0.0 (the "License");
# you may not use this file except in compliance with the License.
#
# You may obtain a copy of the License at:
#
# https://polyformproject.org/licenses/internal-use/1.0.0
# (or)
# https://github.com/polyformproject/polyform-licenses/blob/76a278c4/PolyForm-Internal-Use-1.0.0.md
#
# As far as the law allows, the software comes as is, without any warranty
# or condition, and the licensor will not be liable to you for any damages
# arising out of these terms or the use or nature of the software, under
# any kind of legal claim.

"""
AISec API service

OpenAPI Specification for the AI Runtime Security API service

The version of the OpenAPI document: 0.0.0
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, model_validator
from typing import Any, ClassVar, Dict, List
from aisecurity.generated_openapi_client.models.ai_profile import AiProfile
from aisecurity.generated_openapi_client.models.metadata import Metadata
from aisecurity.generated_openapi_client.models.scan_request_contents_inner import ScanRequestContentsInner
from aisecurity.constants.base import MAX_TRANSACTION_ID_STR_LENGTH, MAX_SESSION_ID_STR_LENGTH
from aisecurity.exceptions import AISecSDKException, ErrorType
from typing import Optional, Set
from typing_extensions import Self


class ScanRequest(BaseModel):
    """
    ScanRequest
    """  # noqa: E501

    tr_id: Optional[StrictStr] = Field(
        default=None, description="Unique identifier for the transaction correlating prompt and response"
    )
    session_id: Optional[StrictStr] = Field(default=None, description="Unique identifier for tracking Sessions")
    ai_profile: AiProfile
    metadata: Optional[Metadata] = None
    contents: List[ScanRequestContentsInner] = Field(
        description="List of prompt or response or prompt/response pairs. The last element is the one that needs to be scanned, and the previous elements are the context for the scan."
    )
    __properties: ClassVar[List[str]] = ["tr_id", "session_id", "ai_profile", "metadata", "contents"]

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
    )

    @field_validator("session_id")
    @classmethod
    def validate_id_length(cls, v: Optional[str], info) -> Optional[str]:
        """Only validate session_id length"""
        if v is not None:
            cleaned_value = str(v).strip()
            if len(cleaned_value) > MAX_SESSION_ID_STR_LENGTH:
                raise AISecSDKException(
                    f"sessionID exceeds maximum length of {MAX_SESSION_ID_STR_LENGTH} characters",
                    ErrorType.USER_REQUEST_PAYLOAD_ERROR,
                )
            return cleaned_value
        return v

    @model_validator(mode="after")
    def validate_id_priority(self) -> "ScanRequest":
        """Handle priority logic: session_id > tr_id, but only validate tr_id if session_id is empty"""
        session_id = self.session_id
        tr_id = self.tr_id

        # Check if session_id has actual content
        has_valid_session_id = session_id and str(session_id).strip()

        # If session_id is empty/None but tr_id is provided, validate tr_id length
        if not has_valid_session_id and tr_id:
            cleaned_tr_id = str(tr_id).strip()
            if len(cleaned_tr_id) > MAX_TRANSACTION_ID_STR_LENGTH:
                raise AISecSDKException(
                    f"transactionID exceeds maximum length of {MAX_TRANSACTION_ID_STR_LENGTH} characters",
                    ErrorType.USER_REQUEST_PAYLOAD_ERROR,
                )

        return self

    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 ScanRequest 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 ai_profile
        if self.ai_profile:
            _dict["ai_profile"] = self.ai_profile.to_dict()
        # override the default output from pydantic by calling `to_dict()` of metadata
        if self.metadata:
            _dict["metadata"] = self.metadata.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in contents (list)
        _items = []
        if self.contents:
            for _item_contents in self.contents:
                if _item_contents:
                    _items.append(_item_contents.to_dict())
            _dict["contents"] = _items
        return _dict

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

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

        _obj = cls.model_validate({
            "tr_id": obj.get("tr_id"),
            "session_id": obj.get("session_id"),
            "ai_profile": AiProfile.from_dict(obj["ai_profile"]) if obj.get("ai_profile") is not None else None,
            "metadata": Metadata.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None,
            "contents": [ScanRequestContentsInner.from_dict(_item) for _item in obj["contents"]]
            if obj.get("contents") is not None
            else None,
        })
        return _obj
