from __future__ import annotations

import datetime
from collections.abc import Mapping
from typing import Any, TypeVar, cast

from attrs import define as _attrs_define
from attrs import field as _attrs_field
from dateutil.parser import isoparse

from ..types import UNSET, Unset

T = TypeVar("T", bound="ValidatorScoreSummary")


@_attrs_define
class ValidatorScoreSummary:
    """Aggregated scoring and performance stats for a single validator.

    Attributes:
        validator_hotkey (str): Validator hotkey
        total_runs (int): Total completed runs
        avg_score (float): Mean score across runs
        median_score (float): Median score
        stddev_score (float): Standard deviation of scores
        min_score (float): Minimum score
        max_score (float): Maximum score
        deviation_from_global (float): Percentage deviation from the global average (negative = below)
        is_outlier (bool): True if deviation exceeds 1.5 standard deviations from global mean
        avg_execution_seconds (float | Unset): Mean seconds from claimed to completed Default: 0.0.
        median_execution_seconds (float | Unset): Median execution time in seconds Default: 0.0.
        min_execution_seconds (float | Unset): Fastest run Default: 0.0.
        max_execution_seconds (float | Unset): Slowest run Default: 0.0.
        execution_deviation_pct (float | Unset): % deviation from global avg execution time Default: 0.0.
        is_slow_outlier (bool | Unset): Significantly slower than peers Default: False.
        success_count (int | Unset): SUCCESS runs Default: 0.
        failed_count (int | Unset): FAILED runs Default: 0.
        timed_out_count (int | Unset): TIMED_OUT runs Default: 0.
        success_rate (float | Unset): success / total Default: 0.0.
        last_failure_reason (None | str | Unset): Most recent failure reason
        last_failure_at (datetime.datetime | None | Unset): When last failure occurred
    """

    validator_hotkey: str
    total_runs: int
    avg_score: float
    median_score: float
    stddev_score: float
    min_score: float
    max_score: float
    deviation_from_global: float
    is_outlier: bool
    avg_execution_seconds: float | Unset = 0.0
    median_execution_seconds: float | Unset = 0.0
    min_execution_seconds: float | Unset = 0.0
    max_execution_seconds: float | Unset = 0.0
    execution_deviation_pct: float | Unset = 0.0
    is_slow_outlier: bool | Unset = False
    success_count: int | Unset = 0
    failed_count: int | Unset = 0
    timed_out_count: int | Unset = 0
    success_rate: float | Unset = 0.0
    last_failure_reason: None | str | Unset = UNSET
    last_failure_at: datetime.datetime | None | Unset = UNSET
    additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)

    def to_dict(self) -> dict[str, Any]:
        validator_hotkey = self.validator_hotkey

        total_runs = self.total_runs

        avg_score = self.avg_score

        median_score = self.median_score

        stddev_score = self.stddev_score

        min_score = self.min_score

        max_score = self.max_score

        deviation_from_global = self.deviation_from_global

        is_outlier = self.is_outlier

        avg_execution_seconds = self.avg_execution_seconds

        median_execution_seconds = self.median_execution_seconds

        min_execution_seconds = self.min_execution_seconds

        max_execution_seconds = self.max_execution_seconds

        execution_deviation_pct = self.execution_deviation_pct

        is_slow_outlier = self.is_slow_outlier

        success_count = self.success_count

        failed_count = self.failed_count

        timed_out_count = self.timed_out_count

        success_rate = self.success_rate

        last_failure_reason: None | str | Unset
        if isinstance(self.last_failure_reason, Unset):
            last_failure_reason = UNSET
        else:
            last_failure_reason = self.last_failure_reason

        last_failure_at: None | str | Unset
        if isinstance(self.last_failure_at, Unset):
            last_failure_at = UNSET
        elif isinstance(self.last_failure_at, datetime.datetime):
            last_failure_at = self.last_failure_at.isoformat()
        else:
            last_failure_at = self.last_failure_at

        field_dict: dict[str, Any] = {}
        field_dict.update(self.additional_properties)
        field_dict.update(
            {
                "validator_hotkey": validator_hotkey,
                "total_runs": total_runs,
                "avg_score": avg_score,
                "median_score": median_score,
                "stddev_score": stddev_score,
                "min_score": min_score,
                "max_score": max_score,
                "deviation_from_global": deviation_from_global,
                "is_outlier": is_outlier,
            }
        )
        if avg_execution_seconds is not UNSET:
            field_dict["avg_execution_seconds"] = avg_execution_seconds
        if median_execution_seconds is not UNSET:
            field_dict["median_execution_seconds"] = median_execution_seconds
        if min_execution_seconds is not UNSET:
            field_dict["min_execution_seconds"] = min_execution_seconds
        if max_execution_seconds is not UNSET:
            field_dict["max_execution_seconds"] = max_execution_seconds
        if execution_deviation_pct is not UNSET:
            field_dict["execution_deviation_pct"] = execution_deviation_pct
        if is_slow_outlier is not UNSET:
            field_dict["is_slow_outlier"] = is_slow_outlier
        if success_count is not UNSET:
            field_dict["success_count"] = success_count
        if failed_count is not UNSET:
            field_dict["failed_count"] = failed_count
        if timed_out_count is not UNSET:
            field_dict["timed_out_count"] = timed_out_count
        if success_rate is not UNSET:
            field_dict["success_rate"] = success_rate
        if last_failure_reason is not UNSET:
            field_dict["last_failure_reason"] = last_failure_reason
        if last_failure_at is not UNSET:
            field_dict["last_failure_at"] = last_failure_at

        return field_dict

    @classmethod
    def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
        d = dict(src_dict)
        validator_hotkey = d.pop("validator_hotkey")

        total_runs = d.pop("total_runs")

        avg_score = d.pop("avg_score")

        median_score = d.pop("median_score")

        stddev_score = d.pop("stddev_score")

        min_score = d.pop("min_score")

        max_score = d.pop("max_score")

        deviation_from_global = d.pop("deviation_from_global")

        is_outlier = d.pop("is_outlier")

        avg_execution_seconds = d.pop("avg_execution_seconds", UNSET)

        median_execution_seconds = d.pop("median_execution_seconds", UNSET)

        min_execution_seconds = d.pop("min_execution_seconds", UNSET)

        max_execution_seconds = d.pop("max_execution_seconds", UNSET)

        execution_deviation_pct = d.pop("execution_deviation_pct", UNSET)

        is_slow_outlier = d.pop("is_slow_outlier", UNSET)

        success_count = d.pop("success_count", UNSET)

        failed_count = d.pop("failed_count", UNSET)

        timed_out_count = d.pop("timed_out_count", UNSET)

        success_rate = d.pop("success_rate", UNSET)

        def _parse_last_failure_reason(data: object) -> None | str | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            return cast(None | str | Unset, data)

        last_failure_reason = _parse_last_failure_reason(d.pop("last_failure_reason", UNSET))

        def _parse_last_failure_at(data: object) -> datetime.datetime | None | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            try:
                if not isinstance(data, str):
                    raise TypeError()
                last_failure_at_type_0 = isoparse(data)

                return last_failure_at_type_0
            except (TypeError, ValueError, AttributeError, KeyError):
                pass
            return cast(datetime.datetime | None | Unset, data)

        last_failure_at = _parse_last_failure_at(d.pop("last_failure_at", UNSET))

        validator_score_summary = cls(
            validator_hotkey=validator_hotkey,
            total_runs=total_runs,
            avg_score=avg_score,
            median_score=median_score,
            stddev_score=stddev_score,
            min_score=min_score,
            max_score=max_score,
            deviation_from_global=deviation_from_global,
            is_outlier=is_outlier,
            avg_execution_seconds=avg_execution_seconds,
            median_execution_seconds=median_execution_seconds,
            min_execution_seconds=min_execution_seconds,
            max_execution_seconds=max_execution_seconds,
            execution_deviation_pct=execution_deviation_pct,
            is_slow_outlier=is_slow_outlier,
            success_count=success_count,
            failed_count=failed_count,
            timed_out_count=timed_out_count,
            success_rate=success_rate,
            last_failure_reason=last_failure_reason,
            last_failure_at=last_failure_at,
        )

        validator_score_summary.additional_properties = d
        return validator_score_summary

    @property
    def additional_keys(self) -> list[str]:
        return list(self.additional_properties.keys())

    def __getitem__(self, key: str) -> Any:
        return self.additional_properties[key]

    def __setitem__(self, key: str, value: Any) -> None:
        self.additional_properties[key] = value

    def __delitem__(self, key: str) -> None:
        del self.additional_properties[key]

    def __contains__(self, key: str) -> bool:
        return key in self.additional_properties
