"""
osidb-bindings helpers
"""

import json
from os import getenv
from typing import Any

from .exceptions import OSIDBBindingsException

_MAP = {
    "y": True,
    "yes": True,
    "t": True,
    "true": True,
    "on": True,
    "1": True,
    "n": False,
    "no": False,
    "f": False,
    "false": False,
    "off": False,
    "0": False,
}


def strtobool(value: str) -> bool:
    try:
        return _MAP[str(value).lower()]
    except KeyError:
        raise ValueError('"{}" is not a valid bool value'.format(value))


def get_env(
    key: str,
    default: str | None = None,
    is_bool: bool = False,
    is_int: bool = False,
    is_json: bool = False,
) -> Any:
    """get environment variable"""
    if (is_bool and is_int) or (is_bool and is_json) or (is_int and is_json):
        raise OSIDBBindingsException(
            "Expected environment variable cannot be of multiple types at the same time"
        )

    value = getenv(key, default)
    # consider empty string as empty value
    # as setting the value to non-existing env variable
    # in compose.yml results in an empty string
    if value == "":
        value = default

    if is_bool:
        value = bool(strtobool(value))
    if is_int:
        value = int(value)
    if is_json:
        value = json.loads(value)

    return value


def parse_version_key(version_str: str) -> tuple[int, int]:
    """
    A helper function to create a sortable key from version string
    """

    if version_str.endswith("beta"):
        is_final = 0  # Beta release
        number_part = version_str[1:-4]
    else:
        is_final = 1  # Final release
        number_part = version_str[1:]

    major_num = int(number_part)
    return major_num, is_final
