#!/usr/bin/env python3
"""
TO_DATE 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, parse_date_iso


class ToDateExecutor(AUniversalOperationExecutor):
    OPERATION_NAME = "TO_DATE"
    OPERATION_TYPE = OperationType.ADVANCED
    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:
        items = extract_items(node)
        field = params.get("field")
        date_format = params.get("format", "%Y-%m-%d")
        as_field = params.get("as_field", "_to_date")

        result_items = []
        for item in items:
            item_copy = item.copy() if isinstance(item, dict) else {"value": item}
            source_value = extract_field_value(item, field) if field else item
            item_copy[as_field] = self._to_date_iso(source_value, date_format)
            result_items.append(item_copy)

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

    def _to_date_iso(self, value: Any, date_format: str) -> Optional[str]:
        return parse_date_iso(value, preferred_format=date_format)


__all__ = ["ToDateExecutor"]
