#!/usr/bin/env python3
"""
PUSH 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 PushExecutor(AUniversalOperationExecutor):
    """PUSH - Append or insert a value into an array field."""
    OPERATION_NAME = "PUSH"
    OPERATION_TYPE = OperationType.ARRAY
    SUPPORTED_NODE_TYPES = []

    def _do_execute(self, action: QueryAction, context: ExecutionContext) -> ExecutionResult:
        params = action.params
        result_data = self._execute_op(context.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:
        field: Optional[str] = params.get("field")
        value: Any = params.get("value")
        position: Optional[int] = params.get("position")
        items = extract_items(node)

        result_items = []
        for item in items:
            item_copy = item.copy() if isinstance(item, dict) else {"value": item}
            current_value = extract_field_value(item_copy, field) if field else None
            target_array = list(current_value) if isinstance(current_value, list) else []

            if position is None:
                target_array.append(value)
            else:
                insert_at = max(0, min(int(position), len(target_array)))
                target_array.insert(insert_at, value)

            if field:
                item_copy[field] = target_array
            result_items.append(item_copy)

        return {
            "items": result_items,
            "count": len(result_items),
            "total_items": len(items),
            "field": field,
            "position": position,
        }


__all__ = ["PushExecutor"]
