from collections.abc import Awaitable, Callable
import inspect
import asyncio

from app.modules.agent.engine.graphs.progress_registry import progress_registry
from app.modules.agent.engine.graphs.state import AgentGraphState

ProgressCallback = Callable[[str, str, str, dict | None], Awaitable[None] | None]


async def emit_progress(
    state: AgentGraphState,
    *,
    stage: str,
    message: str,
    kind: str = "task_progress",
    meta: dict | None = None,
) -> None:
    callback = progress_registry.get(state.get("progress_key"))
    if callback is None:
        return
    result = callback(stage, message, kind, meta or {})
    if inspect.isawaitable(result):
        await result


def emit_progress_sync(
    state: AgentGraphState,
    *,
    stage: str,
    message: str,
    kind: str = "task_progress",
    meta: dict | None = None,
) -> None:
    callback = progress_registry.get(state.get("progress_key"))
    if callback is None:
        return
    result = callback(stage, message, kind, meta or {})
    if inspect.isawaitable(result):
        try:
            loop = asyncio.get_running_loop()
            loop.create_task(result)
        except RuntimeError:
            pass
