#!/usr/bin/env python3
"""
NULLIF 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 NullifExecutor(AUniversalOperationExecutor):
    """
    NULLIF operation executor - Returns None when a field equals a compare value.

    For each item, if the field's value equals compare_value the result is None;
    otherwise the original field value is preserved.

    params:
        field:         field name to inspect
        compare_value: value to compare against
        output:        output field name for the result (default: '_nullif')

    Time Complexity: O(n) single pass
    Capability: Universal
    Operation Type: ADVANCED (conditional)
    """
    OPERATION_NAME = "NULLIF"
    OPERATION_TYPE = OperationType.ADVANCED
    SUPPORTED_NODE_TYPES = []

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

    def _execute_op(self, node: Any, params: dict, context: ExecutionContext) -> dict:
        items = extract_items(node)
        field = params.get('field', '')
        compare_value = params.get('compare_value')
        output_field = params.get('output', '_nullif')

        result_items = []
        nullified_count = 0

        for item in items:
            item_copy = item.copy() if isinstance(item, dict) else {'value': item}
            actual = extract_field_value(item, field) if field else item
            if actual == compare_value:
                item_copy[output_field] = None
                nullified_count += 1
            else:
                item_copy[output_field] = actual
            result_items.append(item_copy)

        return {
            'items': result_items,
            'count': len(result_items),
            'total_items': len(items),
            'nullified_count': nullified_count,
        }

__all__ = ['NullifExecutor']
