from functools import wraps

from im360.internals.strategy import Strategy
from im360.model.firewall import IPList


def add_strategy(f):
    @wraps(f)
    async def wrapper(*args, **kwargs):
        result = await f(*args, **kwargs)
        assert isinstance(result, dict), (
            "Result should be a dictionary %s" % result
        )
        result["strategy"] = Strategy.get()

        return result

    return wrapper


def replace_gray_splashscreen_with_gray(f):
    """
    Replaces 'GRAY_SPLASHSCREEN' value
    for *listname* field for queries like `graylist ip list`
    for compatibility with UI
    """

    @wraps(f)
    async def wrapper(*args, **kwargs):
        result = await f(*args, **kwargs)
        if not isinstance(result.get("items"), list):
            return result
        gray_splashscreen = IPList.GRAY_SPLASHSCREEN.lower()
        for item in result.get("items", []):
            if (
                isinstance(item, dict)
                and item.get("listname")
                and item["listname"].lower() == gray_splashscreen
            ):
                # use same case as it is
                item["listname"] = (
                    IPList.GRAY
                    if item["listname"].isupper()
                    else IPList.GRAY.lower()
                )
        return result

    return wrapper
