# 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: 1.3.0
    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 datetime import datetime
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from mixpeek.models.error_category import ErrorCategory
from typing import Optional, Set
from typing_extensions import Self

class BatchErrorDetail(BaseModel):
    """
    Detailed error information for batch processing failures.  Provides structured error tracking at both object and batch levels. Enables better debugging, retry logic, and error analytics.  Use Cases:     - Track specific errors that occurred during processing     - Identify error patterns across multiple documents     - Provide actionable recovery suggestions     - Enable intelligent retry logic based on error type  Object-level tracking: Attached to individual document processing failures Batch-level tracking: Aggregated summaries in batch metadata
    """ # noqa: E501
    error_type: ErrorCategory = Field(description="REQUIRED. Category of error that occurred. Used for filtering, retry logic, and error analytics. DEPENDENCY: Missing packages/modules (e.g., google-genai not installed). AUTHENTICATION: Invalid credentials or expired tokens. VALIDATION: Schema mismatches or invalid input data. RUNTIME: Code exceptions or processing failures. NETWORK: Connectivity issues or timeouts. RESOURCE: Out of memory or disk space.")
    message: StrictStr = Field(description="REQUIRED. Human-readable error message. Concise description of what went wrong. Should be actionable and help users understand the issue.")
    component: Optional[StrictStr] = Field(default=None, description="OPTIONAL. Component or service where the error occurred. Helps identify which part of the system failed. Examples: service class names, module names, or feature names.")
    stage: Optional[StrictStr] = Field(default=None, description="OPTIONAL. Processing stage where the error occurred. Identifies which pipeline stage failed. Examples: pipeline stage names from collection configuration.")
    traceback: Optional[StrictStr] = Field(default=None, description="OPTIONAL. Full Python traceback for debugging. Includes stack trace for code-level troubleshooting. Should be truncated if too long (e.g., max 2000 chars).")
    timestamp: Optional[datetime] = Field(default=None, description="REQUIRED. ISO 8601 timestamp when the error occurred. Used for chronological error tracking and debugging.")
    affected_document_ids: Optional[List[StrictStr]] = Field(default=None, description="OPTIONAL. List of document IDs affected by this error. For object-level errors: contains single document ID. For batch-level aggregation: contains all affected document IDs. Used to identify scope of impact.")
    affected_count: Optional[Annotated[int, Field(strict=True, ge=1)]] = Field(default=1, description="REQUIRED. Number of documents affected by this error. For object-level: typically 1. For batch-level aggregation: total count of affected documents. Used for error impact analysis.")
    recovery_suggestion: Optional[StrictStr] = Field(default=None, description="OPTIONAL. Actionable suggestion for resolving the error. Helps users quickly fix common issues. Examples: install missing package, check credentials, update schema.")
    metadata: Optional[Dict[str, Any]] = Field(default=None, description="OPTIONAL. Additional error context and metadata. Free-form dictionary for error-specific details. Examples: retry_count, last_retry_at, error_code, http_status.")
    __properties: ClassVar[List[str]] = ["error_type", "message", "component", "stage", "traceback", "timestamp", "affected_document_ids", "affected_count", "recovery_suggestion", "metadata"]

    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 BatchErrorDetail 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,
        )
        return _dict

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

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

        _obj = cls.model_validate({
            "error_type": obj.get("error_type"),
            "message": obj.get("message"),
            "component": obj.get("component"),
            "stage": obj.get("stage"),
            "traceback": obj.get("traceback"),
            "timestamp": obj.get("timestamp"),
            "affected_document_ids": obj.get("affected_document_ids"),
            "affected_count": obj.get("affected_count") if obj.get("affected_count") is not None else 1,
            "recovery_suggestion": obj.get("recovery_suggestion"),
            "metadata": obj.get("metadata")
        })
        return _obj


