#!/usr/bin/env python
"""
    This script has been built to query the CMOR CVs to check for the presence of a given
    field type : field pair - i.e. is "CanESM5" and valid "source_id"?
"""
import argparse
import json
import sys
import os

def check_CV(field="", field_type="", quiet=False, cv_file="cmip6-cmor-tables/Tables/CMIP6_CV.json"):
    """Check if the entry defined by ``field`` and ``field_type`` is contained
       within the given ``cv_file``, exiting with a non-zero exit status if the 
       entry isn't found

        Parameters
        ----------
            field : string
                (required) the entry to be searched for
            field_type : string
                (required) the type of entry ``field`` is - one of "source_id", "activity_id", "experiment_id" or "sub_experiment_id"
            quiet : boolean
                (optional) set to True to supress all output - defaults to ``False``
            cv_file : str
                (optional) the CV file to query - defaults to "cmip6-cmor-tables/Tables/CMIP6_CV.json"
    """
    if not quiet:
        print("Checking for {} : {} in {}".format(field_type,field,cv_file))

    # open/load the CV
    if not os.path.isfile(cv_file):
        raise Exception("check_CVs: unable to find controlled vocabulary file : {}".format(cv_file))
    with open(cv_file,'r') as f:
        CV = json.load(f)['CV']
        
    # check for entry
    if field in CV[field_type]:
        if not quiet: print("Found!")
        sys.exit(0)
    else:
        if not quiet: print("Not Found!") 
        sys.exit(1)

def process_args(args):
    """Translate given arguments into dictionary
       
        Parameters 
        ----------
            args : argparse.Namespace object

        Returns
        -------
            arg_dict : dictionary 
                dictionary containing the processed argument list 
    """
    # initiate dict
    arg_dict = {} 

    # determine the field of interest
    if args.source_id:
        arg_dict['field_type']  = "source_id"
        arg_dict['field']       = args.source_id
    elif args.activity_id:
        arg_dict['field_type']  = "activity_id"
        arg_dict['field']       = args.activity_id
    elif args.experiment_id:
        arg_dict['field_type']  = "experiment_id"
        arg_dict['field']       = args.experiment_id
    elif args.subexperiment_id:
        arg_dict['field_type']  = "sub_experiment_id"
        arg_dict['field']       = args.subexperiment_id

    # set additional args
    arg_dict['quiet'] = args.quiet
    if args.cv_file:
        arg_dict['cv_file'] = args.cv_file

    # return
    return arg_dict
    
if __name__ == "__main__": 
    
    #---------------
    # define parser 
    #---------------
    prog_desc = "Check if the given field is contained in the CMOR controlled vocabularies (CVs)"
    parser = argparse.ArgumentParser(prog = "check_CVs", description = prog_desc)
    
    # make mutually exclusive arg group for fields to check
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument("--src", metavar="SOURCE ID", type=str, dest="source_id",
                                help="Model Source ID (i.e. CanESM5, CanESM5-CanOE)")
    group.add_argument("--act", metavar="ACTIVITY ID", type=str, dest="activity_id",
                                help="Activity ID (i.e. CMIP, AMIP)")
    group.add_argument("--exp", metavar="EXPERIMENT ID", type=str, dest="experiment_id",
                                help="Experiment ID (i.e. historical, piControl)")
    group.add_argument("--subexp", metavar="SUBEXPERIMENT ID", type=str, dest="subexperiment_id",
                                help="Subexperiment ID")

    # define additional optional arguments
    parser.add_argument("-q", "--quiet", action='store_true', default=False,
                                help="If used, suppress all output")
    parser.add_argument("--CV", metavar="CV FILE", type=str, dest="cv_file",
                                help=("File containing the controlled vocabulary. If not given ")+
                                     ("assumes cmip6-cmor-tables/Tables/CMIP6_CV.json"))
    
    #-----------------
    # ingest arguments
    #-----------------
    args = parser.parse_args()
    processed_args = process_args(args)

    #-----------
    # check CVs
    #-----------
    check_CV(**processed_args)
