from pathlib import Path


def save_options_to_config(filepath, opt, unknown=None):
    """
    Saves the parsed options to a config file to be used as arguments.

    Args:
        filepath: path to write the config file to.
        opt: parsed known options.
        unknown: unknown options (only safe for non-commandline parameters).
    """
    def _to_key_value_str(key, value):
        if value is None:
            value = ''  # defined as empty (see dict_parser._convert_config_items)
        elif isinstance(value, (str, Path)):
            value = f'"{value}"'
            if "\n" in value:
                value = value.replace("\n", "\n    ")  # spaces in new line indicate continuation
        return f"{key} = {value}\n"

    lines = "[DEFAULT]\n"
    for o in opt:
        lines += _to_key_value_str(o, opt[o])

    if unknown is not None and len(unknown):
        lines += "; Unknown options --------------------------\n"
        if isinstance(unknown, dict):
            for o in unknown:
                lines += _to_key_value_str(o, unknown[o])
        else:
            lines += f"; {' '.join(unknown)}\n"

    with open(filepath, "w") as f:
        f.write(lines)