"""Current file format for the various text only notebook extensions"""

import os

FILE_FORMAT_VERSION = {
    # R markdown format
    '.Rmd': '1.0',
    # Version 1.0 on 2018-08-22 - jupytext v0.5.2 : Initial version

    # Markdown format
    '.md': '1.0',
    # Version 1.0 on 2018-08-31 - jupytext v0.6.0 : Initial version

    # Python and Julia scripts
    '.py': '1.2',
    '.jl': '1.2',
    # Version 1.2 on 2018-09-05 - jupytext v0.6.3 : Metadata bracket can be
    # omitted when empty, if previous line is empty #57
    # Version 1.1 on 2018-08-25 - jupytext v0.6.0 : Cells separated with one
    # blank line #38
    # Version 1.0 on 2018-08-22 - jupytext v0.5.2 : Initial version

    # Python scripts
    '.R': '1.0',
    # Version 1.0 on 2018-08-22 - jupytext v0.5.2 : Initial version
}

MIN_FILE_FORMAT_VERSION = {'.Rmd': '1.0', '.md': '1.0', '.py': '1.1',
                           '.jl': '1.1', '.R': '1.0'}

FILE_FORMAT_VERSION_ORG = FILE_FORMAT_VERSION


def file_format_version(ext):
    """Return file format version for given ext"""
    return FILE_FORMAT_VERSION.get(ext)


def min_file_format_version(ext):
    """Return minimum file format version for given ext"""
    return MIN_FILE_FORMAT_VERSION.get(ext)


def check_file_version(notebook, source_path, outputs_path):
    """Raise if file version in source file would override outputs"""
    _, ext = os.path.splitext(source_path)
    current = file_format_version(ext)
    version = notebook.metadata.get('jupytext_format_version')
    if version:
        del notebook.metadata['jupytext_format_version']

    # Missing version, still generated by jupytext?
    if notebook.metadata and not version:
        version = current

    # Same version? OK
    if version == current:
        return

    # Version larger than minimum readable version
    if version <= current and version >= min_file_format_version(ext):
        return

        # Not merging? OK
    if source_path == outputs_path:
        return

    raise ValueError("File {} has jupytext_format_version={}, but "
                     "current version for that extension is {}.\n"
                     "It would not be safe to override the source of {} "
                     "with that file.\n"
                     "Please remove one or the other file."
                     .format(os.path.basename(source_path),
                             version, current,
                             os.path.basename(outputs_path)))
