#!/usr/bin/env python
"""
 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

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

    cij_evars = cij.paths_from_env("CIJ", ["TEMPLATES"])
    for key, val in cij_evars.items():
        if val is None:
            cij.err(
                "rprtr:rprtr: failed parsing environment variable 'CIJ_%s'" %
                key
            )
            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.sep.join([cij_evars["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: %r" % 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())
