#!/usr/bin/env python
import argparse
import sys
from analyze import AnalysisDataValidation, analyze, analyze_validation
from custom import do_custom
from download_data import retrieve_data
from validate_local_data import validate_local_data
from classify.classifyhelp import show_classification_help
from save import save_classification_rules


def run_analyze(sysargv: str):
    parser = argparse.ArgumentParser(description='Run entire analysis')
    parser.add_argument("-s", "--summary", action="store_true",
                        help="Print summary analysis only")
    parser.add_argument("-m", "--monthly", action="store_true",
                        help="Print monthly analysis only")
    parser.add_argument("-c", "--cutoff", type=int, default=12,
                        help="Specify how many months back to perform analysis")
    parser.add_argument("-e", "--spreadsheet",
                        action="store_true", help="Output a spreadsheet file")

    args = parser.parse_args(sysargv)
    if args.summary and args.monthly:
        print("--summary and --monthly cannot be present at the same time")
        exit(1)

    validation_results = analyze_validation()
    if validation_results != AnalysisDataValidation.SUCCESS:
        if validation_results == AnalysisDataValidation.MISSING_DATA:
            print("Data is not available, use `src/run download` to download data")
        elif validation_results == AnalysisDataValidation.DATA_ERRORS:
            print("Data has errors, use `src/run validate` to see validation errors")
        else:
            print("Some unknown validation error occurred")
        exit(1)

    analyze(summaryonly=args.summary, monthlyonly=args.monthly,
            cutoffmonths=int(args.cutoff), spreadsheetout=args.spreadsheet)


def run_custom(sysargv: str):
    parser = argparse.ArgumentParser(description='Run custom thing', usage='')
    parser.add_argument("-c", "--cutoff", type=int, default=12,
                        help="Specify how many months back to perform analysis")
    args = parser.parse_args(sysargv)
    do_custom(int(args.cutoff))


def run_download(sysargv: str):
    retrieve_data()


def run_validate(sysargv: str):
    validate_local_data()


def run_classify(sysargv: str):
    parser = argparse.ArgumentParser(
        description='Helps fix classification errors by listing the errors and showing all categories of classification')
    parser.add_argument("-c", "--categories", action="store_true",
                        help="Only print classification categories")

    args = parser.parse_args(sysargv)
    show_classification_help(args.categories)


def run_save(sysargv: str):
    save_classification_rules()


parser = argparse.ArgumentParser(description='run finance analysis', usage='''

    Commands available:
        analyze     Run financial analysis
        custom      Run custom stuff
        download    Download data
        validate    See data validation errors
        classify    Manage classification errors
        save        Saves classification rules
''')

commands = {
    "analyze": run_analyze,
    "custom": run_custom,
    "download": run_download,
    "validate": run_validate,
    "classify": run_classify,
    "save": run_save,
}

parser.add_argument("command", help="Subcommand to run")

# parse_args defaults to [1:] for args, but you need to
# exclude the rest of the args too, or validation will fail
args = parser.parse_args(sys.argv[1:2])
if not args.command in commands:
    print('Unrecognized command')
    parser.print_help()
    exit(1)

# use dispatch pattern to invoke method with same name
commands[args.command](sys.argv[2:])
