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

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 FirstValueExecutor(AUniversalOperationExecutor):
    """FIRST_VALUE operation executor."""

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

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

    def _execute_first_value(self, node: Any, params: dict[str, Any]) -> dict[str, Any]:
        items = extract_items(node)
        field: Optional[str] = params.get("field")
        as_field = params.get("as_field", "first_value")

        first_value = None
        for item in items:
            value = extract_field_value(item, field) if field else item
            if value is not None:
                first_value = value
                break

        return {
            as_field: first_value,
            "field": field,
            "count": len(items),
        }


__all__ = ["FirstValueExecutor"]
