#!/usr/bin/env python
"""
Common functions for badge management.
"""

import urllib.parse


def get_badge_url(label, message, color, **query_params):
    """
    Get a URL to an SVG image of a custom badge generated by the img.shields.io
    website.

    Args:
        label:
            The text on the left side of the badge.

        message:
            The text on the right side of the badge.

        color:
            The hexadecimal color code for the background of the message.

        query_params:
            Additional query parameters for the img.shields.io URL.

    Returns:
        The image URL as a string.
    """
    for char, escape in (("_", "__"), (" ", "_"), ("-", "--")):
        label = label.replace(char, escape)
        message = message.replace(char, escape)
    if query_params:
        query_params = (
            f"{urllib.parse.quote(k)}={urllib.parse.quote(v)}"
            for (k, v) in query_params.items()
        )
        query_params = "&".join(query_params)
        query_params = f"?{query_params}"
    else:
        query_params = ""
    return f"https://img.shields.io/badge/{label}-{message}-{color}.svg{query_params}"
