import argparse
import json
import logging
from airflow.models import Variable


def update_defaults(conn_id: str, output: list=None, remove=False):
    try:
        var = json.loads(Variable.get(key=conn_id, default_var={}, deserialize_json=True))
        if output is not None:
            var['output'] = output
        elif remove and 'output' in var:
            var.pop('output')
        Variable.set(key=conn_id, value=json.dumps(var), serialize_json=True)
        var = Variable.get(key=conn_id, default_var={}, deserialize_json=True)
        logging.info("set Variable {conn_id} to value {var}".format(**locals()))
    except KeyError as e:
        logging.error("could not find key {conn_id} in airflow Variable: {e}".format(**locals()))
        raise

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="update a defaults etl dag to zenyatta",
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    # python update_dag_defaults --rds-id chat_depot --output-format csv /--remove
    parser.add_argument('--rds-id', required=True, dest='conn_id', action='store', help='RDS identifier')
    parser.add_argument('--output-format', required=False, type=str, nargs='*', action='store',
                        dest="output_format", help='a list add in airflow Variable for db output format')
    parser.add_argument('--remove', required=False, dest='remove', action='store_true',
                        help='remove output field')
    args = parser.parse_args()
    if args.output_format:
        update_defaults(args.conn_id + '_defaults', output=args.output_format)
    elif args.remove:
        update_defaults(args.conn_id + '_defaults', remove=True)
    else:
        logging.info("please provide a valid action")
