#!/usr/bin/env python3
"""
cij_testcases - Lists CIJOE testcases

Produces a HTML report with an overview of available testcases
"""
from __future__ import print_function
import argparse
import sys
import os
import dataclasses
from cij.reporter import tcase_parse_descr, dset_to_html
from cij.runner import TestCase
import cij.conf
import cij


def construct_dset(conf: cij.conf.Config) -> dict:
    """
    Create a dataset = { "group_names": [ testcase, .. , testcase ] }
    """

    dset = {
        "group_names": [],
    }

    for fname in cij.index(conf.testcases, "TCASES"):
        group = fname.split("_")[0]
        if group not in dset:
            dset[group] = []
            dset["group_names"].append(group)

        fpath = os.path.join(conf.testcases, fname)

        tcase = TestCase(
            fpath=fpath,
            name=fname,
            fname=fname,
            src_content=open(fpath, "r").read(),
        )

        descr, descr_long = tcase_parse_descr(tcase)

        tcase.descr = descr
        tcase.descr_long = descr_long

        dset[group].append(dataclasses.asdict(tcase))

    dset["group_names"].sort()

    for group in dset["group_names"]:
        dset[group] = sorted(dset[group], key=lambda k: k.get("name", ""))

    return dset


def parse_args():
    """Parse command-line arguments and conf for cij_testcases"""

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

    prsr = argparse.ArgumentParser(
        description='cij_testcases - Creates a report containing all testcases'
    )
    prsr.add_argument(
        '--template',
        help="Path to template",
        default=os.path.join(conf.templates, "testcases.html")
    )
    prsr.add_argument(
        '--output',
        help="Path to store testcase report",
        default=os.getcwd()
    )

    args = prsr.parse_args()

    # 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, conf


def main(args: argparse.Namespace, conf: cij.conf.Config) -> int:
    """Main entry point"""

    html_fpath = os.path.join(args.output, "testcases.html")

    cij.emph("html_fpath: %r" % html_fpath)

    dset = construct_dset(conf)

    try:

        with open(html_fpath, 'w') as html_fd:
            html = dset_to_html(dset, args.tmpl_fpath)
            html_fd.write(html)

    except (IOError) as exc:
        cij.err("Failed writing report to file, err: '%r'" % exc)
        return 1

    return 0


if __name__ == "__main__":
    ARGS, CONF = parse_args()

    if None in [ARGS, CONF]:
        sys.exit(1)

    sys.exit(main(ARGS, CONF))
