#!/usr/bin/env python

"""
Compare files in a normalized way. Used by create_test for
diffing non-namelist files.
"""

from standard_script_setup import *
import CIME.simple_compare
from CIME.utils import expect

import argparse, sys, os

###############################################################################
def parse_command_line(args, description):
###############################################################################
    parser = argparse.ArgumentParser(
usage="""\n{0} <Path to gold namelist file> <Path to non-namelist file> [-c <CASEBASEID>] [--verbose]
OR
{0} --help
OR
{0} --test

\033[1mEXAMPLES:\033[0m
    \033[1;32m# Compare files\033[0m
    > {0} baseline_dir/test/file mytestarea/file -c <CASE>
""".format(os.path.basename(args[0])),

description=description,

formatter_class=argparse.ArgumentDefaultsHelpFormatter
)

    CIME.utils.setup_standard_logging_options(parser)

    parser.add_argument("gold_file", help="Path to gold file")

    parser.add_argument("new_file", help="Path to file to compare against gold")

    parser.add_argument("-c", "--case", action="store", dest="case", default=None,
                        help="The case base id (<TESTCASE>.<GRID>.<COMPSET>). Helps us normalize data.")

    args = CIME.utils.parse_args_and_handle_standard_logging_options(args, parser)

    # Normalize case
    if (args.case is not None):
        args.case = CIME.utils.normalize_case_id(args.case)

    return args.gold_file, args.new_file, args.case

###############################################################################
def _main_func(description):
###############################################################################
    if ("--test" in sys.argv):
        CIME.utils.run_cmd_no_fail("python -m doctest {}/simple_compare.py -v".format(CIME.utils.get_python_libs_root(), arg_stdout=None, arg_stderr=None))
        return

    gold_file, compare_file, case = \
        parse_command_line(sys.argv, description)

    if (case is None):
        logging.warning("No case id data available, will not be able to normalize values as effectively")
    else:
        logging.info("Using case: '{}'".format(case))

    success, comments = CIME.simple_compare.compare_files(gold_file, compare_file, case)
    expect(success,
           "Diff between files {} and {}:\n{}".format(gold_file, compare_file, comments))

    print("Files {} and {} MATCH".format(gold_file, compare_file))

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

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