#!/usr/bin/env python3
"""
UNPIVOT 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 UnpivotExecutor(AUniversalOperationExecutor):
    """UNPIVOT - Convert columns into row pairs."""
    OPERATION_NAME = "UNPIVOT"
    OPERATION_TYPE = OperationType.ADVANCED
    SUPPORTED_NODE_TYPES = []

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

    def _execute_unpivot(self, node: Any, params: dict, context: ExecutionContext) -> dict:
        items = extract_items(node)
        value_columns = params.get("value_columns", [])
        name_field = params.get("name_field", "name")
        value_field = params.get("value_field", "value")

        if not isinstance(value_columns, list) or not value_columns:
            return {"items": [], "count": 0, "error": "value_columns must be a non-empty list"}

        output = []
        for item in items:
            if isinstance(item, dict):
                base_fields = {k: v for k, v in item.items() if k not in value_columns}
            else:
                base_fields = {"value": item}
            for column in value_columns:
                new_row = dict(base_fields)
                new_row[name_field] = column
                new_row[value_field] = extract_field_value(item, column)
                output.append(new_row)

        return {
            "items": output,
            "count": len(output),
            "input_count": len(items),
            "columns_unpivoted": list(value_columns),
        }
