"""Nested saga helpers."""

from __future__ import annotations

from typing import Any, Awaitable, Callable, TypeVar

from restate_saga.types import SagaContext

T = TypeVar("T")


async def run_nested_saga(
    saga: SagaContext,
    handler: Callable[[SagaContext], Awaitable[T]],
) -> T:
    """Run a nested saga that shares the parent's compensation context.

    All steps executed by *handler* register their compensations in the
    parent's compensation stack.  If the parent saga fails later, the
    nested compensations run together with the parent's in reverse order.
    """
    return await handler(saga)


def create_saga_module(
    handler: Callable[[SagaContext, Any], Awaitable[Any]],
) -> Callable[[SagaContext, Any], Awaitable[Any]]:
    """Create a reusable saga module that can be embedded in other workflows.

    Unlike ``create_saga_workflow``, this is just a function — not a Restate
    service.  It always shares the parent's compensation context.
    """
    return handler
