#!/usr/bin/env python3
"""
DROP_VERTEX 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 DropVertexExecutor(AUniversalOperationExecutor):
    """DROP_VERTEX - Remove vertices matching a filter."""
    OPERATION_NAME = "DROP_VERTEX"
    OPERATION_TYPE = OperationType.GRAPH
    SUPPORTED_NODE_TYPES = []

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

    def _matches(self, item: Any, filter_spec: Optional[dict]) -> bool:
        if not filter_spec:
            return True
        if not isinstance(filter_spec, dict):
            return False
        return all(extract_field_value(item, key) == value for key, value in filter_spec.items())

    def _execute_drop_vertex(self, node: Any, params: dict, context: ExecutionContext) -> dict:
        items = extract_items(node)
        filter_spec = params.get("filter")

        kept = []
        removed = []
        for item in items:
            if self._matches(item, filter_spec):
                removed.append(item)
            else:
                kept.append(item)

        return {
            "items": kept,
            "count": len(kept),
            "removed_count": len(removed),
            "removed_items": removed,
        }
