# 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 pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from mixpeek.models.covariate_config import CovariateConfig
from mixpeek.models.step_key_source import StepKeySource
from typing import Optional, Set
from typing_extensions import Self

class StepAnalyticsConfigInput(BaseModel):
    """
    Configuration for step-by-step transition analytics on taxonomy assignments.  Enables analysis of how documents progress through taxonomy labels as a temporal sequence, answering questions like: - How long from \"inquiry\" to \"closed_won\"? - What % of \"inquiry\" emails reach \"proposal\"? - Which sender domains correlate with faster progression?  Use Cases:     1. Email Thread Analysis:        - Track progression: inquiry → followup → proposal → closed_won        - Identify which subject lines correlate with faster closure      2. Content Workflow Tracking:        - Monitor: draft → review → approved → published        - Find bottlenecks and optimization opportunities      3. Safety Compliance Monitoring:        - Trace: violation_detected → investigated → resolved        - Track resolution times and success rates  Attributes:     timestamp_field: Document field containing event timestamp     sequence_id_field: Field that groups related documents into sequences     step_key_source: How to extract the step identifier (label/node_id/custom field)     step_key_field_path: Required if step_key_source='field_path'     covariates: List of predictor variables to analyze for conversion lift     max_sequence_duration_days: Filter out sequences longer than this (data quality)  Example:     ```python     # Email thread analysis configuration     StepAnalyticsConfig(         timestamp_field=\"Date\",  # Email timestamp         sequence_id_field=\"Thread-Index\",  # Groups emails in same thread         step_key_source=\"assignment_label\",  # Use taxonomy label as step         covariates=[             CovariateConfig(                 field_path=\"sender_domain\",                 covariate_type=\"categorical\",                 name=\"Sender Domain\"             ),             CovariateConfig(                 field_path=\"word_count\",                 covariate_type=\"numeric\",                 name=\"Email Length\"             )         ],         max_sequence_duration_days=90  # Ignore threads >90 days     )     ```
    """ # noqa: E501
    timestamp_field: StrictStr = Field(description="Document field containing event timestamp (e.g., 'Date', 'created_at', 'metadata.timestamp')")
    sequence_id_field: StrictStr = Field(description="Document field that groups related items into a sequence (e.g., 'Thread-Index', 'session_id', 'user_id')")
    step_key_source: Optional[StepKeySource] = Field(default=None, description="How to determine the 'step' for each document (label, node_id, or custom field)")
    step_key_field_path: Optional[StrictStr] = Field(default=None, description="Required if step_key_source='field_path'. Dot-notation path to step value in document.")
    covariates: Optional[Annotated[List[CovariateConfig], Field(max_length=20)]] = Field(default=None, description="Predictor fields to analyze for conversion lift (categorical, numeric, embedding, cluster)")
    max_sequence_duration_days: Optional[Annotated[int, Field(le=365, strict=True, ge=1)]] = Field(default=None, description="Maximum allowed duration for a sequence. Sequences beyond this are flagged as data quality issues.")
    __properties: ClassVar[List[str]] = ["timestamp_field", "sequence_id_field", "step_key_source", "step_key_field_path", "covariates", "max_sequence_duration_days"]

    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 StepAnalyticsConfigInput 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 covariates (list)
        _items = []
        if self.covariates:
            for _item_covariates in self.covariates:
                if _item_covariates:
                    _items.append(_item_covariates.to_dict())
            _dict['covariates'] = _items
        return _dict

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

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

        _obj = cls.model_validate({
            "timestamp_field": obj.get("timestamp_field"),
            "sequence_id_field": obj.get("sequence_id_field"),
            "step_key_source": obj.get("step_key_source"),
            "step_key_field_path": obj.get("step_key_field_path"),
            "covariates": [CovariateConfig.from_dict(_item) for _item in obj["covariates"]] if obj.get("covariates") is not None else None,
            "max_sequence_duration_days": obj.get("max_sequence_duration_days")
        })
        return _obj


