import json
import random
import time
from typing import Union
import pathlib


def save_json_file(json_file: Union[str, pathlib.Path], dictionary_to_save: dict, retries: int = 3) -> None:
    """
    Writes a new JSON file to disk. If the file exists, it will be overwritten.
    :param json_file: JSON file to write into
    :param dictionary_to_save:
    :param retries: If file is locked for any reason, retry writing this number of times
    :return: None
    """

    assert isinstance(retries, int), "Retries parameter must be an integer"
    assert retries >= 0, "Retries must be a positive integer"
    assert isinstance(json_file, (str, pathlib.Path)), "json_file must be a pathlib.Path() or a string path"
    file_path = pathlib.Path(json_file)
    while retries >= 0:
        retries -= 1
        try:
            with file_path.open("w") as file:
                return json.dump(dictionary_to_save, file, ensure_ascii=False)
        except PermissionError:
            wait_time = random.random()
            time.sleep(wait_time)
    raise PermissionError(f"Permission issue while writing JSON: {file_path}")