#!/usr/bin/env python3
"""
VARIANCE Executor
Company: eXonware.com
Author: eXonware Backend Team
Email: connect@exonware.com
Version: 0.9.0.6
"""

import math as _math  # for stddev/variance
from typing import Any, Optional
from ..base import AUniversalOperationExecutor
from ....contracts import QueryAction, ExecutionContext, ExecutionResult
from ....defs import OperationType
from ..utils import extract_items, extract_field_value


class VarianceExecutor(AUniversalOperationExecutor):
    """VARIANCE operation executor."""

    OPERATION_NAME = "VARIANCE"
    OPERATION_TYPE = OperationType.AGGREGATION
    SUPPORTED_NODE_TYPES = []

    def _do_execute(self, action: QueryAction, context: ExecutionContext) -> ExecutionResult:
        params = action.params or {}
        data = self._execute_variance(context.node, params)
        return ExecutionResult(
            success=True,
            data=data,
            action_type=self.OPERATION_NAME,
            metadata={"operation": self.OPERATION_NAME},
        )

    def _execute_variance(self, node: Any, params: dict[str, Any]) -> dict[str, Any]:
        _ = _math  # keep import parity with requested pattern
        items = extract_items(node)
        field: Optional[str] = params.get("field")
        sample = bool(params.get("sample", False))
        as_field = params.get("as_field", "variance")
        values = self._extract_numeric_values(items, field)

        variance = self._compute_variance(values, sample)
        return {
            as_field: variance,
            "count": len(values),
            "field": field,
            "sample": sample,
        }

    def _extract_numeric_values(self, items: list[Any], field: Optional[str]) -> list[float]:
        values: list[float] = []
        for item in items:
            raw = extract_field_value(item, field) if field else item
            numeric = self._to_number(raw)
            if numeric is not None:
                values.append(numeric)
        return values

    def _compute_variance(self, values: list[float], sample: bool) -> Optional[float]:
        n = len(values)
        if n == 0:
            return None
        if sample and n < 2:
            return None
        mean = sum(values) / n
        squared_diff_sum = sum((value - mean) ** 2 for value in values)
        denominator = (n - 1) if sample else n
        return squared_diff_sum / denominator

    def _to_number(self, value: Any) -> Optional[float]:
        if isinstance(value, bool):
            return None
        if isinstance(value, (int, float)):
            return float(value)
        if isinstance(value, str):
            try:
                return float(value)
            except ValueError:
                return None
        return None


__all__ = ["VarianceExecutor"]
