#!/usr/bin/env python3
"""
 CIJOE test reporter
"""
from __future__ import print_function
import argparse
import sys
import os
import cij.reporter
import cij.runner
import cij.util
import cij.conf
import cij


def parse_args():
    """Parse command-line arguments for cij_reporter"""

    conf = cij.conf.from_system()
    if conf is None:
        cij.err("rprt: failed retrieving CIJOE configuration")
        return None

    # Parse the Command-Line
    prsr = argparse.ArgumentParser(
        description='cij_reporter - CIJOE Test Runner',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    prsr.add_argument(
        '--output',
        help="Path to test output",
        default=os.getcwd()
    )
    prsr.add_argument(
        '--template',
        help="Path to report template",
        default=os.path.join(conf.templates, "report.html")
    )
    prsr.add_argument(
        '--force',
        help="Overwrite possibly existing report",
        action='store_true'
    )
    args = prsr.parse_args()

    args.output = cij.util.expand_path(args.output)
    if not os.path.exists(args.output):
        cij.err("rprtr:output: %r, does not exist" % args.output)
        return None

    args.trun_fpath = cij.runner.yml_fpath(args.output)
    if not os.path.exists(args.trun_fpath):
        cij.err("rprtr:trun_fpath: path: %r does not exist" % args.trun_fpath)
        return None

    args.template = cij.util.expand_path(args.template)
    if not os.path.exists(args.template):
        cij.err("rprtr:template: %r, does not exist" % args.template)
        return None

    # Expand and construct template paths
    args.tmpl_fpath = args.template
    args.tmpl_fname = os.path.basename(args.tmpl_fpath)
    args.tmpl_name = os.path.splitext(args.tmpl_fname)[0]

    return args


def main():
    """
    Parse environment variables and command-line arguments constructing a
    configuration for which to invoke the reporter
    """

    args = parse_args()
    if args is None:
        cij.err("rprtr: failed parsing command-line args")
        return 1

    rcode = cij.reporter.main(args)
    if rcode:
        cij.err("rprtr: rcode: %r, error while creating report" % rcode)

    return rcode


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