#!/usr/bin/env python3
"""
IS_NULL 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 IsNullExecutor(AUniversalOperationExecutor):
    """
    IS_NULL operation executor - Null check filtering.
    Returns items where a field is None (SQL IS NULL) or not None (IS NOT NULL).
    Supports negation for IS NOT NULL semantics.
    O(n) scan over items.
    Capability: Universal
    Operation Type: FILTERING
    """
    OPERATION_NAME = "IS_NULL"
    OPERATION_TYPE = OperationType.FILTERING
    SUPPORTED_NODE_TYPES = []  # Universal

    def _do_execute(self, action: QueryAction, context: ExecutionContext) -> ExecutionResult:
        """Execute IS_NULL operation."""
        params = action.params
        field = params.get('field')
        negate = params.get('negate', False)
        path = params.get('path', None)

        if not field:
            return ExecutionResult(
                success=False,
                data=None,
                error=f"IS_NULL requires 'field'. Got: {action.params}",
                action_type=self.OPERATION_NAME
            )

        node = context.node
        result_data = self._execute_is_null(node, field, negate, path, context)

        return ExecutionResult(
            success=True,
            data=result_data,
            action_type=self.OPERATION_NAME,
            metadata={'matched_count': len(result_data.get('items', []))}
        )

    def _execute_is_null(self, node: Any, field: str, negate: bool,
                         path: Optional[str], context: ExecutionContext) -> dict:
        """
        Execute IS_NULL / IS NOT NULL check - O(n) single-pass scan.
        A field is considered null if:
        - It does not exist on the item, OR
        - Its value is None
        When negate=True, returns items where the field exists AND is not None.
        """
        if path:
            try:
                data = node.get(path, default=None)
            except Exception:
                data = None
        else:
            data = node

        items = extract_items(data)
        matched_items = []

        for item in items:
            value = extract_field_value(item, field)
            is_null = value is None
            if (is_null and not negate) or (not is_null and negate):
                matched_items.append(item)

        op_label = 'IS NOT NULL' if negate else 'IS NULL'
        return {
            'items': matched_items,
            'count': len(matched_items),
            'total_items': len(items),
            'field': field,
            'operation': op_label
        }


__all__ = ['IsNullExecutor']
