"""
State types and reducers for automation workflows.

This module provides the base state class and reducer functions used
by LangGraph to manage state throughout automation execution.
"""

from __future__ import annotations

from typing import Annotated, Any, TypedDict

from torivers_sdk.context import CredentialProxy, ExecutionContext


def merge_dict(left: dict[str, Any], right: dict[str, Any]) -> dict[str, Any]:
    """
    Merge two dictionaries, with right values overwriting left.

    This reducer is used for accumulating output data where
    newer values should overwrite older ones.

    Args:
        left: The existing dictionary
        right: The new values to merge in

    Returns:
        Merged dictionary
    """
    return {**left, **right}


def append_list(left: list[Any], right: list[Any]) -> list[Any]:
    """
    Concatenate two lists.

    This reducer is used for accumulating lists of items
    (e.g., errors, logs) throughout execution.

    Args:
        left: The existing list
        right: Items to append

    Returns:
        Concatenated list
    """
    return left + right


def last_value(left: Any, right: Any) -> Any:
    """
    Return the last (right) value.

    This reducer is used for fields that should simply be
    overwritten with the latest value.

    Args:
        left: The previous value (ignored)
        right: The new value

    Returns:
        The new value
    """
    return right


class BaseState(TypedDict, total=False):
    """
    Base state that all automation states must extend.

    These fields are automatically populated by the runtime:
    - execution_id: Unique execution identifier
    - input_data: User-provided input
    - output_data: Accumulated output (use merge_dict reducer)
    - context: Execution context with progress reporting
    - credentials: Proxy for secure credential access

    Example:
        class MyState(BaseState):
            # Add custom fields for your automation
            processed_items: Annotated[list[str], append_list]
            current_item: Annotated[str, last_value]
            summary: Annotated[dict[str, Any], merge_dict]
    """

    # Auto-populated by runtime
    execution_id: str
    input_data: dict[str, Any]

    # Output accumulation
    output_data: Annotated[dict[str, Any], merge_dict]

    # Runtime context (injected by the execution engine)
    # Properly typed to provide full type safety and IDE autocomplete support.
    context: ExecutionContext
    credentials: CredentialProxy

    # Progress tracking
    current_step: Annotated[str, last_value]
    errors: Annotated[list[dict[str, Any]], append_list]
