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

from datetime import datetime, date, timedelta, timezone
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


def _parse_datetime(val):
    if isinstance(val, datetime):
        return val
    if isinstance(val, date):
        return datetime.combine(val, datetime.min.time())
    if isinstance(val, (int, float)):
        return datetime.fromtimestamp(val)
    if isinstance(val, str):
        for fmt in ('%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d', '%m/%d/%Y'):
            try:
                return datetime.strptime(val, fmt)
            except ValueError:
                continue
    return None


class UnixTimestampExecutor(AUniversalOperationExecutor):
    OPERATION_NAME = "UNIX_TIMESTAMP"
    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")
        as_field = params.get("as_field", "_unix_timestamp")

        result_items = []
        for item in items:
            item_copy = item.copy() if isinstance(item, dict) else {"value": item}
            raw_value = extract_field_value(item, field) if field else item
            parsed = _parse_datetime(raw_value)
            item_copy[as_field] = parsed.timestamp() if parsed else None
            result_items.append(item_copy)

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


__all__ = ["UnixTimestampExecutor"]
