# -*- coding: utf-8 -*-

import asyncio
import inspect
from typing import Tuple, Union
from ddans.common.type import T, Callback


def import_safe(name):
    try:
        # 使用 `importlib` 动态导入模块
        import importlib
        module = importlib.import_module(name)
        return module
    except ImportError:
        return None


def func_safe(func: Callback, *args, **kwargs):
    """_summary_

    Args:
        func (Callable[..., Any]): 方法函数

    Returns:
        Any: 返回值
    """
    result = None
    try:
        result = func(*args, **kwargs)
    except Exception:
        result = None
    finally:
        return result


def func_to(func: Callback[T], *args, **kwargs) ->\
        Union[Tuple[Exception, None], Tuple[T, None]]:
    """_summary_

    Args:
        func (Callable[..., T]): 方法函数

    Returns:
        err, result: 异常，结果
    """
    try:
        result = func(*args, **kwargs)
        return None, result
    except Exception as e:
        return e, None


def func_template(func: Callback[T], args=None, kwargs=None):
    func = func
    args = args if args is not None else []
    kwargs = kwargs if kwargs is not None else {}
    return (func, args, kwargs)


def prints(content: str, chunk_size=1000):
    """分段打印
    Args:
        content (str): 内容
        chunk_size (int, optional): 分段大小. 默认1000.
    """
    length = len(content)
    if length <= chunk_size:
        print(content)
        return

    for i in range(0, length, chunk_size):
        print(content[i:i + chunk_size], end="")
    print()


def run_async(func, *args, **kwargs):
    """安全执行同步或异步函数，支持已有事件循环"""
    if not inspect.iscoroutinefunction(func):
        return func(*args, **kwargs)
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        return asyncio.run(func(*args, **kwargs))
    else:
        return loop.run_until_complete(func(*args, **kwargs))
