from typing import Any, Awaitable, Callable, Dict, Optional, Union

from django_simple_task.task import defer

from django.apps import apps


def defer_or_sync(
    func: Union[Callable[[Any], Awaitable], Callable],
    arguments: Optional[Dict] = None,
    *,
    options: Optional[Dict] = None
):
    app_config = apps.get_app_config("django_simple_task")
    if not app_config:
        return

    if arguments is None:
        arguments = {}

    loop = getattr(app_config, "loop", None)

    if loop:
        defer(func, arguments, options=options)
    else:
        func(*arguments.get("args", []), **arguments.get("kwargs", {}))
