from qgis.core import Qgis
from qgis.utils import iface, plugins

from oslandia.toolbelt import PlgLogger


def get_plugins_installed() -> list:
    """Get qgis plugins installed in current profile

    :return: List of QGIS Plugins installed
    :rtype: list
    """

    return list(plugins.keys())


def get_plugin_pretty_name(plugin_name: str) -> str | None:
    """If a plugin is installed, this retrieves the plugin's pretty name.
    Example :
    name = pyqgis_resource_browser
    pretty_name = PyQGIS Resource Browser

    :param plugin_name: Plugin name
    :type plugin_name: str
    :return: Plugin pretty name
    :rtype: str
    """

    if plugin_name in get_plugins_installed():
        try:
            # WARNING :
            # Please note that for some reason this command will return nothing if a
            # QGIS_PLUGINPATH variable is defined in the profile and the user has never
            # launched the plugin manager in the current session.
            return iface.pluginManagerInterface().pluginMetadata(plugin_name)["name"]
        except Exception as err:
            PlgLogger.log(
                message="Impossible to determine the pretty name of the plugin "
                f"{plugin_name}. Trace: {err}",
                push=False,
                log_level=Qgis.MessageLevel.Warning,
            )
    return None


def is_installed_plugin(plugin_name: str, is_pretty_name: bool = False) -> bool:
    """Checks if a given plugin is installed.

    :param plugin_name: Name of the plugin to check
    :type plugin_name: str
    :param is_pretty_name: The given name is the pretty name, defaults to False
    :type is_pretty_name: bool, optional
    :return: True if the plugin is installed, False otherwise.
    :rtype: bool
    """

    if is_pretty_name:
        return plugin_name in [
            get_plugin_pretty_name(element) for element in get_plugins_installed()
        ]

    return plugin_name in get_plugins_installed()
