from __future__ import annotations

from typing import Any, Callable

from ...registry import get_registry


def to_langgraph_node(agent_name: str) -> Callable[..., Any]:
    reg = get_registry()
    definition = reg.agents.get(agent_name)
    if definition is None:
        raise KeyError(f"Unknown agent: {agent_name}")

    async def node(state: Any, runtime: Any) -> Any:
        ctx = getattr(runtime, "context", None)
        if definition.is_async:
            return await definition.fn(ctx, state)
        return definition.fn(ctx, state)

    return node


def to_langgraph_router(router_name: str) -> Callable[..., Any]:
    reg = get_registry()
    definition = reg.routers.get(router_name)
    if definition is None:
        raise KeyError(f"Unknown router: {router_name}")

    async def router(state: Any, runtime: Any) -> Any:
        ctx = getattr(runtime, "context", None)
        if definition.is_async:
            return await definition.fn(ctx, state)
        return definition.fn(ctx, state)

    return router
