from pathlib import Path
import json


def merge_citations_crossref_into_metadata(
        input_citations_crossref_file,
        output_metadata_file,
        revision_index=None,
        write_output=False, verbose=False):
    """
    Add to an existing output_metadata_file (metadata.json) file the contents
    of the _citations_crossref_file, which has been created by query_crossref_xxx
    scripts.
    Parameters
    ----------
    input_citations_crossref_file: Str (Path)
        Input file `a_name_citations_crossref.json` generated using
        scripts `query_crossref_xxx.py`
    output_metadata_file: Str (Path)
        Path to the metadata.json file, used by gatsby to generate the publication page.
    revision_index: int
        The revision index to update, if None (default), use the last one.
        Be aware that the revision number in the old database might not be the same
        in the new one.
        We treat the old database as inmutable, and we only upload the last revised article.
        Future publications in the IJ should be more dynamic.
    write_output: Bool
        Write the updated metadata with the citations into the output_metadata_file.
    verbose: Bool
        Extra info printed to stdout
    Returns
    -------
    The updated metadata, if write_output is True, also updates the content of the metadata file.
    """

    input_citations_crossref_path = Path(input_citations_crossref_file).expanduser()
    if not input_citations_crossref_path.exists():
        print("citations_crossref_file does not exist {}".format(input_citations_crossref_file))
        raise Exception("citations_crossref_file does not exist.")

    output_metadata_path = Path(output_metadata_file).expanduser()
    if not output_metadata_path.exists():
        print("Output metadata file does not exist: {}".format(output_metadata_path))
        raise Exception("Output metadata file does not exist.")

    with open(input_citations_crossref_file, 'r') as fp:
        citation_list = json.load(fp=fp)
    with open(output_metadata_file, 'r') as fp:
        metadata = json.load(fp=fp)

    revisions = metadata["publication"]["revisions"]
    num_existing_revisions = len(revisions)
    if num_existing_revisions == 0:
        raise Exception("publication does not have any revision")
    max_index_existing_revisions = num_existing_revisions - 1

    if not revision_index:
        # Use the last one
        revision_index = max_index_existing_revisions
    else:
        if revision_index > max_index_existing_revisions:
            raise Exception("revision_index {} is greater than the max index allowed for the number of existing revisions {}".format(revision_index, max_index_existing_revisions))

    metadata["publication"]["revisions"][revision_index]["citation_list"] = citation_list

    # if verbose:
    #     json.dump(metadata["publication"]["revisions"][revision_index], fp=sys.stdout, indent=2)
    #     print()

    if write_output:
        with open(output_metadata_file, 'w') as fp:
            json.dump(metadata, fp, sort_keys=True, indent=2)

    return metadata