import json


def try_to_replace_line_json(line, json_type, new_json, json_prefix=""):
    """Attempts to replace a JSON declaration if it's on the line.

    Parameters
    ----------
    line: str
       A line from a JavaScript code file. It's assumed that, if it declares
       a JSON, this declaration will only take up one line (i.e. it
       will be of the form
       "[whitespace?]var [JSON prefix?][JSON name] = {JSON contents};").

       If a replacement is made, everything on and after the { in this line
       will be replaced with the contents of the new JSON, followed by
       ";\n".

    json_type: str
       One of "rank", "sample", or "count". Other values will result in a
       ValueError being thrown.

    new_json: dict
       A JSON to try replacing the current variable declaration (if present)
       on the input line with.

    json_prefix: str (default value: "")
       An optional prefix that will be appended to any JSON names we try to
       replace. If this is anything but "", this *won't replace normal JSON
       lines* (e.g. "var rankPlotJSON = {") -- instead, this will only
       replace lines with the given prefix (e.g. if the prefix is "SST",
       then only JSON lines of the format "var SSTrankPlotJSON = {" will be
       replaced.

    Returns
    -------
    (line, replacement_made): str, bool
       If no replacement was made, replacement_made will be False and line
       will just equal to the input line.

       If a replacement was made, replacement_made will be True and line
       will be equal to the new line with the JSON replaced.
    """

    prefixToReplace = ""
    if json_type == "rank":
        prefixToReplace = "var {}rankPlotJSON = {{"
    elif json_type == "sample":
        prefixToReplace = "var {}samplePlotJSON = {{"
    elif json_type == "count":
        prefixToReplace = "var {}countJSON = {{"
    else:
        raise ValueError(
            "Invalid json_type argument. Must be 'rank', "
            "'sample', or 'count'."
        )

    prefixToReplace = prefixToReplace.format(json_prefix)

    if line.lstrip().startswith(prefixToReplace):
        return (
            (
                line[: line.index("{")]
                + json.dumps(new_json, sort_keys=True)
                + ";\n"
            ),
            True,
        )
    return line, False