import os

from janim import __version__
from janim.logger import log
from janim.locale import get_translator

_ = get_translator('janim.utils.deprecation')

type VersionTuple = tuple[int, int]


def _get_version_tuple() -> VersionTuple:
    dot1 = __version__.index('.')
    dot2 = __version__.index('.', dot1 + 1)
    return (
        int(__version__[:dot1]),
        int(__version__[dot1 + 1: dot2])
    )


_version_tuple = _get_version_tuple()

_DEPRECATED_MSG = _('{name!r} is deprecated and will be removed in JAnim {remove}')
_DEPRECATED_MSG_I = _('{name!r} is deprecated and will be removed in JAnim {remove}, use {instead!r} instead')


def deprecated(name, instead=None, *, remove: tuple[int, int]):
    """
    例：

    .. code-block:: python

        from janim.utils.deprecation import deprecated
        deprecated(
            'update_points_by_attrs',
            'update_by_attrs',
            remove=(4, 3)
        )
    """

    remove_formatted = f"{remove[0]}.{remove[1]}"
    if is_removed(remove):
        msg = f'{name!r} has been deprecated and removed since JAnim {remove_formatted}'
        raise RuntimeError(msg)
    else:
        if instead is None:
            msg = _DEPRECATED_MSG.format(name=name, remove=remove_formatted)
        else:
            msg = _DEPRECATED_MSG_I.format(name=name, remove=remove_formatted, instead=instead)
        log.warning(msg, stacklevel=3)


def is_removed(remove: tuple[int, int]):
    return (_version_tuple[0] > remove[0]) or (_version_tuple[0] == remove[0] and _version_tuple[1] >= remove[1])


def deprecated_classvar(value, name, instead=None, *, remove: tuple[int, int]):
    """
    例：

    .. code-block:: python

        class HighlightRect(boolean_ops.Difference):
            difference_config_d = deprecated_classvar(
                Rect.preset_shadow,
                'HighlightRect.difference_config_d',
                'Rect.preset_shadow',
                remove=(4, 3)
            )
    """

    class _DeprecatedClassVar:
        def __get__(self, instance, owner=None):
            if os.getenv('JANIM_SPHINX_BUILD') != '1':  # 在构建文档时静默
                deprecated(name, instead, remove=remove)
            return value

    return _DeprecatedClassVar()
