#!/usr/bin/env python3
"""
Application for tracking GCP costs. It runs BigQuery queries on a billing
data set looking for resources with a specific label and reports aggregate
cost.

Author: Greg Boratyn boratyng@ncbi.nlm.nih.gov
"""

import argparse
import sys
from elb.cost import get_cost, DFLT_BQ_DATASET, DFLT_BQ_TABLE
from elb.cost import BQ_ERROR, NO_RESULTS_ERROR, CMD_ARGS_ERROR


def parse_arguments():
    """Parse command line arguments"""
    parser = argparse.ArgumentParser(description='GCP cost tracking application, provides aggregate cost for resources with a specific label.')
    parser.add_argument(metavar='RUN-LABEL', dest='label', type=str,
                        help='Run label, must be of the form <key>:<value>')
    parser.add_argument('--date-range', metavar='STRING', dest='date_range',
                        type=str, help='Search for costs only between given '
                        ' dates. Date range format: yyyy-mm-dd:yyyy-mm-dd.'
                        ' Using date range makes search faster and'
                        ' cheaper.')
    parser.add_argument('--dataset', metavar='STRING', dest='dataset',
                        type=str, default=DFLT_BQ_DATASET,
                        help='BigQuery dataset to search for costs')
    parser.add_argument('--table', metavar='STRING', dest='table', type=str,
                        default=DFLT_BQ_TABLE, help='BigQuery table to search')
    parser.add_argument('--verbose', dest='verbose', action='store_true',
                        help='Print additional informaton')
    return parser.parse_args()

def main():
    """The main function, entry point of the program"""
    # parse command line parameters
    args = parse_arguments()

    # label is a mandatory parameter
    if not args.label:
        print('Error: Run label not provided', file=sys.stderr)
        return CMD_ARGS_ERROR
    
    try:
        cost = get_cost(args.label, args.date_range, args.dataset, args.table,
                        args.verbose)
    except ValueError as e:
        print(f'Error: {e}', file=sys.stderr)
        return CMD_ARGS_ERROR
    except RuntimeError as e:
        print(f'{e}', file=sys.stderr)
        return BQ_ERROR

    if not cost:
        print(f'Error: There are no results for run labeled "{args.label}". Please, make sure that label is spelled correctly, you are using the correct GCP project, BigQuery dataset, and table, as well as date range, if used was set properly.', file=sys.stderr)
        return NO_RESULTS_ERROR

    # We could have summed the cost in SQL, but then we would not be able to
    # tell the difference between zero cost and no records found.
    print('${:.2f}'.format(sum(cost)))
    return 0

        
if __name__ == '__main__':
    sys.exit(main())
