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

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 ReplaceStrExecutor(AUniversalOperationExecutor):
    """
    REPLACE_STR operation executor - Replace occurrences of a substring within a field.

    params:
        field: source field name
        old: substring to find
        new: replacement string
        count: max replacements (-1 = all, default -1)
        as_field: output field name (optional, defaults to overwriting field)
    """
    OPERATION_NAME = "REPLACE_STR"
    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)
        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) -> dict:
        items = extract_items(node)
        field = params.get('field', '')
        old = params.get('old', '')
        new = params.get('new', '')
        count = params.get('count', -1)
        as_field = params.get('as_field', field)

        result_items = []
        for item in items:
            item_copy = item.copy() if isinstance(item, dict) else {'value': item}
            val = extract_field_value(item, field)
            if val is not None:
                s = str(val)
                item_copy[as_field] = s.replace(old, new) if count == -1 else s.replace(old, new, count)
            else:
                item_copy[as_field] = None
            result_items.append(item_copy)

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


__all__ = ['ReplaceStrExecutor']
