#!python

"""
Create the html files needed to describe the versioning
information for a set of libraries and executables in
pycbc results pages
"""

import argparse
import logging

import pycbc
from pycbc.results import (
    get_code_version_numbers,
    get_library_version_info,
    html_escape,
    save_fig_with_metadata,
)

logger = logging.getLogger(__name__)

parser = argparse.ArgumentParser()
pycbc.add_common_pycbc_options(parser)
parser.add_argument(
    "--executables",
    nargs="+",
    required=True,
    help="List of executables to provide version information for",
)
parser.add_argument(
    "--executables-names",
    nargs="+",
    required=True,
    help="Names of the executables, must be in the same order as --executables-files",
)
parser.add_argument(
    "--output-file", required=True, help="The directory for output html snippets"
)
args = parser.parse_args()

pycbc.init_logging(args.verbose)

if not len(args.executables) == len(args.executables_names):
    raise parser.error(
        "--executables-files and executables-names must be the same number of arguments"
    )


logger.info("Getting version information for libraries")
library_list = get_library_version_info()
html_text = ""
for curr_lib in library_list:
    lib_name = curr_lib["Name"]
    logger.info("Getting %s information", lib_name)
    html_text += f"<h2>{lib_name} Version Information</h2>:<br>\n"
    for key, value in curr_lib.items():
        html_text += f"<li> {key} : {value} </li>\n"


code_version_dict = get_code_version_numbers(args.executables_names, args.executables)

html_text += "<h2>Version Information from Executables</h2>:<br>\n"
for key, value in code_version_dict.items():
    value_html = str(value).replace("@", "&#64;")
    html_text += f"<li><b>{key}</b>:<br><pre>{value_html}</pre></li><hr><br><br>\n"

kwds = {
    "render-function": "render_text",
    "title": "Version Information",
}

save_fig_with_metadata(html_escape(html_text), args.output_file, **kwds)
logger.info("Done")
