#!/usr/bin/env python3
"""
ADD_VERTEX 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 AddVertexExecutor(AUniversalOperationExecutor):
    """ADD_VERTEX - Add graph vertex with label/properties."""
    OPERATION_NAME = "ADD_VERTEX"
    OPERATION_TYPE = OperationType.GRAPH
    SUPPORTED_NODE_TYPES = []

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

    def _execute_add_vertex(self, node: Any, params: dict, context: ExecutionContext) -> dict:
        label = params.get("label", "vertex")
        properties = params.get("properties", {})
        if not isinstance(properties, dict):
            properties = {}

        vertex = {"label": label, **properties}

        items = extract_items(node)
        items.append(vertex)

        return {
            "items": items,
            "count": len(items),
            "created_vertex": vertex,
            "created": 1,
        }
