# 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, Union
from typing_extensions import Annotated
from mixpeek.models.duration_stats import DurationStats
from mixpeek.models.predictor_lift import PredictorLift
from typing import Optional, Set
from typing_extensions import Self

class StepTransitionResponse(BaseModel):
    """
    API response model for step transition analytics.  Contains comprehensive statistics about the A→B transition including conversion metrics, duration analysis, and predictor insights.  Example Response:     ```json     {         \"from_step\": \"inquiry\",         \"to_step\": \"closed_won\",         \"count\": 1000,         \"converted\": 350,         \"conversion_rate\": 0.35,         \"durations_sec\": {             \"mean\": 432000.0,             \"median\": 345600.0,             \"p50\": 345600.0,             \"p90\": 691200.0,             \"p95\": 864000.0,             \"std_dev\": 172800.0,             \"min\": 86400.0,             \"max\": 1209600.0         },         \"top_predictors\": [             {                 \"field\": \"Sender Domain\",                 \"value\": \"enterprise.com\",                 \"count\": 150,                 \"conversion_rate\": 0.75,                 \"lift\": 2.14             }         ],         \"metadata\": {             \"collection_id\": \"col_emails\",             \"taxonomy_id\": \"tax_sales_stages\",             \"total_events_analyzed\": 5432         }     }     ```
    """ # noqa: E501
    from_step: StrictStr = Field(description="Starting step")
    to_step: StrictStr = Field(description="Ending step")
    count: Annotated[int, Field(strict=True, ge=0)] = Field(description="Total number of sequences starting at from_step")
    converted: Annotated[int, Field(strict=True, ge=0)] = Field(description="Number of sequences that reached to_step")
    conversion_rate: Union[Annotated[float, Field(le=1.0, strict=True, ge=0.0)], Annotated[int, Field(le=1, strict=True, ge=0)]] = Field(description="Percentage that converted (converted / count)")
    durations_sec: Optional[DurationStats] = Field(default=None, description="Duration statistics (None if no conversions)")
    top_predictors: Optional[Annotated[List[PredictorLift], Field(max_length=50)]] = Field(default=None, description="Covariates with highest lift (sorted by absolute lift)")
    metadata: Optional[Dict[str, Any]] = Field(default=None, description="Additional metadata (collection_id, event counts, etc.)")
    __properties: ClassVar[List[str]] = ["from_step", "to_step", "count", "converted", "conversion_rate", "durations_sec", "top_predictors", "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 StepTransitionResponse 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 durations_sec
        if self.durations_sec:
            _dict['durations_sec'] = self.durations_sec.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in top_predictors (list)
        _items = []
        if self.top_predictors:
            for _item_top_predictors in self.top_predictors:
                if _item_top_predictors:
                    _items.append(_item_top_predictors.to_dict())
            _dict['top_predictors'] = _items
        return _dict

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

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

        _obj = cls.model_validate({
            "from_step": obj.get("from_step"),
            "to_step": obj.get("to_step"),
            "count": obj.get("count"),
            "converted": obj.get("converted"),
            "conversion_rate": obj.get("conversion_rate"),
            "durations_sec": DurationStats.from_dict(obj["durations_sec"]) if obj.get("durations_sec") is not None else None,
            "top_predictors": [PredictorLift.from_dict(_item) for _item in obj["top_predictors"]] if obj.get("top_predictors") is not None else None,
            "metadata": obj.get("metadata")
        })
        return _obj


