#!/usr/bin/env python3

"""
Populates a netcdf file adding requested variables, either importing them
from another file, or by computing them as function of other existing ones.
"""

from utils import check_minimum_python_version
check_minimum_python_version(3, 4)

import argparse, sys, pathlib

from compare_nc_files import CompareNcFiles

###############################################################################
def parse_command_line(args, description):
###############################################################################
    parser = argparse.ArgumentParser(
        usage="""\n{0} <ARGS> [--verbose]
OR
{0} --help

\033[1mEXAMPLES:\033[0m

    \033[1;32m# Compares array A1 and A2 in file a.nc with array B1 and B2 in b.nc

        > ./{0} -s a.nc -t b.nc -c A1=B1 A2=B2

    \033[1;32m# Compares scalar value A(1,2) in file a.nc with B(4,2,1) in b.nc (notice ' is needed in bash when using '()' )

        > ./{0} -s a.nc -t b.nc -c 'A(1,2)=B(4,2,1)'

    \033[1;32m# Compares 1d array A(:,2) in file a.nc with 1d array B(4,2,:) in b.nc (notice ' is needed in bash when using '()' )

        > ./{0} -s a.nc -t b.nc -c 'A(:,2)=B(4,2,:)'

""".format(pathlib.Path(args[0]).name),
        description=description,
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )

    # The name of the nc files where to grab data from
    parser.add_argument("-s","--src-file", type=str, required=True,
            help="Name of the source netcdf file")
    parser.add_argument("-t","--tgt-file", type=str,
            help="Name of the target netcdf file")

    # Variables comparison
    parser.add_argument("-c","--compare",nargs='+', default=[],
                        help="Compare variables from src file against variables from tgt file")

    return parser.parse_args(args[1:])

###############################################################################
def _main_func(description):
###############################################################################
    pncf = CompareNcFiles(**vars(parse_command_line(sys.argv, description)))

    cmp_str = '\n      - ' + '\n      - '.join(pncf._compare)
    print (f" **** Comparing nc files **** \n"
           f"  src file: {pncf._src_file}\n"
           f"  tgt file: {pncf._tgt_file}\n"
           f"  comparisons: {cmp_str}")
    success = pncf.run()

    print("Comparisons result: {}".format("SUCCESS" if success else "FAIL"))

    sys.exit(0 if success else 1)

###############################################################################

if (__name__ == "__main__"):
    _main_func(__doc__)
