#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" TcEx Framework Package Module """
import argparse
import sys
import traceback

import colorama as c
from tcex.bin import Package, Validate

# autoreset colorama
c.init(autoreset=True, strip=False)

parser = argparse.ArgumentParser()
parser.add_argument('--bundle', action='store_true', help='Build a bundle file.')
parser.add_argument(
    '--exclude', action='append', default=[], help='File and directories to exclude from build.'
)
parser.add_argument(
    '--ignore_validation', action='store_true', help='Do not exit on validation errors.'
)
parser.add_argument('--json_output', action='store_true', help='Return output in JSON format.')
parser.add_argument(
    '--install_json', help='The install.json file name for the App that should be built.'
)
parser.add_argument(
    '--outdir', default='target', help='Directory to write the outfile. (Default: target)'
)
args, extra_args = parser.parse_known_args()


if __name__ == '__main__':
    try:
        # validate App
        tcv = Validate(args)
        tcv.update_system_path()
        tcv.check_syntax()
        tcv.check_imports()
        tcv.check_install_json()
        tcv.check_layout_json()
        if not args.json_output:
            tcv.print_results()
        if tcv.exit_code != 0:
            sys.exit(tcv.exit_code)

        # set exit code for tc package
        tcp = Package(args)
        tcp.validation_data = tcv.validation_data
        tcp.package()
        if args.json_output:
            tcp.print_json()
        else:
            tcp.print_results()

        # exit command with appropriate exit code
        sys.exit(tcp.exit_code)
    except Exception:
        # TODO: Update this, possibly raise
        print(f'{c.Style.BRIGHT}{c.Fore.RED}{traceback.format_exc()}')
        sys.exit(1)
