# Copyright 2025 - Oumi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import asyncio
from collections.abc import Coroutine
from concurrent.futures import ThreadPoolExecutor
from typing import Any, TypeVar

T = TypeVar("T")


def safe_asyncio_run(main: Coroutine[Any, Any, T]) -> T:
    """Run an Awaitable in a new thread. Blocks until the thread is finished.

    This circumvents the issue of running async functions in the main thread when
    an event loop is already running (Jupyter notebooks, for example).

    Prefer using `safe_asyncio_run` over `asyncio.run` to allow upstream callers to
    ignore our dependency on asyncio.

    Args:
        main: The Coroutine to resolve.

    Returns:
        The result of the Coroutine.
    """
    with ThreadPoolExecutor(max_workers=1) as executor:
        task = executor.submit(asyncio.run, main)
        return task.result()
