from typing import SupportsIndex


def ireplace(text: str, old_: str, new_: str, count_: SupportsIndex = -1) -> str:
    """Case-insensitive :py:meth:`str.replace` alternative.

    :param text: String to search through.
    :param old_: Case-insensitive substring to look for.
    :param new_: Case-sensitive substring to replace with.
    :param count_: Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

    :return: A string with all substrings matching old_ replaced with new_.
    """
    index: int = 0
    if not old_:
        return text.replace('', new_)
    if text.lower() == old_.lower() and count_.__index__() != 0:
        return new_
    while index < len(text) and count_.__index__() < 0:
        index_l = text.lower().find(old_.lower(), index)
        if index_l == -1:
            return text
        text = text[:index_l] + new_ + text[index_l + len(old_):]
        index = index_l + len(new_)
    return text