import requests


def get_matches(
    ip_address: tuple[str, int], error_message: str
) -> list[tuple[str, str, float]]:
    """
    Find matches for an error message in the discussion threads.
    """
    ip, port = ip_address
    response = requests.post(
        f"{ip}:{port}/threads/matches",
        json={"text": error_message},
        timeout=10,
    )
    response.raise_for_status()
    return response.json()["matches"]


def get_formatted_matches(ip_address: tuple[str, int], error_message: str) -> str:
    """
    Get formatted matches for an error message in the discussion threads.

    Args:
        ip_address: The IP address and port of the Flask server.
        error_message: The error message to find matches for.

    Returns:
        A string with the matches formatted as a list of links, or an
        empty string if there are no matches.
    """
    output = ""
    try:
        matches = get_matches(ip_address, error_message)
        if len(matches):
            formatted = "\n\t".join(f"{title}: {link}" for title, link, _ in matches)
            output += (
                "\nOther students may be experiencing a similar issue. "
                "These threads on Ed may be useful: \n"
            )
            output += f"\t{formatted}\n"
    except Exception:  # pylint: disable=broad-exception-caught
        pass
    return output or None
